Spring Boot Interceptor Handlerinterceptor "Learn Spring boot from scratch"

Source: Internet
Author: User

Ext.: http://blog.csdn.net/linxingliang/article/details/52069495

The previous article on the definition of the filter has been explained, but also relatively simple. Filters are APIs that are part of the servlet category and do not have anything to do with spring.
In web development, we can also use the Handlerinterceptor (Interceptor) provided by spring, in addition to filtering the Web request using filter.

The Handlerinterceptor function is similar to a filter, but provides finer control: Before the request is answered, after the request is answered, before the view is rendered, and after the request is complete. We cannot modify the request content through interceptors, but we can pause the execution of the request by throwing an exception (or returning false).

The interceptors that implement Userroleauthorizationinterceptor are:
Conversionserviceexposinginterceptor
Corsinterceptor
Localechangeinterceptor
Pathexposinghandlerinterceptor
Resourceurlproviderexposinginterceptor
Themechangeinterceptor
Uritemplatevariableshandlerinterceptor
Userroleauthorizationinterceptor

Among them, Localechangeinterceptor and themechangeinterceptor are more commonly used.

Configuring interceptors is also simple, Spring provides the base class Webmvcconfigureradapter, and we only need to rewrite the Addinterceptors method to add a registered interceptor.

It only takes 3 steps to implement a custom interceptor:
1. Create our own interceptor class and implement the Handlerinterceptor interface.

2. Create a Java class to inherit Webmvcconfigureradapter, and override the Addinterceptors method.

2. Instantiate our custom interceptor, and then manually add the image to the interceptor chain (added in the Addinterceptors method).

PS: This article focuses on how to use interceptors in the spring-boot, about the principle of interceptors please consult the information to understand.

code example:

Com.kfit.interceptor.MyInterceptor1.java

Package com.kfit.interceptor;

Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;

Import Org.springframework.web.servlet.HandlerInterceptor;

Import Org.springframework.web.servlet.ModelAndView;

/**

* Custom Interceptors 1

*

* @author Angel

*/

Publicclass MyInterceptor1 implements Handlerinterceptor {

@Override

Publicboolean Prehandle (httpservletrequestrequest, httpservletresponse response, Object handler)

Throws Exception {

System.out.println (">>>MyInterceptor1>>>>>>> before request processing (before the Controller method call)");

returntrue;//only returns true to continue execution down, return false cancel current request

}

@Override

Publicvoid Posthandle (httpservletrequestrequest, httpservletresponse response, Object handler,

Modelandviewmodelandview) throws Exception {

System.out.println (">>>MyInterceptor1>>>>>>> call after request processing, But before the view is rendered (after the Controller method call) ");

}

@Override

Publicvoid aftercompletion (httpservletrequestrequest, httpservletresponse response, Object handler, Exception ex)

Throws Exception {

System.out.println (">>>MyInterceptor1>>>>>>> is called after the entire request is completed, that is, in Dispatcherservlet Executed after rendering the corresponding view (mainly for resource cleanup) ");

}

}

Com.kfit.interceptor.MyInterceptor2.java

Package com.kfit.interceptor;

Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;

Import Org.springframework.web.servlet.HandlerInterceptor;

Import Org.springframework.web.servlet.ModelAndView;

/**

* Custom Interceptors 2

*

* @author Angel

*/

public class MyInterceptor2 implements Handlerinterceptor {

@Override

Publicboolean Prehandle (httpservletrequestrequest, httpservletresponse response, Object handler)

Throws Exception {

System.out.println (">>>MyInterceptor2>>>>>>> before request processing (before the Controller method call)");

returntrue;//only returns true to continue execution down, return false cancel current request

}

@Override

Publicvoid Posthandle (httpservletrequestrequest, httpservletresponse response, Object handler,

Modelandviewmodelandview) throws Exception {

System.out.println (">>>MyInterceptor2>>>>>>> call after request processing, But before the view is rendered (after the Controller method call) ");

}

@Override

Publicvoid aftercompletion (httpservletrequestrequest, httpservletresponse response, Object handler, Exception ex)

Throws Exception {

System.out.println (">>>MyInterceptor2>>>>>>> is called after the entire request is completed, that is, in Dispatcherservlet Executed after rendering the corresponding view (mainly for resource cleanup) ");

}

}

Com.kfit.config.MyWebAppConfigurer.java

Package com.kfit.config;

Import Com.kfit.interceptor.MyInterceptor1;

Import Com.kfit.interceptor.MyInterceptor2;

Import org.springframework.context.annotation.Configuration;

Import Org.springframework.web.servlet.config.annotation.InterceptorRegistry;

Import Org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration

public class Mywebappconfigurer

Extends Webmvcconfigureradapter {

@Override

Publicvoid addinterceptors (interceptorregistryregistry) {

Multiple interceptors form an interceptor chain

Addpathpatterns for adding interception rules

Excludepathpatterns User exclusion interception

Registry.addinterceptor (New MyInterceptor1 ()). Addpathpatterns ("/**");

Registry.addinterceptor (New MyInterceptor2 ()). Addpathpatterns ("/**");

Super.addinterceptors (registry);

}

}

Then after the browser enters the address: Http://localhost:8080/index, the output of the console is:

>>>MyInterceptor1>>>>>>> Call before request processing (before the Controller method call)

>>>MyInterceptor2>>>>>>> Call before request processing (before the Controller method call)

>>>MyInterceptor2>>>>>>> call after request processing, but before the view is rendered (after the Controller method call)

>>>MyInterceptor1>>>>>>> call after request processing, but before the view is rendered (after the Controller method call)

>>>MyInterceptor2>>>>>>> is called after the entire request is over, that is, the Dispatcherservlet Executes after rendering the corresponding view (primarily for resource cleanup work)

>>>MyInterceptor1>>>>>>> is called after the entire request is over, that is, the Dispatcherservlet Executes after rendering the corresponding view (primarily for resource cleanup work)

According to the output can understand the order of execution of the Interceptor chain (the specific principle of introduction, we look for Niang a ask to know)

Last but not least: the Interceptor chain will only go through Dispatcherservlet requests, and our custom servlet requests will not be intercepted, such as our custom servlet address http://localhost:8080/ MyServlet1 is not intercepted by interceptors. And no matter which servlet it belongs to, the filter will intercept as long as the filter rules of the composite filter.

Finally, we use the above webmvcconfigureradapter is not just registered to add interceptors use, its name is to do the Web configuration, it can have a lot of other functions, through the following can be roughly understood, how each method is used, Leave it to everyone to study it (in fact, it's quite simple).

Spring Boot Interceptor Handlerinterceptor "Learn Spring boot from scratch"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.