SpringMVC的拦截器 Interceptor
Interceptor是SpringMVC框架的,它拦截所有请求Controller(即Handler处理器)对象中业务方法的http请求。
示例程序实现步骤:
0、准备工作
1、自定义拦截器类
实现HandlerInterceptor接口
2、spring-mvc.xml中配置拦截器
3、部署项目,进行测试
0、准备工作
1)写Controller类与处理器方法
@Controller
public class TargetController {
@RequestMapping("/target")
public ModelAndView show(){
System.out.println("目标资源执行......");
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("name","leap");//通过ModelAndView对象给前端页面传递数据
modelAndView.setViewName("index");
return modelAndView;
}
}
2)准备前端页面 index.jsp
上一步用到的
<html>
<body>
<h2>Hello World! ${name}</h2>
</body>
</html>
3)准备spring-mvc.xml,做好所需配置
需要什么配置呢?
(1)组件扫描
(2)mvc注解驱动
(3)静态资源访问权限开放
(4)视图解析器 因为用到了ModelAndView
<?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: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.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
">
<!--组件扫描 扫描Controller-->
<context:component-scan base-package="com.yeats.controller"/>
<!--mvc注解驱动-->
<mvc:annotation-driven/>
<!--静态资源权限开放-->
<mvc:default-servlet-handler/>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
4)web.xml中配置好DispatcherServlet
使用SpringMVC框架,必配的内容!
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
1、自定义拦截器类
想要自定义的拦截器类成为SpringMVC框架管理的类,需要实现HandlerInterceptor接口。
public class MyInterceptor implements HandlerInterceptor {
/**
* 在请求的业务方法执行前,执行
*
* @param request 当前http请求对象
* @param response 当前http响应对象
* @param handler DispatcherServlet为当前http请求调度来的处理器。
* @return 返回true,放行;返回false,不放行。
* 返回false时,DispatcherServlet认为该拦截器已经将http请求处理了,不再为其进行调度。
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle() running...");
//获取请求参数
/*
测试中,请求URL带上参数flag=true或者flag=false
表示要不要放行
*/
String flag = request.getParameter("flag");
//判断
if ("true".equalsIgnoreCase(flag)) {
//放行前做点操作
request.getSession().setAttribute("name", "我是preHandle()!");
//放行
return true;
} else {
System.out.println("请求中没请我放行,不放!");
//不放行,也得做点什么(即对拦下来的http请求,自己做处理)
//通过请求转发,跳转到某个页面
request.getRequestDispatcher("/error.jsp").forward(request, response);
//不放行
return false;
}
}
/**
* 在Controller中业务方法执行后、页面渲染前,执行。
* preHandle()若返回false,说明它把http请求扣留下来自己作了处理。此时,该postHandle()是执行不到的。
*
* @param request
* @param response
* @param handler
* @param modelAndView ModelAndView对象,可以通过其为页面传数据
* Can expose additional model objects to the view via the given ModelAndView.
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle() running...");
// 给页面返回数据
modelAndView.addObject("name","我是postHandle()呀!");
}
/**
* 一个http请求整个的处理流程结束后执行,即页面渲染完成后执行。
* 常用来进行资源的清理
*
* @param request
* @param response
* @param handler
* @param ex handler对象可能返回的异常(任何异常)
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompetion() running...");
}
}
preHandle()方法中做页面跳转时,涉及到一个jsp页面error.jsp。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>error</h1>
</body>
</html>
2、spring-mvc.xml中配置拦截器
<!--配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/><!--对哪些资源执行拦截操作-->
<bean class="com.yeats.interceptor.MyInterceptor"/><!--须放在mvc:mapping标签下面-->
</mvc:interceptor>
<!--<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.yeats.interceptor.MyInterceptor1"/>
</mvc:interceptor>-->
</mvc:interceptors>
3、部署项目,进行测试
浏览器中输入请求URL,进行测试
当请求URL中不带flag参数或flag参数值不为true,如下:
http://localhost:8080/spring_interceptor/target?flag=
此时,前端页面上,URL不变,页面上显示内容"error"。
(去分析流程)
后台,控制台打印内容
preHandle() running...
请求中没请我放行,不放!
当请求URL带上flag=true
http://localhost:8080/spring_interceptor/target?flag=true
前端页面,显示内容:
Hello World! ??postHandle()??
这是响应内容中文乱码了!
后台,控制台打印内容:
preHandle() running...
目标资源执行......
postHandle() running...
afterCompetion() running...