[Interceptor] java web inteceptor

I. Introduction

non-system-level interceptor to intercept java in the offer, that is, on the coverage, the interceptor is better to filter powerful, but more targeted.
The Java-based interceptors, more accurate division of Java reflection mechanism to achieve, should be based on the JDK dynamic proxy implementation. It depends on the specific interface, dynamically generated bytecode during operation.
Interceptors are moving to intercept the object Action called, it provides a mechanism that allows developers to execute a piece of code before and after the execution of an Action, can also prevent its prior to the implementation of an Action
execution, but also provides a possible extraction of Action part of the code reusable manner. In AOP, the interceptor for a method or a field prior to being accessed, then intercepting before or
after the join certain operations. java interceptor is mainly used in the plug-on extensions such as Hibernate Spring Struts2 etc., somewhat similar for slicing technology, first used in that thing before the configuration file that is xml, file section of the declaration.

SpringMVC The main role is to intercept Interceptor interceptor user request url , with particular requests and added before and after the execution handler method, similar to the inside of the servlet filter.

Interceptor SpringMVC the interceptor is also very important and very useful, and its primary role is to intercept the user's request and performs corresponding processing. For example, by it for permission to verify , or to determine whether the user login , or is it looks like 12306 to determine whether the current time is the time of purchase.

Second, the application scenarios

  1, logging, logging may be a request for information, information for monitoring, statistics and other information.
  2, permission checks: detection, such as landing, into the processor detects whether the landing, if not directly back to the login page.
  3, performance monitoring: typically slow logs.

Third, to achieve

3.1 implementation

Interceptor interception request is SpringMVC by HandlerInterceptor  achieved. In SpringMVC Interceptor define a very simple, there are two main ways,

method one:

  Interceptor class definition to achieve the Spring of HandlerInterceptor  interface, or is this class inherits HandlerInterceptor class that implements the interface, such as Spring already provided to achieve the abstract class HandlerInterceptorAdapter HandlerInterceptor interface;

Second way:

  Spring realization of WebRequestInterceptor interface, or inherited achieved WebRequestInterceptor class.

Implement HandlerInterceptor Interface Description:

HandlerInterceptor interface defines three methods, we are treated to intercept the user's request through these three methods.

(1) preHandle (HttpServletRequest request, HttpServletResponse response, Object handle) method, as the name implies, this method will be called before the request processing. SpringMVC Interceptor is a chain of calls, or may be present in a plurality of request Interceptor simultaneously in one application. Each call to the Interceptor sequentially performed in terms of its declaration order, the first and preHandle Interceptor methods are executed, it is possible to make some pre-initialization in this method is a pretreatment, or the current request, and you can make some judgment in this method to determine whether the request should continue. The return value of this process is Boolean Boolean type, when it returns to false, indicating the end of the request, and the subsequent Interceptor Controller will no longer performed; when the return value is true preHandle will continue to call a method in the Interceptor If a Interceptor is the last time will be calling Controller method the current request.

(2) postHandle (HttpServletRequest request, HttpServletResponse response, Object handle, ModelAndView modelAndView) method, a method of interpretation preHandle we know this method include the back to say to afterCompletion method can only be returned in preHandle method of Interceptor currently belongs in order to be called when the value is true. postHandle method, by definition is after the current request is processed, which is executed after Controller method call, but it would be to be called before the view returns rendered DispatcherServlet, so we can operate on ModelAndView object after Controller process in this method. Direction with preHandle postHandle method is called is reversed, postHandle Interceptor method of execution that is contrary to the statement after the meeting, which Interceptor and implementation of Struts2 inside a little type. Execution of Struts2 inside the Interceptor is a chain, but the inside needs to call Struts2 manually invoke methods ActionInvocation to trigger the next Interceptor or Action calls, then the contents of each Interceptor before invoke method calls are in accordance with declaration order execution, and after the contents invoke method is reversed.

(3) afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex), the method also requires a current corresponding to the Interceptor preHandle method are performed when the return value is true. As the name implies, the method after the entire request, that is a corresponding view DispatcherServlet rendered after execution. The main role of this method is that the resources for clean-up work.

3.2 Implementation Example

Directly on the code:

3.2.1 custom interceptor class
package com.my.dm.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class TestInterceptor implements HandlerInterceptor {

        private Logger logger =LogManager.getLogger(TestInterceptor.class);
                                                     
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
        logger.error("afterCompletion");
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        // TODO Auto-generated method stub
        logger.error("postHandle");
    }

    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
        // TODO Auto-generated method stub
        logger.error("preHandle");
        return true;
    }

}
3.2.2 configuration corresponding to a single interceptor
<!-- 配置拦截器 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**" />
            <bean class="com.my.dm.interceptor.TestInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
3.2.3 Configuration for multiple interceptors
<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/employee/**" />
            <mvc:mapping path="/trainning/**" />
            <mvc:mapping path="/manage/**" /> 
            <mvc:exclude-mapping path="/**/fonts/*" />
            <mvc:exclude-mapping path="/**/*.css" />
            <mvc:exclude-mapping path="/**/*.js" />
            <mvc:exclude-mapping path="/**/*.png" />
            <mvc:exclude-mapping path="/**/*.gif" />
            <mvc:exclude-mapping path="/**/*.jpg" />
            <mvc:exclude-mapping path="/**/*.jpeg" />
            <bean class="com.pmo.interceptor.PageInterceptor" />
        </mvc:interceptor>
        <mvc:interceptor>  
                <mvc:mapping path="/**"/>
                <bean class="com.pmo.interceptor.LoginInterceptor"></bean>  
        </mvc:interceptor>
        <mvc:interceptor>  
                <mvc:mapping path="/**"/>
                <bean class="com.pmo.interceptor.UserAuthorityInterceptor"></bean>  
        </mvc:interceptor>
    </mvc:interceptors> 

Since the main reference:

https://www.cnblogs.com/lukelook/p/11079113.html#t2

https://www.jianshu.com/p/82ae825b849b

Guess you like

Origin www.cnblogs.com/wjqhuaxia/p/12148177.html