1. ホーム
  2. Java

SpringMvc Interceptorインターセプターの設定と使用方法

2022-02-26 09:59:27
package com.springmvc.controller;

import com.springmvc.entity.User;
import com.springmvc.service.UserService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class ViewController {

    private Logger logger = Logger.getLogger(ViewController.class);

    @Resource(name = "UserService")
    private UserService userService;

    @RequestMapping("/index")
    public String index() {
        logger.info("Enter index method");
        return "index";
    }

    @RequestMapping("/find")
    @ResponseBody
    public Map<String, Object> find(User user, HttpServletRequest request) {
        Map<String, Object> map = new HashedMap();
        logger.info("Enter find method");
        List<User> loginuser = userService.findByUsernameAndPwd(user.getUsername(), user.getPassword());
        if (loginuser ! = null) {
            map.put("result", "success");
        } else {
            map.put("result", "fail");
        }
        return map;
    }

    @RequestMapping("/success")
    public String success() {
        logger.info("Enter success method");
        return "success";
    }
}
package com.springmvc.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

public class MyInterceptor implements HandlerInterceptor {
    private final static Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("Enter preHandle method... " + request.getRequestURL().toString() + "," + request.getRequestURI());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.info("Enter postHandle method... " + request.getRequestURL().toString() + "," + request.getRequestURI());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("Enter afterCompletion method... " + request.getRequestURL().toString() + "," + request.getRequestURI());
    }
}


    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/user/index"/>
            <bean class="com.springmvc.intercepter.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

