Spring MVC Interceptor

Source: Internet
Author: User

Label:

What is an interceptor?

An interceptor is an enhancement of our functionality by unifying the requests sent from the browser to the server.

What is the difference between Java filters and Springmvc interceptors?

Definition: interceptors are a way to intercept our configuration and do some processing before and after our method request, such as character encoding, validation verification, and so on.

and the filter: in Javaweb, your incoming request, response filter out some of the information beforehand, or set some parameters ahead of time, and then pass in the servlet or struts action for business logic, For example, filter out illegal URLs (not login.do address requests, if the user does not log on to filter out), or in the servlet or struts before the action of the uniform set of character sets, or to remove some illegal characters.

Implementation: Interceptors are based on the reflection mechanism of Java, and filters are based on function callbacks.
Other specific differences: 1. Different configuration methods; 2. The order of execution is different, the filter is based on the order of the filter mapping configuration, and the interceptor is in the order of configuration, but can be controlled by order. 3. Specification; The filter is defined in the servlet specification and is supported by the servlet container, which is implemented based on the spring framework and managed by the spring container. 4. Scope of Use: The filter can only work on the action method, and the interceptor works on almost all methods. Implementation of interceptorsThere are two main ways to implement interceptor interceptors, one is to implementSpringof theHandlerinterceptorinterface, and the other is the class that inherits the Handlerinterceptor interface that implements Spring .
Common Application Scenarios

1、日志记录:记录请求信息的日志,以便进行信息监控、信息统计、计算PV(Page View)等。

2、权限检查:如登录检测,进入处理器检测检测是否登录,如果没有直接返回到登录页面;

3、性能监控:有时候系统在某段时间莫名其妙的慢,可以通过拦截器在进入处理器之前记录开始时间,在处理完后记录结束时间,从而得到该请求的处理时间(如果有反向代理,如apache可以自动记录);

4、通用行为:读取cookie得到用户信息并将用户对象放入请求,从而方便后续流程使用,还有如提取Locale、Theme信息等,只要是多个处理器都需要的即可使用拦截器实现。

5、OpenSessionInView:如Hibernate,在进入处理器打开Session,在完成后关闭Session。

…………本质也是AOP(面向切面编程),也就是说符合横切关注点的所有功能都可以放入拦截器实现。

implementing the Handlerinterceptor interface

There are three methods defined in the Handlerinterceptor interface, and we are using these three methods to intercept the user's request.

Here we take a look at the source code:

/** * Intercept The execution of a handler. Called after Handlermapping determined * A appropriate handler object, but before Handleradapter invokes the handler. * <p>dispatcherservlet processes a handler in an execution chain, consisting * of all number of interceptors, with T He handler itself at the end. * With this method, each interceptor can decide to abort the execution chain, * typically sending a HTTP error or writing A custom response. * <p><strong>Note:</strong> Special considerations apply for Asynchronous * request processing. For more details see * {@link org.springframework.web.servlet.AsyncHandlerInterceptor}. * <p>the default implementation returns {@code true}. * @param request Current HTTP request * @param response Current HTTP response * @param handler chosen handler to execute, For type and/or instance evaluation * @return {@code true} if the execution chain should proceed with the * Next intercept Or or the handler itself. Else, DispatCherservlet assumes * This interceptor have already dealt with the response itself. * @throws Exception in case of Errors */default boolean prehandle (httpservletrequest request, httpservletresponse response , Object handler) throws Exception {return true;}
Let's translate the comments above to see how the author explains the method.

The interception method invokes execution before determining the appropriate processing object to call Handlermapping Handleradapter before invoking the handler, that is, the method is called before the request is processed. Spring interceptors are chained and can have multiple interceptors, and when the method executes, it needs to return a Boolean value to tell the interceptor whether to execute the next method. Each interceptor can decide to abort the execution chain, usually sending an HTTP error or writing a custom response if it is the last Interceptor , it will be the one that invokes the current request. Controller Method

