Spring Interceptor--handlerinterceptor

Source: Internet
Author: User

Tag: Represents the return value complete except done intercept NAT public page

Use the spring interceptor as a way to handle business. Common uses for Handlerinterceptor interceptors are:

1, log records: Log the request information for information monitoring, information statistics, calculation of PV (Page View) and so on.
2, permission check: such as login detection, enter the processor detection detection is logged in, if not directly back to the login page;
3, performance monitoring: Sometimes the system in a certain period of time inexplicably slow, can pass through the interceptor before entering the processor before the start time, record the end time after processing, so as to get the processing time of the request (if there is a reverse proxy, such as Apache can automatically record);
4, general behavior: Read the cookie to get user information and put the user object into the request, so as to facilitate the subsequent use of the process, as well as the extraction locale, theme information, as long as the multiple processors are required to use the interceptor implementation.
5, Opensessioninview: such as Hibernate, enter the processor to open the session, after the completion of the session closed.
............ Nature is also AOP (aspect-oriented programming), meaning that all features that conform to crosscutting concerns can be put into the interceptor implementation.

Needless to say, directly on the code, the understanding of the code is put in the comments.

Code ( PasswordStateInterceptor.java ):

Package com.gildata.gup.interceptor;Import Javax.servlet.http.HttpServletRequest;Import Javax.servlet.http.HttpServletResponse;Import org.springframework.beans.factory.annotation.Autowired;Import Org.springframework.security.core.context.SecurityContext;Import org.springframework.stereotype.Component;Import Org.springframework.web.servlet.HandlerInterceptor;Import Org.springframework.web.servlet.ModelAndView;Import Com.gildata.gup.domain.User;Import Com.gildata.gup.domain.UserEncryptReset;Import Com.gildata.gup.repository.UserEncryptResetRepository;@ComponentNo lessPublicClassPasswordstateinterceptorImplementsHandlerinterceptor {Handlerinterceptor interface must be implemented@AutowiredPrivate Userencryptresetrepository userencryptresetrepository;DAO class for query of user password status@OverridePublicBooleanPrehandle(HttpServletRequest request, httpservletresponse response, Object handler)Throws Exception {TODO auto-generated Method Stub SecurityContext SecurityContext = (securitycontext) request.getsession (). GetAttribute ("Spring_security_context");Gets the SecurityContext object in the session, which contains the user's information Securitycontext.getauthentication (). Getprincipal ();if (!user.equals (NULL)) {Description already logged in Userencryptreset Uer = Userencryptresetrepository.findonebyusername (User.getusername ());Querying objects that record the state of a user's passwordif ((Uer! =NULL) && (Uer.getpasswordstate (). Equals ("1"))) {Uer is present and the user's password status is out of date, the release Response.sendredirect is not allowed ("/#/passwordreset");The userReturnFalse } }Returntrue;}  @Override public void posthandle (HttpServletRequest request, HttpServletResponse response, Object handler, Modelandview modelandview) throws Exception { //TODO auto-generated Method stub return;}  @Override public  void aftercompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {//TODO auto-generated Method stub}}          

With interceptors, you PasswordStateInterceptor also need to register the interceptor. Need to use WebMvcConfigurerAdapter the next addInterceptors method. Creates a new class WebConfigfilter.java that inherits from WebMvcConfigurerAdapter .

Code ( WebConfigfilter.java ):

Package com.gildata.gup.config;Import org.springframework.beans.factory.annotation.Autowired;Import org.springframework.context.annotation.Configuration;Import Org.springframework.web.servlet.config.annotation.InterceptorRegistry;Import Org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;Import Com.gildata.gup.interceptor.PasswordStateInterceptor;@ConfigurationConfigurationPublicClassWebconfigfilterExtendswebmvcconfigureradapter{@AutowiredPrivate Passwordstateinterceptor Passwordstateinterceptor;Instantiating interceptors @Override public void addinterceptors (InterceptorRegistry Registry) {//super.addinterceptors (registry); //Register the Custom Interceptor Passwordstateinterceptor Registry.addinterceptor (passwordstateinterceptor ). Addpathpatterns ( "/api/*") //matches the path to be filtered. Excludepathpatterns ( "/api/changepasswordbyuser/*") //match unfiltered path. The password has to be modified, so this path cannot be intercepted. Excludepathpatterns ( "/api/passwordstatevalid") //password status verification cannot be intercepted. Excludepathpatterns ( "/api/getmanagerversion "); //version information also cannot intercept}}            

At this point the interceptor will take effect.
The following highlights the three overloaded methods under interceptors:

    • Prehandle
    • Posthandle
    • Aftercompletion

(1) Prehandle (httpservletrequest request, httpservletresponse response, Object handle) method, as the name implies, the method will be called before the request processing. Interceptor in SPRINGMVC is a chained invocation, where multiple interceptor can exist in one application or in one request. Each interceptor call is executed sequentially according to its declaration order, and the first execution is the Prehandle method in interceptor, so you can do some pre-initialization operations in this method or a preprocessing of the current request. You can also make some judgments in this method to determine whether the request is going to go on. The return value of the method is a Boolean of type bool, and when it returns to false, it means that the request ends and that subsequent interceptor and controllers are no longer executed, and the next interceptor is resumed when the return value is True Prehandle method, which is the Controller method that invokes the current request if it is already the last interceptor.

(2) Posthandle (HttpServletRequest request, httpservletresponse response, Object handle, Modelandview Modelandview) method, By the interpretation of the Prehandle method, we know that this method, including the Aftercompletion method to be mentioned later, can only be called if the return value of the Prehandle method of the currently owned interceptor is true. The Posthandle method, as the name implies, is executed after the current request is processed, that is, after the controller method call, but it is called before the view returns to render Dispatcherservlet. So we can manipulate the Modelandview object after controller processing in this method. The Posthandle method is called in the opposite direction to Prehandle, which means that the Posthandle method of the declared interceptor is executed later, which is somewhat different from the Struts2 execution in interceptor. Struts2 inside the Interceptor execution process is also chained, but in Struts2 need to manually invoke the Actioninvocation invoke method to trigger the next interceptor or action call, Then the contents of each interceptor before the Invoke method call are executed in the order of Declaration, and the content after the Invoke method is reversed.

(3) Aftercompletion (HttpServletRequest request, httpservletresponse response, Object handle, Exception ex) method, This method is also required when the return value of the Prehandle method of the current corresponding interceptor is true to execute. As the name implies, the method executes after the entire request is finished, that is, after Dispatcherservlet renders the corresponding view. The main function of this method is to perform resource cleanup work.




Spring Interceptor--handlerinterceptor

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.