Thirteen, Spring Boot injection Servlet, Filter, Listener
@
- Thirteen, Spring Boot injection Servlet, Filter, Listener
- 1. Basic introduction
-
2. The first way: the use of annotations into: Servlet, Filter, Listener
- 2.1 Injection using annotations: Servlet
- 2.2 Injection using annotations: Filter
- 2.3 Injection using annotations: Listener
-
3. the second way: using RegistrationBean way to inject Servlet, Filter, Listener
- 3.1 Injecting Servlets Using RegistrationBean Methods
- 3.2 Injecting Filters with RegistrationBeans
- 3.3 Injecting a Listener as a RegistrationBean
- 4. Notes and clarifications
- 5. Summary:
- 6. Finally:
1. Basic introduction
- Considering the actual development of the business is very complex and compatible, Spring-Boot supports Servlet, Filter, Listener injected into the Spring container, become a Spring bean.
- This means that Spring Boot opens up compatibility with native WEB components (Servlet, Filter, Listener).
In Spring Boot when the corresponding Servlet, Filter (Filter), Listener (Listener) injection, there are two ways:
- The first way: use annotations to inject .
- The second way: use the RegistrationBean way to inject Servlet, Filter, Listener way to inject.
2. The first way: the use of annotations into: Servlet, Filter, Listener
2.1 Injection using annotations: Servlet
Use (@WebServlet + @ServletComponentScan
) These two annotations are used to inject the Servlet
Tip: urlPatterns = {"/servlet01", "servlet02"}, mapping of url-pat:request paths configured for servlet
- The injected native Servlet_ will not be intercepted by the Spring boot interceptor.
- For the development of native Servlet, you need to use @ServletComponentScan to specify the native Servlet to be scanned, will be injected into the Spring container, note: is the location of the start scene to add the @ServletComponentScan annotation.
package ;
import ;
import ;
import ;
import ;
import ;
import ;
// utilization extends Mode of inheritance(@WebServlet + @ServletComponentScan explanatory note),pour into servlet
@WebServlet(urlPatterns = {"/servlet01","/servlet02"}) // Note that it's: / beginning
public class Servlet_ extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response
) throws ServletException,
IOException {
// The front-end display print shows some information。
().write("hello , Servlet_!");
}
}
Note that you need to use the @ServletComponentScan annotation in the corresponding project's scenario launcher, in which thebasePackages
attribute specifies the path to the package you want Spring Boot to scan. This allows Spring Boot to find the classes in the ioc container that you want it to inject.
package ;
import ;
import ;
import ;
import ;
@SpringBootApplication // Project Launch Logo
@ServletComponentScan(basePackages = {""})
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext ioc = (, args);
//(); // Stop container
("hello");
}
}
Run the test:
2.2 Injection using annotations: Filter
Use (@WebFilter+ @ServletComponentScan
) These two annotations inject the Filter
Note that the injected Filter filter implements the implements
Filter under
// Note that the Filter under: is
// Injection Filter: (using: @WebFilter(urlPatterns = {"/css/*","/images/*"}) + @ServletComponentScan(basePackages = {""}))
/*
@WebFilter(urlPatterns = {"/css/*", "/images/*"})
@WebFilter indicates that Filter_ is a filter and injects the container
urlPatterns = {"/css/*", "/images/*"} when requesting /css/ directory resources or images
Interpretation: After the direct release, it passes through the interceptor, and whether or not the interceptor intercepts it depends on the interceptor's interception rules.
Special note in: before the following configuration of the interceptor is also intercepted content.
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
("addInterceptors~~~");
// Register the interceptor
(new LoginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/","/login","/images/**");
}
}; }
}
Note: The urlPatterns configured by the filter also go through the Spring-Boot interceptor, so in order for the
To see the effect, put /css/**, in the interceptor configuration.
In the servlet, it means that all matches are"/*"
and in Spring boot, all matches are indicated by."/**"
package ;
import .slf4j.Slf4j;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@Slf4j
@WebFilter(urlPatterns = {"/static/css/*", "/images/*"}) // take note of:be/beginning
public class Filter_ implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
("--Filter_ init0--");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
("Filter - doFitler");
// To make it easier to observe the resources processed by the filter,We output aurl
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
("filtered url={}",());
// We'll let it go straight through.,Actual development,Decide how to handle it based on your business
(servletRequest, servletResponse);
}
@Override
public void destroy() {
("Filter -destory");
}
}
Also note that you need to use the @ServletComponentScan annotation in the corresponding project's scenario launcher, and add the @ServletComponentScan annotation to thebasePackages
attribute specifies the path to the package you want Spring Boot to scan. This allows Spring Boot to find the classes in the ioc container that you want it to inject.
Run the test:
2.3 Injection using annotations: Listener
Use (@WebListener+ @ServletComponentScan
) These two annotations are used to inject the Servlet
package ;
import .slf4j.Slf4j;
import ;
import ;
import ;
// Injecting a Listener(@WebListener + @ServletComponentScan(basePackages = {""}))
@Slf4j
@WebListener
public class Listener_ implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// Here you can add business code related to the initialization of the project
("Listener_ contextInitialized Project InitializationOK~");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// Here you can add the appropriate code...
("Listener_ contextInitialized Project destructionOK~");
}
}
Also note that you need to use the @ServletComponentScan annotation in the corresponding project's scenario launcher, and add the @ServletComponentScan annotation to thebasePackages
attribute specifies the path to the package you want Spring Boot to scan. This allows Spring Boot to find the classes in the ioc container that you want it to inject.
Run the test:
3. the second way: using RegistrationBean way to inject Servlet, Filter, Listener
3.1 Injecting Servlets Using RegistrationBean Methods
package ;
import .
import .Listener_; import .
import .Servlet_; import ;Filter_; import .Listener_; import .
import ;
import ;Servlet_; import ;Filter_; import .Listener_; import .
import ;Servlet_; import ;Filter_; import .Listener_; import .
import ;Servlet_; import ;Listener_; import .
import ;
import ;
// Inject, servlet, listener, filter, and listener listener using configuration classes.
/*
* @Configuration(proxyBeanMethods = true)
* @Configuration means it is a configuration class.
* proxyBeanMethods = true defaults to a singleton return bean (guarantees that each @bean method is the same as many times it is called)
*/
@Configuration(proxyBeanMethods = true)
public class RegisterConfig_ {
// Injecting a Servlet into the Servlet as a RegistrationBean.
// Inject the Servlet
// Note: Add the bean object
//@Bean(name = "Servlet_") // If the bean doesn't have a name, the default is to use the method name as the name/id.
@Bean
public ServletRegistrationBean servlet2() {
// Create the native Servlet object (the one we created ourselves)
Servlet_ servlet_ = new Servlet_(); // Create a native Servlet object (the one we created ourselves).
// Associate the Servlet_ object to the ServletRegistrationBean object.
// "/servlet03" is the url-pattern of the injected Servlet.
return new ServletRegistrationBean(servlet_, "/servlet03");
}
}
package ;
import ;
import ;
import ;
import ;
import ;
import ;
public class Servlet_ extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response
) throws ServletException,
IOException {
// The front-end display print shows some information。
().write("hello , Servlet_!");
}
}
Note that you need to use the @ServletComponentScan annotation in the corresponding project's scenario launcher, in which thebasePackages
attribute specifies the path to the package you want Spring Boot to scan. This allows Spring Boot to find the classes in the ioc container that you want it to inject.
package ;
import ;
import ;
import ;
import ;
@SpringBootApplication // Project Launch Logo
@ServletComponentScan(basePackages = {""})
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext ioc = (, args);
//(); // Stop container
("hello");
}
}
Run the test:
3.2 Injecting Filters with RegistrationBeans
package ;
import .
import .Listener_; import .
import .Servlet_; import ;Filter_; import .Listener_; import .
import ;
import ;Servlet_; import ;Filter_; import .Listener_; import .
import ;Servlet_; import ;Filter_; import .Listener_; import .
import ;Servlet_; import ;Listener_; import .
import ;
import ;
// Inject, servlet, listener, filter, and listener listener using configuration classes.
/*
* @Configuration(proxyBeanMethods = true)
* @Configuration means it is a configuration class.
* proxyBeanMethods = true defaults to a singleton return bean (guarantees that each @bean method is the same as many times it is called)
*/
@Configuration(proxyBeanMethods = true)
public class RegisterConfig_ {
// Inject Filter
// Note: Add the Bean object
@Bean(name = "Filter_")
public FilterRegistrationBean filter2() {
// Create the native Filter_ object (the Filter_ we created ourselves)
Filter_ filter_ = new Filter_();
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(filter_);
// Set the url-pattern of the filter
// ("/css/*", "images/*") converts a string to a collection.
// Note: Don't leave out the "/" at the beginning.
(("/css/*", "/images/*")).
return filterRegistrationBean;
}
}
package ;
import .slf4j.Slf4j;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@Slf4j
public class Filter_ implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
("--Filter_ init0--");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
("Filter - doFitler");
// To make it easier to observe the resources processed by the filter,We output aurl
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
("filtered url={}",());
// We'll let it go straight through.,Actual development,Decide how to handle it based on your business
(servletRequest, servletResponse);
}
@Override
public void destroy() {
("Filter -destory");
}
}
Also note that you need to use the @ServletComponentScan annotation in the corresponding project's scenario launcher, and add the @ServletComponentScan annotation to thebasePackages
attribute specifies the path to the package you want Spring Boot to scan. This allows Spring Boot to find the classes in the ioc container that you want it to inject.
Run the test:
3.3 Injecting a Listener as a RegistrationBean
package ;
import .
import .Listener_; import .
import .Servlet_; import ;Filter_; import .Listener_; import .
import ;
import ;Servlet_; import ;Filter_; import .Listener_; import .
import ;Servlet_; import ;Filter_; import .Listener_; import .
import ;Servlet_; import ;Listener_; import .
import ;
import ;
// Inject, servlet, listener, filter, and listener listener using configuration classes.
/*
* @Configuration(proxyBeanMethods = true)
* @Configuration means it is a configuration class.
* proxyBeanMethods = true defaults to a singleton return bean (guarantees that each @bean method is the same as many times it is called)
*/
@Configuration(proxyBeanMethods = true)
public class RegisterConfig_ {
// Inject: Listener
//@Bean(name = "Listener_")
@Bean
public ServletListenerRegistrationBean Listener2() {
// Create the native Listener_ object (the one we created ourselves)
Listener_ listener_ = new Listener_();
return new ServletListenerRegistrationBean(listener_);
}
}
package ;
import .slf4j.Slf4j;
import ;
import ;
import ;
// Injecting a Listener(@WebListener + @ServletComponentScan(basePackages = {""}))
@Slf4j
@WebListener
public class Listener_ implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// Here you can add business code related to the initialization of the project
("Listener_ contextInitialized Project InitializationOK~");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// Here you can add the appropriate code...
("Listener_ contextInitialized Project destructionOK~");
}
}
Also note that you need to use the @ServletComponentScan annotation in the corresponding project's scenario launcher, and add the @ServletComponentScan annotation to thebasePackages
attribute specifies the path to the package you want Spring Boot to scan. This allows Spring Boot to find the classes in the ioc container that you want it to inject.
Run the test:
4. Notes and clarifications
Why doesn't the interceptor arrive when requesting a (self-written) servlet? 。
When a Servlet is requested, it does not reach the DispatherServlet, and therefore does not reach the interceptor.
Cause Analysis.
The injected Servlet will exist in the Spring container
The DispatherServlet also exists in the Spring container.
Multiple Servlet containers can process to the same layer of interception, exact first principle/longest prefix match principle
So when /servlet01 is requested, it will match directly to the injected servlet
Simply put: when you jump between servlets to communicate, you are first looking for the same layer of servlet, if you are on the same layer of the
The servlet has the mapped request path you need, so it's preferable to jump to the servlet instead of the interceptor, which is in between the servlet and the Controller.
You can recall: we talked about Tomcat in the Servlet url matching principle, multiple servlets can be processed to the same level of the path, the principle of precision priority / longest prefix matching principle
In Spring Boot, going to call the @Controller target method is in accordance with the DispatherServlet distribution matching mechanism, please review the students, our own implementation of Spring MVC's underlying mechanism of the program.
5. Summary:
-
The first way: using annotations to inject Servlet, Filter, Listener:
- Use (
@WebServlet + @ServletComponentScan
) These two annotations are used to inject the Servlet - Use (
@WebFilter+ @ServletComponentScan
) These two annotations inject the Filter - Use (
@WebListener+ @ServletComponentScan
) These two annotations are used to inject the Servlet
- Use (
-
The second way: use RegistrationBean to inject Servlet, Filter, Listener.
-
Note: Either the first or the second way must be used on the location of the corresponding project's scene starter:
@ServletComponentScan
annotation. In the annotation'sbasePackages
attribute specifies the path to the package you want Spring Boot to scan. This allows Spring Boot to find the classes in the ioc container that you want it to inject.
6. Finally:
"In this final chapter, I would like to express my gratitude to each and every one of my readers. Your attention and responses have been a source of motivation for me to create, and I have drawn endless inspiration and courage from you. I will keep your encouragement in my heart and continue to struggle in other areas. Thanks to you all, we will always meet again at some point."