Spring Boot registers Web native components (Servlet, Filter, Listener)

Since Spring Boot is deployed as a Jar package by default, there is no web.xml by default, so it is no longer possible to use Servlet, Filter, and Listener through web.xml configuration as before, but Spring Boot provides 2 ways to register these native Web components .
Registration through component scanning Registration
with RegistrationBean Registration
through component scanning
Servlet 3.0 provides the following three annotations:
@WebServlet: used to declare a Servlet;
@WebFilter: used to declare a Filter;
@WebListener: used to declare a Listener.

These annotations can be directly marked on the corresponding components, and they have the same meaning as the configuration in web.xml. Each annotation has an attribute corresponding to web.xml, which can be configured directly, eliminating the cumbersome configuration of web.xml.

To register these native Web components in SpringBoot, you can use the @ServletComponentScan annotation, which can scan component classes marked with three annotations @WebServlet, @WebFilter and @WebListener and register them in the container.
Note: The @ServletComponentScan annotation can only be marked on the startup class or configuration class.

example

  1. Use the @WebServlet annotation to declare a custom Servlet, the code is as follows.
    package tangyu9880.servlet;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet
    ; import
    javax.servlet.http.HttpServletRequest;
    .io.IOException;
    import java.io.PrintWriter;
    //Declare a Servlet using the @WebServlet annotation
    @WebServlet(name = “myServlet”, urlPatterns = “/myServlet”)
    public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override





    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType(“text/html;charset=UTF-8”);
    PrintWriter writer = resp.getWriter();
    writer.write(“Spring Boot Servlet”);
    writer.close();
    }
    }

  2. Use the @WebFilter annotation to declare a custom Filter, the code is as follows.
    package tangyu9880.filter;
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import java.io.IOException;
    //Use the @WebFilter annotation to declare a custom Filter
    @WebFilter(urlPatterns = (“/myServlet” ))
    public class MyFiler implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("MyFiler initialization"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChange) , ServletException { System.out.println(“MyFiler doFilter”); chain.doFilter(request, response); }









    @Override
    public void destroy() {
    System.out.println(“MyFiler 销毁”);
    }
    }

  3. Use the @WebListener annotation to declare a custom Listener, the code is as follows.
    package tangyu9880.Listener;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import javax.servlet.annotation.WebListener;
    //Use the @WebListener annotation to declare a custom Listener
    @WebListener
    public class MyListener implements ServletContextverListener { @O public void contextInitialized(ServletContextEvent sce) { System.out.println("MyListener listens to ServletContext initialization"); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("MyListener listens to ServletContext destruction"); } }








  4. Use the @ServletComponentScan annotation on the startup class to scan the Servlet, Filter and Listener just declared above, and register them in the container for use. The code is as follows.
    package tangyu9880;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.web.servlet.ServletComponentScan;
    @ServletComponentScan
    @SpringBootApplication
    public class SpringBootServlet {String [] args) { SpringApplication.run(SpringBootServletApplication.class, args); } }



  5. Start Spring Boot, and the console logs are as follows.
    .____ _ _ _ _
    /\ / ' __ _ ( ) __ __ _ \ \ \
    ( ( )_
    _ | '_ | ' | | ' / ` | \ \ \
    \/ )| | )| | | | | || ( | | ) ) ) )
    ' |
    | .__| | | | | | _ , | / / / /
    =========|
    |============ ==| /=/ / / /
    :: Spring Boot :: (v2.5.1)

