上文已经详细讲解了如何对request进行处理,本文主要是案例演示
spring MVC 的写法
添加拦截器
- 定义一个拦截器
public class AppRequestInterceptor implements HandlerInterceptor {
/**
* 在请求处理之前执行,
* 该方法主要是用于准备资源数据的,
* 然后可以把它们当做请求属性放到Request中
* @param request
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("AppRequestInterceptor====>preHandle");
// token 校验
String token = request.getHeader("token");
if (token.equals("1")){
return true;
}
// 拦截器返回false则中断请求,利用response进行跳转到错误页面
response.sendRedirect("/tokenError");
return false;
}
/**
* 该方法将在Controller执行之后,
* 返回视图之前执行,ModelMap表示请求Controller处理之后返回的Model对象,所以可以在
* 这个方法中修改ModelMap的属性,从而达到改变返回的模型的效果。
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("AppRequestInterceptor====>preHandle");
}
/**
* 该方法将在整个请求完成之后,
* 也就是说在视图渲染之后进行调用,
* 主要用于进行一些资源的释放
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("AppRequestInterceptor====>preHandle");
}
}
定义一个返回错误信息的请求
@Controller
@RequestMapping("/")
public class ErrorController {
@RequestMapping("tokenError")
@ResponseBody
public String error(){
return JSON.toJSONString(new BackResult(false,"token错误"));
}
}
- 把定义的拦截器类加到SpringMVC中
修改spring-mvc.xml文件
spring-mvc.xml声明
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
使用mvc:interceptors标签来声明需要加入到SpringMVC拦截器链中的拦截器
<!--添加拦截器到springMVC中-->
<mvc:interceptors>
<!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 -->
<!--<bean class="xxx"/>-->
<mvc:interceptor>
<mvc:mapping path="/communicate/*"/>
<bean class="com.dsdj.Interceptor.AppRequestInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
由上面的示例可以看出可以利用mvc:interceptors标签声明一系列的拦截器,然后它们就可以形成一个拦截器链,拦截器的执行顺序是按声明的先后顺序执行的,先声明的拦截器中的preHandle方法会先执行,然而它的postHandle方法和afterCompletion方法却会后执行。
在mvc:interceptors标签下声明interceptor主要有两种方式:
(1)直接定义一个Interceptor实现类的bean对象。使用这种方式声明的Interceptor拦截器将会对所有的请求进行拦截。
(2)使用mvc:interceptor标签进行声明。使用这种方式进行声明的Interceptor可以通过mvc:mapping子标签来定义需要进行拦截的请求路径。
经过上述两步之后,定义的拦截器就会发生作用对特定的请求进行拦截了
经测试成功:根据上一篇的内容,我们可以进行更多的处理,这里就不赘述了,说明一下token获取之后,在controller中还可以获取,不会失效,而获取request的值进行校验的话,需要使用上一篇文章讲的知识了。