Java - Spring MVC interceptors

Interceptor (Interceptor) URL requests for pre / post-filter.

Filter Interceptor and use similar, but different implementations.

Interceptor is SpringMVC of standard components, Interceptor after being created is natural to run in the IOC container. ,

Filter J2EE is a standard component, except Filter container by different manufacturers achieved.

Interceptor is based on the underlying SpringAOP Aspect Oriented Programming.

Interceptor development process:
  Maven dependent servlet-api
  implement the interface HandlerLnterceptor
  applicationContext.xml arranged interception

 

1. The use of substantially interceptors

(1) introducing dependencies

< Dependency > 
    < the groupId > the javax.servlet </ the groupId > 
    < the artifactId > the javax.servlet-api </ the artifactId > 
    < Version > 3.1.0 </ Version > 
    <-! Prevent tomcat servlet configuration comes with the api each api conflict -> 
    <-! Provided means that only developers will be compiled in a reference -> 
    < scope > Provided </ scope > 
</ dependency >

(2) an interface implemented HandlerLnterceptor

// interceptor must inherit HandlerInterceptor Interface 
public  class myInterceptor the implements HandlerInterceptor {
     // must also implement the following three methods
     // preHandler: pre-execution processing
     // postHandle: target resource has been SpringMVC frame processed after the return, but also no response before the text.
    // afterCompletion: text response has been generated, such as automatically after serialization jackson 
    public  Boolean The preHandle (the HttpServletRequest Request, Response the HttpServletResponse, Object Handler) throws Exception { 
        System.out.println (request.getRequestURL () + "ready to execute" ) ;
         // must return a boolean value, true transfer request will backward (blocking or controller), false request is blocked, in response returned directly 
        return  to true ;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println(request.getRequestURL() + "目标处理成功");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println(request.getRequestURL() + "响应内容已产生");
    }
}

(3) applicationContext.xml interception configuration

< MVC: interceptors > 
    < MVC: Interceptor > 
        <-! Intercepts that the URL of -> 
        < MVC: Mapping path = "/ **" /> 
        <-! Use after interceptor class which handled -> 
        < the bean class = "com.ikidana.restful.interceptor.MyInterceptor" /> 
    </ MVC: Interceptor > 
</ MVC: interceptors >

(4) results of the tests

If you visit: http: // localhost: 8080 / restful / persons

following message appears:
http: // localhost: 8080 / restful / persons ready to execute
http: // localhost: 8080 / restful / persons treatment success target
http: // localhost: 8080 / restful / persons generated response content

 

2.Interceptor tips

(1) exclude interception of static resources

By configuring the applicationContext.xml to:

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**"/>
        <!--对那些资源不进行拦截-->
        <mvc:exclude-mapping path="/**.ico"/>
        <mvc:exclude-mapping path="/**.jpg"/>
        <mvc:exclude-mapping path="/**.gif"/>
        <mvc:exclude-mapping path="/**.js"/>
        <mvc:exclude-mapping path="/**.css"/>
        <bean class="com.ikidana.restful.interceptor.MyInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>

But the above configuration problems are: CI may be a lot
we can all put under all the static files in a directory, this directory can intercept:

 

 Below is to intercept the entire directory:
<MVC: Mapping the exclude-path = "/ Resources / **" />
for a certain prefixes too:
<MVC: Mapping the exclude-path = "/ RESTful / **" />

(2) If a request is intercepted multiple interceptors, which will first perform a?

  If we configure multiple interceptors:

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**"/>
        <bean class="com.ikidana.restful.interceptor.MyInterceptor"/>
    </mvc:interceptor>
    <mvc:interceptor>
        <mvc:mapping path="/**"/>
        <bean class="com.ikidana.restful.interceptor.MyInterceptor1"/>
    </mvc:interceptor>
</mvc:interceptors>

If you visit http: // localhost: 8080 / restful / persons that the URL of:
http: // localhost: 8080 / restful / persons ready to execute
http: // localhost: 8080 / restful / persons ready to execute -1
HTTP: // localhost: 8080 / restful / persons treated successfully target -1
http: // localhost: 8080 / restful / persons handling target success
http: // localhost: 8080 / restful / persons have been generated in response to the contents of -1
HTTP: // localhost: 8080 / RESTful / persons generated response content

 

According to the processing order is not entirely practical configurations:

 

 Somewhat similar to python in middleware

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    System.out.println(request.getRequestURL() + "准备执行");
    response.getWriter().println("拦截器返回");
    return false;
}

Interceptor can directly control the return value.
Whether or middleware interceptors are particularly useful for processing Log in Register.

 

3. User Information Collection interceptor base development

(1) introduced into log-dependent

<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
</dependency>

(2) configuration log format, stores it in the directory

<? Xml Version = "1.0" encoding = "UTF-8" ?> 
< The Configuration > 
    <-! RollingFileAppender adder for generating a daily rolling log file -> 
    < appender name = "accessHistoryLog" class = "CH. qos.logback.core.rolling.RollingFileAppender " > 
        <-! rollingPolicy rolling strategy, TimeBasedRollingPolicy rolling in time -> 
        < rollingPolicy class =" ch.qos.logback.core.rolling.TimeBasedRollingPolicy " > 
            <-! configuration log storage path -> 
            < fileNamePattern > . C: \ java_study \ Project \ RESTful \ log \ D RESTful%.log</fileNamePattern>
        </ RollingPolicy > 
        <-! Define the format of the output log -> 
        < Encoder > 
            < pattern > [% Thread] D%%% Level Logger {10} - n-% MSG% </ pattern > 
        </ Encoder > 
    </ appender > 
    <-! lowest log output level is debug, output addresses for the console -> 
    <-! AccessHistoryInterceptor this class generated logs will use the following rules generated by the label -> 
    <-! additivity whether , false output to the console output only to the specified rules -> 
    < Logger name = "com.ikidana.restful.interceptor.AccessHistoryInterceptor" Level = "info" additivity="false">
        <appender-ref ref="accessHistoryLog"/>
    </logger>
</configuration>

(3) create interceptors, and fill in the information

public class AccessHistoryInterceptor implements HandlerInterceptor {
    //创建一个logger日志对象
    private Logger logger = (Logger) LoggerFactory.getLogger(AccessHistoryInterceptor.class);

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StringBuilder log = new StringBuilder();
        log.append(request.getRemoteAddr());  //地址
        log.append("|");
        log.append(request.getRequestURL());  //URL
        log.append("|");
        log.append(request.getHeader("user-agent"));
        logger.info(log.toString());
        return true;
    }
}

(4) registered for use

<mvc:interceptor>
    <mvc:mapping path="/**"/>
    <bean class="com.ikidana.restful.interceptor.AccessHistoryInterceptor"/>
</mvc:interceptor>

(5) the effect of

 

 

4.SpringMVC process flow

 

Guess you like

Origin www.cnblogs.com/yangmingxianshen/p/12521619.html