Written in front:


UseSpring-Boot Time, Embedded systemServlet Containers can be annotated by scanning(@ServletComponentScan) Method of registrationServlet,Filter andServlet All standard monitors( asHttpSessionListener Monitor). 

Spring boot Master Servlet by
DispatcherServlet, Its defaulturl-pattern by“/”. Generally, the system defaults toServlet That's enough. If you need to customizeServlet, Can inherit system abstract classHttpServlet, Rewrite methods to implement their ownServlet. aboutServlet, Filter, Interceptor, The monitor can refer to:
( turn)servlet,filter,listener,interceptor Differences and connections between
<http://www.cnblogs.com/mr-yang-localhost/p/7775195.html>

Spring-Boot There are two ways to registerServlet,Filter andListener :

1, Code registration: adoptServletRegistrationBean, FilterRegistrationBean and
ServletListenerRegistrationBean Get control.

2, stay SpringBootApplication Upper [email protected] After annotation,Servlet,Filter,Listener
Directly through @WebServlet,@WebFilter,@WebListener Automatic annotation registration, No other code required.

One,Servlet

Servlet Matching rule: The priority of matching is from precision to fuzziness, Compound conditionalServlet Not all.

1, [email protected] Automatic scanning

a,springboot Add comments to the startup entry of:@ServletComponentScan;

 
@SpringBootApplication @ServletComponentScan public class ApplicationMain {
public static void main(String[] args) { SpringApplication.run(ApplicationMain.
class, args); } }
 

b,@WebServlet customServlet, Configure processing request path /demo/myServlet 
@WebServlet(name = "myServletDemo1",urlPatterns =
"/demo/myServlet",description = " Self definedservlet") public class MyServletDemo1
extends HttpServlet { @Override protected void doGet(HttpServletRequest req,
HttpServletResponse resp)throws ServletException, IOException {
System.out.println("==========myServletDemo Get Method==========");
resp.getWriter().println("my myServletDemo1 process request"); super.doGet(req,
resp); } @Overrideprotected void doPost(HttpServletRequest req,
HttpServletResponse resp)throws ServletException, IOException {
System.out.println("==========myServletDemo1 POST Method=========="); super
.doPost(req, resp); } }
 

2, [email protected] annotation

a,@ServletRegistrationBean Inject customServlet, The path of configuration processing is /demo/servletDemo2 
@Configuration public class ServletConfiguration { /** * Code injection */ @Bean public
ServletRegistrationBean myServletDemo() {return new ServletRegistrationBean(new
MyServletDemo2(), "/demo/servletDemo2"); } }
b, Self definedServlet
public class MyServletDemo2 extends HttpServlet { @Override protected void
doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException,
IOException { System.out.println("==========myServletDemo2 Get Method=========="
); resp.getWriter().println("my myServletDemo2 process request"); super
.doGet(req, resp); } @Overrideprotected void doPost(HttpServletRequest req,
HttpServletResponse resp)throws ServletException, IOException {
System.out.println("==========myServletDemo2 POST Method=========="); super
.doPost(req, resp); } }
 

Two,Filter

The whole process is:Filter Preprocessing user requests, Then give the request toServlet Process and generate response, LastFilter Then post process the server response.

Filter There are several uses.

* stayHttpServletRequest ArriveServlet before, Intercept customer'sHttpServletRequest.
* Check as neededHttpServletRequest, It can also be modifiedHttpServletRequest Head and data.
* stayHttpServletResponse Before reaching the client, interceptHttpServletResponse.
* Check as neededHttpServletResponse, It can also be modifiedHttpServletResponse Head and data.
MultipleFIlter Can form a filter call chain, Process one by one according to the set order, formationFilter Call chain.

1, [email protected] Automatic scanning

a,springboot Add comments to the startup entry of:@ServletComponentScan;

