Spring Boot 2.X: Custom registration Servlet, Filter, Listener

Preface

The web.xml file has been removed from Spring Boot. If you need to register and add Servlet, Filter and Listener as Spring Bean, there are two ways in Spring Boot:

  • Annotation @ WebServlet, @ WebFilter, @Listener Used to configure.
  • Spring Boot JavaConfig annotation is used to configure the Bean.

Before registration

When using Servlet, you need to add @ ServletComponentScan annotation to the Spring Boot entry class to tell Spring Boot to scan the Servlet, Filter and Listener registered below.

@SpringBootApplication
@ServletComponentScan
public class SpringBootServletApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootServletApplication.class, args);
	}

}

Register Servlet

1.@WebServlet property

attribute type describe
name String Specify the Servlet name, which is equivalent to < Servlet name >
value String[] Equivalent to the urlPatterns property, both should not be used at the same time
urlPatterns String[] Specifies the URL matching pattern for a set of servlets. Equivalent to < URL pattern > tag
loadOnStartup int Specifies the order in which servlets are loaded, equivalent to the < load on startup > tag
initParams WebInitParam[] Specifies a set of Servlet initialization parameters, equivalent to the < init param > tag
asyncSupported boolean Declare whether the Servlet supports asynchronous operation mode, equivalent to the < async supported > tag
smallIcon String Small icon for this Servlet
largeIcon String Large icon for this Servlet
description String The description information of the Servlet is equivalent to the < description > tag
displayName String The display name of the Servlet, usually used with tools, is equivalent to the < display name > label

2. example

@WebServlet(urlPatterns = "/TestServlet")
public class TestServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3325041776508043481L;

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doPost(req, resp);
	}
    /*
    *  Implement request uri and header printing, and return another json
    */
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("RequestURI:" + req.getRequestURI());

		System.out.println("Request Headers:");

		StringBuilder sb = new StringBuilder();
		Enumeration<?> names = req.getHeaderNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement().toString();
			Enumeration<?> hs = req.getHeaders(name);
			sb.append(name).append(":");
			while (hs.hasMoreElements()) {
				sb.append(hs.nextElement()).append(";");
			}
		}
		System.out.println(sb);
		
		ObjectMapper om=new ObjectMapper();
		UserEntity user=new UserEntity();
		user.setId(1L);
		user.setUserName("zwqh");
		user.setUserSex("male");
		user.setHeaders(sb.toString());
		String resultJson=om.writeValueAsString(user);

		resp.setContentType("application/json;charset=UTF-8");
		
		resp.getWriter().print(resultJson);
	}

}

Where @ WebServlet(urlPatterns = "/TestServlet") is equivalent to the following code:

<servlet>
<!-- Class name -->
<servlet-name> TestServlet </servlet-name>
<!-- The package -->
<servlet-class> cn.zwqh.springbboot.servlet.TestServlet </servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name> TestServlet </servlet-name>
   <!-- Visiting url Path address -->
   <url-pattern> /TestServlet </url-pattern>
</servlet-mapping>

3. test

Browser access http://127.0.0.1:8080/TestServlet Log output:

Register Filter

1.@WebFilter property

attribute type describe
filterName String Specify the Filter name, which is equivalent to < Filter name >
value String[] Equivalent to the urlPatterns property, both should not be used at the same time
urlPatterns String[] Specifies the URL matching pattern for a set of filters. Equivalent to < URL pattern > tag
servletNames String[] Specifies which servlets the filter will be applied to. Take the value of the name attribute in @ web Servlet or the value of < Servlet name > in web.xml
initParams WebInitParam[] Specify a set of Filter initialization parameters, equivalent to the < init param > tag
dispatcherTypes DispatcherType[] Specifies the forwarding mode of the Filter, including: ASYNC, ERROR, FORWARD, INCLUDE, REQUEST
asyncSupported boolean Declare whether the Filter supports asynchronous operation mode, equivalent to the < async supported > tag
smallIcon String Small icon for this Filter
largeIcon String Large icon for this Filter
description String Description information of the Filter, equivalent to < description > label
displayName String The display name of the Filter, usually used with tools, is equivalent to the < display name > label

2. example

@WebFilter(urlPatterns = { "/TestServlet" }) // Register interceptor and add interception path '/ TestServlet'
public class TestFilter implements Filter {

	/**
	 * Initialization, only executed once when the project is started
	 */
	@Override
	public void init(FilterConfig filterConfig) {
		System.out.println("===> TestFilter init");
	}
	/**
	* Business logic implementation code for storing filters
	*/
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		chain.doFilter(request, response);// Boundary between processing request and response
		System.out.println("===> chain.doFilter Post execution processing response Related methods of");
		// Set a token in the response header
		setToken(response);

	}

	private void setToken(ServletResponse response) {
		HttpServletResponse res = (HttpServletResponse) response;
		String token = UUID.randomUUID().toString();
		res.setHeader("Token", token);
		System.out.println("===> Set up token: " + token);
	}

	/**
	 * Destruction is called before the project is closed and the Servlet container is destroyed.
	 */
	@Override
	public void destroy() {
		System.out.println("===> TestFilter destroy");
	}

}