/* * * interception handler execution. After calling Handleradapter the actual * call handler, but the rendering view in Dispatcherservlet. * Other object models can be exposed through a given view of the Modelandview. * <P> Dispatcherservlet Process Handler in the execution chain consists of * any number of interception with the processor itself at the end. * With this method, each intercept can be processed after an execution, which is applied in the inverse order of the execution chain. * strong > Note:</strong > Special Considerations apply to Asynchronous * request processing. For more details, see * * link org. Springframework.com.Servlet Asynchandlerinterceptor}. * The default implementation is empty. * @param require the current HTTP request * @param respond to the current HTTP response * @param processor processor (or {@ link Handlermethod}) begins asynchronous * execution, type and/or instance check * @param modelandview {@ Code, the handler returns Modelandview}* (which can also be "@ Code") "throws an exception in case of error" */default void Posthandle (HttpServletRequest request, HttpServletResponse response, Object handler, Modelandview Modelandview) throws Exception {}
Posthandlemethod, as the name implies, after the current request is processed, i.e.Controlleris executed after the method call, but it isDispatcherservletis called before the view is returned to render, so we can do this in the methodControllerafter processing theModelandviewobject to operate. Posthandlemethod is called in the directionPrehandleis the opposite, which means that the first declarationInterceptorof thePosthandlemethod instead will execute after
/* * * After completion of the request processing callback, that is, after rendering * view. Any result that the handler executes will be called, allowing * to clean up the appropriate resources. * <BR> Note: Only in this interceptor {@ Code Prehandle called}* method has successfully completed and returned {code true}! * <BR> with {@ Code Posthandle} method, the method will be called every * in the chain in reverse order, so the first intercept will be * the last one called. * strong > Note:</strong > Special Considerations apply to Asynchronous * request processing. For more details, see * * link org. Springframework. Web site. Servlet Asynchandlerinterceptor}. * The default implementation is empty. * @param require the current HTTP request * @param respond to the current HTTP response * @param processor processor (or {@ link Handlermethod}) begins asynchronous * execution, type and/or instance check * @param the execution of the exception handler thrown before the If any "throws exception in case of error" */default void Aftercompletion (HttpServletRequest request, httpservletresponse response, Object Handler, Exception ex) throws Exception {}
According to the comments we can conclude that this method is alsothe current correspondingInterceptorof thePrehandleThe return value of the method istrueand is executed in the same order as the Posthandle method,
The chain in reverse order, so the first intercept will be the last call, and here the author also emphasizes the applicability of asynchronous programming.

Here the method is mainly used to do resource cleanup work.

Here is a small example where the requirement is to measure the execution time of a particular method, find the pain point and optimize it, which is 3 of the applicable scenario above.

 public class Performanceinterceptor implements handlerinterceptor{/** * Prehandle method is used for processor interception, as the name implies, the method will be in the Cont Roller is called before processing, * The Interceptor interceptor in SPRINGMVC is chained, can exist simultaneously * multiple interceptor, then SPRINGMVC executes one after the other according to the order of the Declaration, * and all The Prehandle method in interceptor is called before the * Controller method call.      SPRINGMVC This interceptor chain structure can also be interrupted, * This mode of interruption is to make the Prehandle return value of false, when the return value of Prehandle is false, the entire request is over. */@Override public boolean prehandle (HttpServletRequest request, HttpServletResponse Response,ob  Ject handler) throws exception{{long startTime = System.currenttimemillis ();              Start time Request.setattribute ("StartTime", startTime);          return true;             /** * This method will only be executed if the current interceptor Prehandle method returns a value of true. * Posthandle is used for processor interception, its execution time is after the processor to process the *, that is, after the controller's method call execution, but it will be in the dispatcherservlet * view Before rendering, * that is, in this method you can do the ModelanDview.              The chain structure of this method is the opposite of the normal access direction, that is to say, the first declaration of the Interceptor Interceptor that the * method will be called after the *, which is a bit like the execution process of the interceptor inside the STRUTS2, * Just Struts2 inside the Intercept method to manually invoke the Actioninvocation Invoke method *, the Invoke method called Actioninvocation in struts is called the next INTERCEP              Tor * or call the action, and then the content to be called before Interceptor is written before invoking invoke, * the content to be called after Interceptor is written after invoking the Invoke method.              */@Override public void Posthandle (httpservletrequest request,httpservletresponse response, Object Handler,modelandview Modelandview) throws exception{long StartTime = (long) Request.getattri Bute ("StartTime");              Gets the start time long endTime = System.currenttimemillis ();   Modelandview.addobject ("Handlingtime", endtime-starttime);         To get the final result}/** * This method is also required when the return value of the Prehandle method of the current corresponding interceptor is true before execution.  * This method will be completed after the entire request, that is, dispatcherservlet rendered view execution, * This method of the main role is to clean up resources, of course, this method can only be in the current interceptor Prehandle       * Execution occurs when the return value of the method is true. */@Override public void aftercompletion (HttpServletRequest request, HttpServletResponse resp   Onse,object handler,exception ex) throws exception{Request.removeattribute ("StartTime");  Resource Reasonable Work}}

Next, we'll configure our XML file

<beans xmlns= "Http://www.springframework.org/schema/beans"      xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:context=" Http://www.springframework.org/schema/context "      xmlns:mvc="/http/ Www.springframework.org/schema/mvc "      xsi:schemalocation=" Http://www.springframework.org/schema/beans       Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd       http://www.springframework.org/schema/ Context       http://www.springframework.org/schema/context/spring-context-3.0.xsd/       http WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MVC       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">  
This allows the MVC tag to be used in the SPRINGMVC configuration file, with an mvc:interceptors in the MVC tag that declares the SPRINGMVC interceptor.

<mvc:interceptors>      <!--using beans to define a interceptor, directly defined under the Mvc:interceptors root interceptor will intercept all requests--      <bean class= "Com.cn.web.interceptor.PerformanceInterceptor"/>  </mvc:interceptors>  






Spring MVC Interceptor

Related Article

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.

Tags Index: