SpringMvc Interceptor拦截器的配置与使用

Java 同时被 2 个专栏收录
515 篇文章 2 订阅
23 篇文章 0 订阅
 
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("进入 index 方法");
        return "index";
    }

    @RequestMapping("/find")
    @ResponseBody
    public Map<String, Object> find(User user, HttpServletRequest request) {
        Map<String, Object> map = new HashedMap();
        logger.info("进入 find 方法");
        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("进入 success 方法");
        return "success";
    }
}
package com.springmvc.intercepter;

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("进入 preHandle 方法..." + request.getRequestURL().toString() + "," + request.getRequestURI());
        return true;
    }

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

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

spring-mvc.xml:

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

user/index

点击登录,先执行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)] - 进入 index 方法
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)] - 进入 preHandle 方法...http://localhost:8080/user/find,/user/find
2018-02-28 17:33:05,144 -[INFO]  method:[com.springmvc.controller.ViewController (36763ms)] - 进入 find 方法
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 -[DEBUG]  method:[org.mybatis.spring.transaction.SpringManagedTransaction (37107ms)] - JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@6bf8a75f] will not be managed by Spring
2018-02-28 17:33:05,546 -[DEBUG]  method:[com.springmvc.dao.UserDao.findByUsernameAndPwd (37165ms)] - ==>  Preparing: SELECT id, username, password, sex FROM t_user WHERE username =? AND password =? 
2018-02-28 17:33:05,628 -[DEBUG]  method:[com.springmvc.dao.UserDao.findByUsernameAndPwd (37247ms)] - ==> Parameters: Tom(String), 123(String)
2018-02-28 17:33:05,696 -[DEBUG]  method:[com.springmvc.dao.UserDao.findByUsernameAndPwd (37315ms)] - <==      Total: 1
2018-02-28 17:33:05,698 -[DEBUG]  method:[com.alibaba.druid.pool.PreparedStatementPool (37317ms)] - {conn-10001, pstmt-20000} enter cache
2018-02-28 17:33:05,699 -[DEBUG]  method:[org.mybatis.spring.SqlSessionUtils (37318ms)] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3e3b62ad]
2018-02-28 17:33:05,700 -[DEBUG]  method:[org.springframework.jdbc.datasource.DataSourceUtils (37319ms)] - Returning JDBC Connection to DataSource
2018-02-28 17:33:05,762 -[DEBUG]  method:[org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdviceChain (37381ms)] - Invoking ResponseBodyAdvice chain for body={result=success}
2018-02-28 17:33:05,763 -[DEBUG]  method:[org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdviceChain (37382ms)] - After ResponseBodyAdvice chain body={result=success}
2018-02-28 17:33:05,779 -[DEBUG]  method:[org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor (37398ms)] - Written [{result=success}] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@1782747b]
2018-02-28 17:33:06,555 -[INFO]  method:[com.springmvc.intercepter.MyIntercepter (38174ms)] - 进入 postHandle 方法...http://localhost:8080/user/find,/user/find
2018-02-28 17:33:06,556 -[DEBUG]  method:[org.springframework.web.servlet.DispatcherServlet (38175ms)] - Null ModelAndView returned to DispatcherServlet with name 'SpringMVC': assuming HandlerAdapter completed request handling
2018-02-28 17:33:06,795 -[INFO]  method:[com.springmvc.intercepter.MyIntercepter (38414ms)] - 进入 afterCompletion 方法...http://localhost:8080/user/find,/user/find
2018-02-28 17:33:06,796 -[DEBUG]  method:[org.springframework.web.servlet.DispatcherServlet (38415ms)] - Successfully completed request
2018-02-28 17:33:06,815 -[DEBUG]  method:[org.springframework.web.servlet.DispatcherServlet (38434ms)] - DispatcherServlet with name 'SpringMVC' processing GET request for [/user/success]
2018-02-28 17:33:06,816 -[DEBUG]  method:[org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping (38435ms)] - Looking up handler method for path /user/success
2018-02-28 17:33:06,817 -[DEBUG]  method:[org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping (38436ms)] - Returning handler method [public java.lang.String com.springmvc.controller.ViewController.success()]
2018-02-28 17:33:06,817 -[DEBUG]  method:[org.springframework.beans.factory.support.DefaultListableBeanFactory (38436ms)] - Returning cached instance of singleton bean 'viewController'
2018-02-28 17:33:06,818 -[DEBUG]  method:[org.springframework.web.servlet.DispatcherServlet (38437ms)] - Last-Modified value for [/user/success] is: -1
2018-02-28 17:33:07,203 -[INFO]  method:[com.springmvc.intercepter.MyIntercepter (38822ms)] - 进入 preHandle 方法...http://localhost:8080/user/success,/user/success
2018-02-28 17:33:07,204 -[INFO]  method:[com.springmvc.controller.ViewController (38823ms)] - 进入 success 方法
2018-02-28 17:33:07,423 -[INFO]  method:[com.springmvc.intercepter.MyIntercepter (39042ms)] - 进入 postHandle 方法...http://localhost:8080/user/success,/user/success
2018-02-28 17:33:07,424 -[DEBUG]  method:[org.springframework.web.servlet.view.BeanNameViewResolver (39043ms)] - No matching bean found for view name 'success'
2018-02-28 17:33:07,425 -[DEBUG]  method:[org.springframework.beans.factory.support.DefaultListableBeanFactory (39044ms)] - Invoking afterPropertiesSet() on bean with name 'success'
2018-02-28 17:33:07,425 -[DEBUG]  method:[org.springframework.web.servlet.DispatcherServlet (39044ms)] - Rendering view [org.springframework.web.servlet.view.JstlView: name 'success'; URL [/WEB-INF/page/success.jsp]] in DispatcherServlet with name 'SpringMVC'
2018-02-28 17:33:07,426 -[DEBUG]  method:[org.springframework.web.servlet.view.JstlView (39045ms)] - Forwarding to resource [/WEB-INF/page/success.jsp] in InternalResourceView 'success'
2018-02-28 17:33:07,695 -[INFO]  method:[com.springmvc.intercepter.MyIntercepter (39314ms)] - 进入 afterCompletion 方法...http://localhost:8080/user/success,/user/success
2018-02-28 17:33:07,695 -[DEBUG]  method:[org.springframework.web.servlet.DispatcherServlet (39314ms)] - Successfully completed request

去除拦截,方法执行顺序:
ViewController.index()


拦截,方法执行顺序:(由上至下)
HandlerExecutionChain.applyPreHandle()
MyInterceptor.preHandle()
ViewController.find()
HandlerExecutionChain.applyPostHandle()
MyInterceptor.postHandle()
HandlerExecutionChain.triggerAfterCompletion()
MyInterceptor.afterCompletion()
跳转到新页面

配置说明:

<!-- 配置用于session验证的拦截器 -->
    <!-- 
        如果有多个拦截器满足拦截处理的要求,则依据配置的先后顺序来执行
     -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!-- 拦截所有的请求,这个必须写在前面,也就是写在【不拦截】的上面 -->
            <mvc:mapping path="/**" />
            <!-- 但是排除下面这些,也就是不拦截请求 -->
            <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

 

之前一直不明白拦截器干啥的,觉得很高大上,其实也没啥,拦截器就是拦截某些请求的,同时会附加一些处理。

 

更多企业内的技术应用和使用技巧,请移步至我的公众号【程序员实用技能】

图片

  • 19
    点赞
  • 3
    评论
  • 38
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值