SpringMVC的拦截器Inceptor

源码请见SpringMVCInceptorDemo

一、 目标
  1. 编写拦截器,拦截请求
二、 项目代码
  1. 像以往一样完成控制器的逻辑
  2. 编写Inceptor拦截器需要实现HandlerInterceptor接口
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class MyFiddle1 implements HandlerInterceptor{

    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyFiddle1.preHandle");
        return true;
    }

    public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        System.out.println("MyFiddle1.postHandle");
    }

    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("MyFiddle1.afterCompletion");
    }

}
  1. 配置拦截器
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    ...
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/*/h1" />
            <bean class="cn.dectfix.inceptor.MyFiddle1"></bean>
        </mvc:interceptor>
        <bean class="cn.dectfix.inceptor.MyFiddle2"></bean>
    </mvc:interceptors>
    ...
</beans>

需要配置mvc:interceptors,这里可以直接在其中指定bean类,默认对所有传入连接都进行拦截;也可以使用mvc:interceptor及mvc:mapping对拦截器设置过滤得链接后缀。

三、 原理描述

启动项目后,访问不同链接试试,看有没有触发指定的拦截器。你会说,我的请求没有别拦截啊!等等,这里拦截了请求,实现HandlerInterceptor接口的类有3个方法,拦截过程中,其生命周期如下所示:

Created with Raphaël 2.1.0 preHandle 拦截? WARN PAGE postHandle afterCompletion yes no

只是在preHandle方法中都反悔了true值,所以postHandle、afterCompletion也执行了!

preHandle返回true:不拦截请求;
preHandle返回false:拦截住了请求;

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MEMORYLORRY

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值