Introduction to the

Interceptors in Java dynamically intercept the object called by an Action. They provide a mechanism for executing code before and after an Action is executed, preventing an Action from executing before it is executed, and a way to extract reusable portions of the Action code. In AOP, interceptors are used to intercept a method or field before it is accessed, and then add some action before or after.

Interceptor code

The Java part

public class HandlerInterceptorAdapter implements HandlerInterceptor {   
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 
            throws Exception{
    }   
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception{
    }   
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception{
    }
}
Copy the code

The spring-MVC configuration section

 <!--配置拦截器, 多个拦截器,顺序执行 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!-- 匹配的是url路径, 如果不配置或/**,将拦截所有的Controller -->
            <mvc:mapping path="/ps/**"/ > <! --<mvc:mapping path="/user/**"/ > -- > <! --<mvc:mapping path="/test/**" />-->
            <bean class="com.weixin.InterceptorAdapter.HandlerInterceptorAdapter"></bean> </mvc:interceptor> <! When setting up multiple interceptors, call the preHandle method in order and then the postHandle and afterCompletion methods for each interceptor in reverse order.Copy the code

Use of interceptors

Interface source code

Public Interface HandlerInterceptor {// Called before the request is processed by the business handler Boolean preHandle(HttpServletRequest var1, HttpServletResponse var2, Object var3) throws Exception; // After the request is processed by the business processor, Void postHandle(HttpServletRequest var1, HttpServletResponse var2, Object var3, ModelAndView var4) throws Exception; // called after the DispatcherServlet has fully processed the request, Void afterCompletion(HttpServletRequest var1, HttpServletResponse Var2, Object Var3, Exception var4) throws Exception; }Copy the code

PreHandle,

The preHandle method takes three parameters: HttpServletRequest HttpServletResponse Object

HttpServletRequest Controls the request parameters of the program before the business handler. HttpServletResponse controls the return parameters of the program after passing through the handler. Object The entity of the intercepted request ActionCopy the code

The return value:

True means to continue the process. False means that the process is interrupted and will not continue to call other interceptors or processors. In this case, we need to generate a response via responseCopy the code

Example:

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object Handler) throws Exception{// Calculate the current server time. Long timeNowForServer=new Date().getTime(); // Get the parameters requested from the front-end interfaceif(null! =request.getParameter("token"String Token = encryptutil.aesDecrypt (request.getParameter()) String token= encryptutil.aesDecrypt (request."token"),"0000000000000000");
            if(null! =token) { Long timeNowForClient = Long.parseLong(token); // Long timeMinus = timeNowForServer - timeNowForClient;if(-50000 <= timeMinus && timeMinus <= 50000) {// Continue the interface processreturn true;
                } else{response.senderror (HTTP status code, page display reason for blocking); response.sendError(405,"Parameters illegal"); // Call back this operation and return the corresponding responsereturn false; }}else{
                response.sendError(405, "Parameters illegal");
                return false; } // if the request address contains getUserInfo, the request will be whitelisted.else if(request.getRequestURI().indexOf("getUserInfo") > 0) {return true;
        }elseResponse.sendredirect (request.getContextPath() +"/Login1.html");                  
             return false; }}Copy the code

For details about the status code, see HTTP Status Code