b,@WebFilter Configure to process allurl OfFilter
@WebFilter(filterName = "myFilter",urlPatterns = "/*") public class MyFilter
implements Filter { public void init(FilterConfig filterConfig) throws
ServletException { System.out.println(">>>>>>myFilter init ……"); } public void
doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain)throws IOException, ServletException {
System.out.println(">>>>>> Perform filtering operations"); filterChain.doFilter(servletRequest,
servletResponse); }public void destroy() { System.out.println(">>>>>>myFilter
destroy ……"); } }

 * doFilter() Method is the core method of filter, By implementing this method, the user request can be preprocessed, It can also realize post-processing of server response—— Their dividing line is whether they callfilterChain.doFilter(), Before executing this method, That is, preprocessing user requests; After executing the method, That is, post-processing the server response.

2, [email protected] register

a,@Bean Inject customFilter
@Configuration public class ServletConfiguration { @Bean public
FilterRegistrationBean myFilterDemo(){ FilterRegistrationBean registration= new
FilterRegistrationBean(); registration.setFilter(new MyFilter2());
registration.addUrlPatterns("/demo/myFilter2"); registration.addInitParameter(
"paramName", "paramValue"); registration.setName("myFilter2");
registration.setOrder(2);// Appointfilter Sequence return registration; } }


b, Self definedFilter
public class MyFilter2 implements Filter { public void init(FilterConfig
filterConfig)throws ServletException { System.out.println("======MyFilter2 init
……"); } public void doFilter(ServletRequest servletRequest, ServletResponse
servletResponse, FilterChain filterChain)throws IOException, ServletException {
System.out.println("======MyFilter2 Perform filtering operations");
filterChain.doFilter(servletRequest, servletResponse); }public void destroy() {
System.out.println("======MyFilter2 destroy ……"); } }
Three,Listener

at present Servlet Provided in 6 Observer interface of two kinds of events, They are:4 individual EventListeners
Type,ServletContextAttributeListener,ServletRequestAttributeListener,ServletRequestListener,HttpSessionAttributeListener
and 2 individual LifecycleListeners Type,ServletContextListener,HttpSessionListener.

* ServletContextAttributeListener Interception pairServletContext Operation of property, For example, increase, delete, modify attribute.
*
ServletContextListener MonitorServletContext. When createdServletContext Time, inspirecontextInitialized(ServletContextEvent
sce) Method; When destroyedServletContext Time, inspirecontextDestroyed(ServletContextEvent sce) Method.
* HttpSessionListener MonitorHttpSession Operation. When creating aSession Time, inspiresession
Created(HttpSessionEvent se) Method; When you destroy oneSession Time, inspiresessionDestroyed
(HttpSessionEvent se) Method.
*
HttpSessionAttributeListener MonitorHttpSession Operations on properties in. When inSession When adding a property, inspireattributeAdded(HttpSessionBindingEvent
se) Method; When inSession When deleting a property, inspireattributeRemoved(HttpSessionBindingEvent
se) Method; When inSession When property is reset, inspireattributeReplaced(HttpSessionBindingEvent se) Method.
1, [email protected] Automatic scanning

a,ServletListenerRegistrationBean  Inject customListener;

b, Self definedListener
@WebListener public class MyLisener implements ServletContextListener { public
void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("MyLisener contextInitialized method"); } public void
contextDestroyed(ServletContextEvent servletContextEvent) { System.out.println(
"MyLisener contextDestroyed method"); } }
2, [email protected]  register

a,@Bean Inject customListener;
@Configuration public class ServletConfiguration { @Bean public
ServletListenerRegistrationBean myListener(){return new
ServletListenerRegistrationBean(new MyLisener()); } }
b, Self definedListener
public class MyLisener implements ServletContextListener { public void
contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("MyLisener contextInitialized method"); } public void
contextDestroyed(ServletContextEvent servletContextEvent) { System.out.println(
"MyLisener contextDestroyed method"); } } 
Four, Verificationservlet,filter,listener Sequence

a, UseMyServletDemo2,MyFilter2,MyFilter3,MyLisener Do the test;

b, Set upservlet Handleurl Format is /demo/*; Set upMyFilter2 In sequence2;MyFilter3 In the order of3;
@Configuration public class ServletConfiguration { /** Code injection*/ @Bean public
ServletRegistrationBean myServletDemo(){return new ServletRegistrationBean(new
MyServletDemo2(),"/demo/*"); } @Bean public FilterRegistrationBean
myFilterDemo(){ FilterRegistrationBean registration= new
FilterRegistrationBean(); registration.setFilter(new MyFilter2());
registration.addUrlPatterns("/demo/myFilter"); registration.addInitParameter(
"paramName", "paramValue"); registration.setName("myFilter2");
registration.setOrder(2);// Appointfilter Sequence return registration; } @Bean public
FilterRegistrationBean myFilterDemo2(){ FilterRegistrationBean registration= new
FilterRegistrationBean(); registration.setFilter(new MyFilter3());
registration.addUrlPatterns("/demo/*"); registration.addInitParameter(
"paramName", "paramValue"); registration.setName("myFilter3");
registration.setOrder(1); return registration; } @Bean public
ServletListenerRegistrationBean myListener(){return new
ServletListenerRegistrationBean(new MyLisener()); } } View Code
c, Output after starting project:(FIlter2 First executioninit, [email protected] Before)

MyLisener contextInitialized method
======MyFilter2 init ……
======MyFilter3 init ……

d, Browser input address:http://localhost:8080/demo/myFilter, output:

======MyFilter3 Perform filtering operations
======MyFilter2 Perform filtering operations
>>>>>>>>>>test Get Method==========

It can be seen that:

* Filter3 thanFilter2 First execution;
* Filter Can match theurl Will execute, And in order(Filter Calling chain);
* Filter thanservlet First execution.
* servlet Match first, Then fuzzy matching, And only oneservlet Match up, No,servlet Call chain.
The order of execution is:Listener》Filter》Servlet

Five,ApplicationListener Custom listener class

Reference resources:http://blog.csdn.net/liaokailin/article/details/48186331
<http://blog.csdn.net/liaokailin/article/details/48186331>

Six,Interceptor

Interceptors only handleDispatcherServlet Processedurl

a, custom interceptor
public class MyInterceptor implements HandlerInterceptor { public boolean
preHandle(HttpServletRequest httpServletRequest, HttpServletResponse
httpServletResponse, Object o)throws Exception { System.out.println(
">>>>MyInterceptor preHandle"); return true; } public void
postHandle(HttpServletRequest httpServletRequest, HttpServletResponse
httpServletResponse, Object o, ModelAndView modelAndView)throws Exception {
System.out.println(">>>>MyInterceptor postHandle"); } public void
afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse
httpServletResponse, Object o, Exception e)throws Exception {
System.out.println(">>>>MyInterceptor afterCompletion"); } }
 

b, Register interceptor
@Configuration public class WebMvcConfiguration extends
WebMvcConfigurerAdapter { @Overridepublic void
addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new
MyInterceptor()).addPathPatterns("/**"); super.addInterceptors(registry); } }
c, Interceptor verification

Input address:http://localhost:8080/home/test

>>>>MyInterceptor preHandle
>>>>MyInterceptor postHandle
>>>>MyInterceptor afterCompletion

Input address:http://localhost:8080/demo/myFilter ( Self definedServlet Request processed, The interceptor does not process at this time)

Interceptor does not handle.