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. 配置拦截器
"1.0" encoding="UTF-8"?>
"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">
    ...
    
        
            "/*/h1" />
            "cn.dectfix.inceptor.MyFiddle1">
        
        "cn.dectfix.inceptor.MyFiddle2">
    
    ...

需要配置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:拦截住了请求;

你可能感兴趣的:(Java,spring,mvc,inceptor)