Write in front :


use Spring-Boot Time , Embedded Servlet Containers can be annotated by scanning (@ServletComponentScan) Registration by Servlet,Filter and Servlet All standard monitors ( as HttpSessionListener monitor ). 

Spring boot The Lord of Servlet by
DispatcherServlet, Its default url-pattern by “/”. Generally, the system defaults to Servlet That's enough , If you need to customize Servlet, Can inherit system abstract class HttpServlet, Rewrite methods to implement their own Servlet. about Servlet, 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 register Servlet,Filter and Listener :

1, Code registration : adopt ServletRegistrationBean, FilterRegistrationBean and
ServletListenerRegistrationBean Gain control .

2, stay SpringBootApplication Use on @ServletComponentScan After annotation ,Servlet,Filter,Listener
Directly through @WebServlet,@WebFilter,@WebListener Automatic annotation registration , No other code required .

One ,Servlet

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

1, adopt @ServletComponentScan Autoscan

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 custom Servlet, Configure processing request path  /demo/myServlet 
@WebServlet(name = "myServletDemo1",urlPatterns =
"/demo/myServlet",description = " Customized servlet") 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, use @ServletRegistrationBean annotation

a,@ServletRegistrationBean Inject custom Servlet, 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, Customized Servlet
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 to Servlet Process and generate response , last Filter Then post process the server response .

Filter There are several uses .

* stay HttpServletRequest arrive Servlet before , Intercept customer's HttpServletRequest.
* Check as needed HttpServletRequest, It can also be modified HttpServletRequest Header and data .
* stay HttpServletResponse Before reaching the client , intercept HttpServletResponse.
* Check as needed HttpServletResponse, It can also be modified HttpServletResponse Header and data .
Multiple FIlter Can form a filter call chain , Process one by one according to the set order , formation Filter Call chain .

1, adopt @ServletComponentScan Autoscan

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

b,@WebFilter Configure to process all url Of Filter
@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 call filterChain.doFilter(), Before executing this method , That is, preprocessing user requests ; After executing the method , That is, post-processing the server response .

2, adopt @FilterRegistrationBean register

a,@Bean Inject custom Filter
@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);// appoint filter Order of return registration; } }


b, Customized Filter
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
Of type ,ServletContextAttributeListener,ServletRequestAttributeListener,ServletRequestListener,HttpSessionAttributeListener
and 2 individual LifecycleListeners Of type ,ServletContextListener,HttpSessionListener.

* ServletContextAttributeListener Monitor right ServletContext Operation of property , For example, increase , delete , modify attribute .
*
ServletContextListener monitor ServletContext. When creating ServletContext Time , inspire contextInitialized(ServletContextEvent
sce) method ; When destroyed ServletContext Time , inspire contextDestroyed(ServletContextEvent sce) method .
* HttpSessionListener monitor HttpSession Operation of . When creating a Session Time , inspire session
Created(HttpSessionEvent se) method ; When you destroy one Session Time , inspire sessionDestroyed
(HttpSessionEvent se) method .
*
HttpSessionAttributeListener monitor HttpSession Operations on properties in . When Session When adding a property , inspire attributeAdded(HttpSessionBindingEvent
se) method ; When Session When deleting a property , inspire attributeRemoved(HttpSessionBindingEvent
se) method ; When Session When property is reset , inspire attributeReplaced(HttpSessionBindingEvent se) method .
1, adopt @ServletComponentScan Autoscan

a,ServletListenerRegistrationBean  Inject custom Listener;

b, Customized Listener
@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, adopt @ServletListenerRegistrationBean  register

a,@Bean Inject custom Listener;
@Configuration public class ServletConfiguration { @Bean public
ServletListenerRegistrationBean myListener(){return new
ServletListenerRegistrationBean(new MyLisener()); } }
b, Customized Listener
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 , verification servlet,filter,listener Order of

a, use MyServletDemo2,MyFilter2,MyFilter3,MyLisener Do a test ;

b, set up servlet handle url Format is  /demo/*; set up MyFilter2 The order is 2;MyFilter3 The order is 3;
@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);// appoint filter Order of 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 Execute first init, because @Ben 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 than Filter2 Execute first ;
* Filter Can match the url Will be implemented , And in order (Filter Call chain for );
* Filter than servlet Execute first .
* servlet Match first , Then fuzzy matching , And there can only be one servlet 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 handle DispatcherServlet Processed url

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

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

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

Enter address :http://localhost:8080/demo/myFilter ( Customized Servlet Request processed , The interceptor does not process at this time )

Interceptor does not handle .