2018-02-28 17:32:40,869 -[DEBUG] method:[org.springframework.web.servlet.DispatcherServlet (12488ms)] - Last-Modified value for [/user/ index] is: -1
2018-02-28 17:32:40,870 -[INFO] method:[com.springmvc.controller.ViewController (12489ms)] - Entering index method
2018-02-28 17:32:41,086 -[DEBUG] method:[org.springframework.web.servlet.view.BeanNameViewResolver (12705ms)] - No matching bean found for view name 'index'
2018-02-28 17:32:41,087 -[DEBUG] method:[org.springframework.web.servlet.DispatcherServlet (12706ms)] - Rendering view [org. springframework.web.servlet.view.JstlView: name 'index'; URL [/WEB-INF/page/index.jsp]] in DispatcherServlet with name 'SpringMVC'
2018-02-28 17:32:41,087 -[DEBUG] method:[org.springframework.web.servlet.view.JstlView (12706ms)] - Forwarding to resource [/WEB-INF/page/ index.jsp] in InternalResourceView 'index'
2018-02-28 17:32:41,088 -[DEBUG] method:[org.springframework.web.servlet.DispatcherServlet (12707ms)] - Successfully completed request
2018-02-28 17:33:03,505 -[DEBUG] method:[org.springframework.web.servlet.DispatcherServlet (35124ms)] - DispatcherServlet with name ' SpringMVC' processing POST request for [/user/find]
2018-02-28 17:33:03,508 -[DEBUG] method:[org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping (35127ms)] - Looking up handler method for path /user/find
2018-02-28 17:33:03,508 -[DEBUG] method:[org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping (35127ms)] - Returning handler method [public java.util.Map<java.lang.String, java.lang.Object> com.springmvc.controller.ViewController.find( com.springmvc.entity.User,javax.servlet.http.HttpServletRequest)]
2018-02-28 17:33:03,508 -[DEBUG] method:[org.springframework.beans.factory.support.DefaultListableBeanFactory (35127ms)] - Returning cached instance of singleton bean 'viewController'
2018-02-28 17:33:05,084 - [INFO] method:[com.springmvc.intercepter.MyIntercepter (36703ms)] - Entering preHandle method... .http://localhost:8080/user/find,/user/find
2018-02-28 17:33:05,144 -[INFO] method:[com.springmvc.controller.ViewController (36763ms)] - Go to the find method
2018-02-28 17:33:05,326 -[DEBUG] method:[org.mybatis.spring.SqlSessionUtils (36945ms)] - Creating a new SqlSession
2018-02-28 17:33:05,343 - [DEBUG] method:[org.mybatis.spring.SqlSessionUtils (36962ms)] - SqlSession [org.apache.ibatis.session.defaults. DefaultSqlSession@3e3b62ad] was not registered for synchronization because synchronization is not active
2018-02-28 17:33:05,446 -[DEBUG] method:[org.springframework.jdbc.datasource.DataSourceUtils (37065ms)] - Fetching JDBC Connection from DataSource
2018-02-28 17:33:05,488 -[D

spring-mvc.xmlを使用します。

<! -- Configure interceptors for session validation -->
    <! -- 
        If there are multiple interceptors that meet the requirements for interception processing, they are executed according to the order of configuration
     -->
    <mvc:interceptors>
        <mvc:interceptor>
            <! -- intercept all requests, this must be written first, i.e. above the [no intercept] -->
            <mvc:mapping path="/**" />
            <! -- but excluding the following, i.e. not intercepting requests -->
            <mvc:exclude-mapping path="/login.html" />
            <mvc:exclude-mapping path="/account/login.do" />
            <mvc:exclude-mapping path="/account/regist.do" />
            <bean class="com.msym.cloudnote.interceptors.SessionInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>

ユーザー/インデックス

ログインをクリックし、最初にuser/findを実行し、次にuser/successを実行し、成功したら。

インターセプトで/user/indexが削除されるため、preHanle, postHandle, afterCompletionメソッドのログが出力されない

インターセプトでは /user/find が削除されないため、ログには preHanle、postHandle、afterCompletion の各メソッドのログが出力されます。

インターセプトでは /user/success が削除されないため、preHanle, postHandle, afterCompletion メソッドのログが出力されます。

ログをよく見てください、開始からログイン成功まで(ログの裏には驚きの事実があります)

2018-02-28 17:32:40,869 -[DEBUG] method:[org.springframework.web.servlet.DispatcherServlet (12488ms)] - Last-Modified value for [/user/ index] is: -1
2018-02-28 17:32:40,870 -[INFO] method:[com.springmvc.controller.ViewController (12489ms)] - Entering index method
2018-02-28 17:32:41,086 -[DEBUG] method:[org.springframework.web.servlet.view.BeanNameViewResolver (12705ms)] - No matching bean found for view name 'index'
2018-02-28 17:32:41,087 -[DEBUG] method:[org.springframework.web.servlet.DispatcherServlet (12706ms)] - Rendering view [org. springframework.web.servlet.view.JstlView: name 'index'; URL [/WEB-INF/page/index.jsp]] in DispatcherServlet with name 'SpringMVC'
2018-02-28 17:32:41,087 -[DEBUG] method:[org.springframework.web.servlet.view.JstlView (12706ms)] - Forwarding to resource [/WEB-INF/page/ index.jsp] in InternalResourceView 'index'
2018-02-28 17:32:41,088 -[DEBUG] method:[org.springframework.web.servlet.DispatcherServlet (12707ms)] - Successfully completed request
2018-02-28 17:33:03,505 -[DEBUG] method:[org.springframework.web.servlet.DispatcherServlet (35124ms)] - DispatcherServlet with name ' SpringMVC' processing POST request for [/user/find]
2018-02-28 17:33:03,508 -[DEBUG] method:[org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping (35127ms)] - Looking up handler method for path /user/find
2018-02-28 17:33:03,508 -[DEBUG] method:[org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping (35127ms)] - Returning handler method [public java.util.Map<java.lang.String, java.lang.Object> com.springmvc.controller.ViewController.find( com.springmvc.entity.User,javax.servlet.http.HttpServletRequest)]
2018-02-28 17:33:03,508 -[DEBUG] method:[org.springframework.beans.factory.support.DefaultListableBeanFactory (35127ms)] - Returning cached instance of singleton bean 'viewController'
2018-02-28 17:33:05,084 - [INFO] method:[com.springmvc.intercepter.MyIntercepter (36703ms)] - Entering preHandle method... .http://localhost:8080/user/find,/user/find
2018-02-28 17:33:05,144 -[INFO] method:[com.springmvc.controller.ViewController (36763ms)] - Go to the find method
2018-02-28 17:33:05,326 -[DEBUG] method:[org.mybatis.spring.SqlSessionUtils (36945ms)] - Creating a new SqlSession
2018-02-28 17:33:05,343 - [DEBUG] method:[org.mybatis.spring.SqlSessionUtils (36962ms)] - SqlSession [org.apache.ibatis.session.defaults. DefaultSqlSession@3e3b62ad] was not registered for synchronization because synchronization is not active
2018-02-28 17:33:05,446 -[DEBUG] method:[org.springframework.jdbc.datasource.DataSourceUtils (37065ms)] - Fetching JDBC Connection from DataSource
2018-02-28 17:33:05,488 -[D

インターセプトの削除、メソッドの実行順序。
ViewController.index()


インターセプト、メソッドの実行順。(上から下へ)
HandlerExecutionChain.applyPreHandle()を実行します。
MyInterceptor.preHandle()を実行します。
ViewController.find()
HandlerExecutionChain.applyPostHandle()を実行します。
MyInterceptor.postHandle()
HandlerExecutionChain.triggerAfterCompletion()を実行します。
MyInterceptor.afterCompletion()を実行します。
新しいページにジャンプする

コンフィギュレーションに関する注意事項。

<! -- Configure interceptors for session validation -->
    <! -- 
        If there are multiple interceptors that meet the requirements for interception processing, they are executed according to the order of configuration
     -->
    <mvc:interceptors>
        <mvc:interceptor>
            <! -- intercept all requests, this must be written first, i.e. above the [no intercept] -->
            <mvc:mapping path="/**" />
            <! -- but excluding the following, i.e. not intercepting requests -->
            <mvc:exclude-mapping path="/login.html" />
            <mvc:exclude-mapping path="/account/login.do" />
            <mvc:exclude-mapping path="/account/regist.do" />
            <bean class="com.msym.cloudnote.interceptors.SessionInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>

  1. preHandle は、ビジネスプロセッサがリクエストを処理する前に呼び出されます。
  2. postHandleは、リクエストがサービスプロセッサによって処理された後、ビューが生成される前に実行されます。
  3. afterCompletionは、DispatcherServletがリクエストを完全に処理した後に呼び出され、リソースのクリーンアップなどに使用されることがあります。 AfterCompletion() が実行され、ページがレンダリングされます。

preHandleがfalseを返した場合、リクエストはそれ以上下に処理されません。

参考:https://www.cnblogs.com/daimajun/p/7172208.html

http://blog.csdn.net/huangjp_hz/article/details/73614314

今までインターセプターが何をするものなのか理解していなかったのですが、とてもハイレベルなものだと思っていたのですが、そうでもないのですね。インターセプターとは、特定のリクエストを傍受して、それに何らかの処理を追加するものです。