3. test

Browser access http://127.0.0.1:8080/TestServlet : Log printing:

4. Main use scenarios of filter

  • Disable browser caching (processing of caching)
  • Solve the problem of Chinese code disorder
  • Login authentication and authority management
  • User authorization is responsible for checking the user's request and filtering the user's illegal request according to the request
  • Logging, recording some special user requests in detail
  • Other scenes

Register Listener

1.@Listener property

attribute type describe
value String Description of Listener

2. example

Monitor related to ServletContext

The Listener of Servlet is a server-side program that implements the javax.servlet.ServletContextListener interface. It starts with the start of Web application, initializes only once, and destroys with the stop of Web application. Its main function is to add some initialization contents, such as parameters and objects.

@WebListener
public class ContextListener implements ServletContextListener, ServletContextAttributeListener{

	public static final String INITIAL_CONTENT = "Content created in servlet Context";

	/**
	 * ServletContext Establish
	 */
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("===> context initialized");
		ServletContext servletContext = sce.getServletContext();
		servletContext.setAttribute("content", INITIAL_CONTENT);
	}

	/**
	 * ServletContext Destruction
	 */
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("===> context destroyed");
	}

	/**
	 * context Attribute added
	 */
	@Override
	public void attributeAdded(ServletContextAttributeEvent scae) {
		System.out.println("===> context attribute added");
	}

	/**
	 * context Attribute Removal
	 */
	@Override
	public void attributeRemoved(ServletContextAttributeEvent scae) {
		System.out.println("===> context attribute removed");
	}

	/**
	 * context Attribute substitution
	 */
	@Override
	public void attributeReplaced(ServletContextAttributeEvent scae) {
		System.out.println("===> context attribute replaced");
	}
}
HttpSession related listening
@WebListener
public class SessionListener implements HttpSessionListener, HttpSessionIdListener, HttpSessionAttributeListener,
		HttpSessionActivationListener {

	/**
	 * session When created
	 */
	@Override
	public void sessionCreated(HttpSessionEvent se) {
		System.out.println("===> session created");
	}

	/**
	 * session When destroyed
	 */
	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		System.out.println("===> session destroyed");
	}

	/**
	 * sessionId change
	 */
	@Override
	public void sessionIdChanged(HttpSessionEvent se, String oldSessionId) {
		System.out.println("===> session id changed");
	}

	/**
	 * session Attribute added
	 */
	@Override
	public void attributeAdded(HttpSessionBindingEvent se) {
		System.out.println("===> session attribute added");
	}

	/**
	 * session Attribute Removal
	 */
	@Override
	public void attributeRemoved(HttpSessionBindingEvent se) {
		System.out.println("===> session attribute removed");
	}

	/**
	 * session Attribute substitution
	 */
	@Override
	public void attributeReplaced(HttpSessionBindingEvent se) {
		System.out.println("===> session attribute replaced");
	}
	/**
	 * session Passivation, the process of writing data from memory to a hard disk.
	 */
	@Override
	public void sessionWillPassivate(HttpSessionEvent se) {
		System.out.println("===> session will passivate");
	}
	/**
	 * session To restore the hard disk data to memory.
	 */
	@Override
	public void sessionDidActivate(HttpSessionEvent se) {
		System.out.println("===> session did activate");
	}

}
ServletRequest related listening
@WebListener
public class RequestListener implements ServletRequestListener,ServletRequestAttributeListener {
	/**
	 * When a request is about to enter the scope of a Web application / request initialization
	 */
	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		System.out.println("===> request initialized");
	}
	/**
	 * Request coming into scope of Web application / when request is destroyed
	 */
	@Override
	public void requestDestroyed(ServletRequestEvent sre) {
		System.out.println("===> request destroyed");
	}
	/**
	 * request Attribute added
	 */
	@Override
	public void attributeAdded(ServletRequestAttributeEvent srae) {
		System.out.println("===> request attribute added");
	}
	/**
	 * request Attribute Removal
	 */
	@Override
	public void attributeRemoved(ServletRequestAttributeEvent srae) {
		System.out.println("===> request attribute removed");
	}
	/**
	 * request Attribute substitution
	 */
	@Override
	public void attributeReplaced(ServletRequestAttributeEvent srae) {
		System.out.println("===> request attribute replaced");
	}
}

3. Project related log input (start and stop)

First, execute contextinitialized method, and then execute init method of TestFilter class. The contextDestroyed method is executed after the TestFilter class destroy method is executed.

Sample code

github

Code cloud

Unless otherwise specified, the copyright of this article belongs to Foggy and cold All, reprint please indicate the source.

Original title: spring boot 2. X (x): Custom registration Servlet, Filter, Listener

Original address: https://www.zwqh.top/article/info/17

If the article is helpful to you, please scan the code and pay attention to my public account. The article is continuously updated...

Keywords: Programming Attribute Session Spring xml

Added by andrewtayloruk on Fri, 25 Oct 2019 03:58:18 +0300