2021-06-23 14:07:04.202 INFO 10200 — [ main] n.b.www.SpringBootServletApplication : Starting SpringBootServletApplication using Java 1.8.0_131 on LAPTOP-C67MRMAG with PID 10200 (D:\spring-boot-servlet\target\classes started by 79330 in D:\spring-boot-servlet)
2021-06-23 14:07:04.205 INFO 10200 — [ main] n.b.www.SpringBootServletApplication : No active profile set, falling back to default profiles: default
2021-06-23 14:07:05.169 INFO 10200 — [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-06-23 14:07:05.180 INFO 10200 — [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-06-23 14:07:05.180 INFO 10200 — [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.46]
2021-06-23 14:07:05.245 INFO 10200 — [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-06-23 14:07:05.245 INFO 10200 — [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 984 ms
MyListener 监听到 ServletContext 初始化
MyFiler 初始化
2021-06-23 14:07:05.543 INFO 10200 — [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ‘’
2021-06-23 14:07:05.550 INFO 10200 — [ main] n.b.www.SpringBootServletApplication : Started SpringBootServletApplication in 1.853 seconds (JVM running for 2.764)
MyFiler doFilter

It can be seen from the above log output that the custom filter Filter and the listener Listener have taken effect.

  1. The browser accesses "http://localhost:8080/myServlet", and the results are as follows.

insert image description here

Spring Boot Register Servlet
Figure 1: Spring Boot Register Servlet

As can be seen from the figure above, the custom Servlet has also taken effect.

Registration using RegistrationBean
We can also use RegistrationBean in the configuration class to register native Web components, but this method is more cumbersome than the annotation method. Native Web components registered in this way no longer need to use annotations such as @WebServlet, @WebListener and @WebListener.

RegistrationBean is an abstract class responsible for registering components into the Servlet container. Spring provides three implementation classes for registering Servlet, Filter and Listener respectively.
ServletRegistrationBean: Servlet registration class
FilterRegistrationBean: Filter registration class
ServletListenerRegistrationBean: Listener registration class

We can use @Bean annotations to add ServletRegistrationBean, FilterRegistrationBean and ServletListenerRegistrationBean to the Spring container in the configuration class, and register our custom Servlet, Filter and Listener components to the container through them.
Example 2

  1. 创建自定义 Servlet,代码如下。
    package tangyu9880.servlet;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType(“text/html;charset=UTF-8”);
    PrintWriter writer = resp.getWriter();
    writer.write(“Spring Boot Servlet”);
    writer.close();
    }
    }

  2. Create a custom Filter, the code is as follows.
    package tangyu9880.filter;
    import javax.servlet.*;
    import java.io.IOException;
    public class MyFiler implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("MyFiler initialization"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println(“MyFiler doFilter”); chain.doFilter(request, response); } @Override public) void destroy( System.out.println("MyFiler destroyed"); } }













  3. Create a custom Listener, the code is as follows.
    package tangyu9880.Listener;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    //Monitor the initialization and destruction process of ServletContext
    public class MyListener implements ServletContextListener { @Override public void contextInitialized(ServletContext.printoutEvent) { "MyListener listens to ServletContext initialization"); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("MyListener listens to ServletContext destruction"); } }








  4. Create a configuration class MyConfig, use @Bean annotation to add ServletRegistrationBean, FilterRegistrationBean and ServletListenerRegistrationBean to the Spring container, and use them to register our custom Servlet, Filter and Listener respectively. The sample code is as follows.
    package tangyu9880.config;
    import tangyu9880.Listener.MyListener;
    import tangyu9880.filter.MyFiler;
    import tangyu9880.servlet.MyServlet;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.boot. ServletListenerRegistrationBean;
    import org.springframework.boot.web.servlet.ServletRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import java.util.Arrays;
    @Configuration
    public class MyConfig {
    /**

    • Register servlet
    • @return
      /
      @Bean
      public ServletRegistrationBean servletRegistrationBean() {
      MyServlet myServlet = new MyServlet();
      return new ServletRegistrationBean(myServlet, “/myServlet”);
      }
      /
      *
    • register filter
    • @return
      /
      @Bean
      public FilterRegistrationBean filterRegistrationBean() { MyFiler myFiler = new MyFiler(); FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFiler); //Register the url that the filter needs to filter filterRegistrationBean.setUrlPatterns(Arrays.asList(“/myServlet” )); return filterRegistrationBean; } /






      *
    • register listener
    • @return
      */
      @Bean
      public ServletListenerRegistrationBean servletListenerRegistrationBean() {
      MyListener myListener = new MyListener();
      return new ServletListenerRegistrationBean(myListener);
      }
      }
  5. Start Spring Boot, and the console logs are as follows.
    .____ _ _ _ _
    /\ / ' __ _ ( ) __ __ _ \ \ \
    ( ( )_
    _ | '_ | ' | | ' / ` | \ \ \
    \/ )| | )| | | | | || ( | | ) ) ) )
    ' |
    | .__| | | | | | _ , | / / / /
    =========|
    |============ ==| /=/ / / /
    :: Spring Boot :: (v2.5.1)

2021-06-23 14:39:16.338 INFO 8684 — [ main] n.b.www.SpringBootServletApplication : Starting SpringBootServletApplication using Java 1.8.0_131 on LAPTOP-C67MRMAG with PID 8684 (D:\spring-boot-servlet\target\classes started by 79330 in D:\spring-boot-servlet)
2021-06-23 14:39:16.340 INFO 8684 — [ main] n.b.www.SpringBootServletApplication : No active profile set, falling back to default profiles: default
2021-06-23 14:39:17.059 INFO 8684 — [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-06-23 14:39:17.069 INFO 8684 — [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-06-23 14:39:17.070 INFO 8684 — [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.46]
2021-06-23 14:39:17.138 INFO 8684 — [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-06-23 14:39:17.138 INFO 8684 — [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 766 ms
MyListener 监听到 ServletContext 初始化
MyFiler 初始化
2021-06-23 14:39:17.390 INFO 8684 — [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ‘’
2021-06-23 14:39:17.396 INFO 8684 — [ main] n.b.www.SpringBootServletApplication : Started SpringBootServletApplication in 1.379 seconds (JVM running for 2.19)

It can be seen from the above log output that the custom filter Filter and the listener Listener have taken effect.

  1. The browser accesses "http://localhost:8080/myServlet", and the result is as shown in the figure below.

insert image description here

Spring Boot Register Servlet
Figure 1: Spring Boot Register Servlet

As can be seen from the figure above, the custom Servlet has also been registered and takes effect.

Guess you like

Origin blog.csdn.net/weixin_64842782/article/details/125106934