首页 > 代码库 > SpringMVC的拦截器

SpringMVC的拦截器

一、先写一个拦截器(新建一个Class,实现HandlerInterceptor接口,他会重写3个方法)

package com.hd.common.interceptor;

import java.util.ArrayList;

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

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


public class ValidationInterceptor implements HandlerInterceptor{

@Override
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
//主要是执行完方法,做资源的释放
System.out.println("会在请求Controller方法执行完毕后执行");

}

@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {

System.out.println("会在请求Controller方法执行完毕后,跳转到下个页面(请求)之前执行");


}

@Override
public boolean preHandle(HttpServletRequest req,
HttpServletResponse resp,
Object obj) throws Exception {

System.out.println("会在请求Controller方法之前执行");

if(req.getSession().getAttribute("userid")==null){
resp.sendRedirect("login.html");
return false;
}

//是否有该权限("获取调用方法上面的注解值")
RequestMapping rm=null;
String[] v = rm.value();
//从数据库查询出来的权限值 根据userid查数据库权限
ArrayList list = new ArrayList<String>();
list.add("/save.do");
list.add("/find.do");
//匹配注解上的值/save.do
if(list.contains(v)){
//代表有权限
return true;
}

return true;
}
}

在SpringMVC的配置文件中配置

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!-- 公共配置 扫描所有模块的控制器,给所有的控制器加入后缀.jsp -->

<context:component-scan
base-package="com.hd.controll"/>
<bean id="dao" class="com.hd.dao.UserDao"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/> <!-- 拦截任意包、子包下所有.do请求, -->
<mvc:exclude-mapping path="/isLogin.do"/><!-- 不拦截某些.do请求, -->
<bean class="com.hd.common.interceptor.ValidationInterceptor"/> <!--把自定义拦截器配置进来 -->
</mvc:interceptor>
</mvc:interceptors>



</beans>

SpringMVC的拦截器