一. Interceptor
首先编写一个拦截器,编辑器需要添加@Component注解,并实现HandlerInterceptor 接口,然后重写preHandle、postHandle、afterCompletion,其中:
-
preHandle:在请求目标请求之前执行,返回值如果为true,则代表放行,如果为false,则代表为拦截
-
postHandle:请求目标请求之后执行,返回视图之前
-
afterCompletion:请求完成时执行
package io.zhangjia.springmvc.interceptors; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class Interceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("Interceptor.preHandle"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("Interceptor.postHandle"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("Interceptor.afterCompletion"); } }
接下来在spring-mvc.xml中配置拦截器:
<mvc:interceptors> <ref bean="interceptor" /> </mvc:interceptors>
ref的bean属性的值即为我们的拦截器类的类名小写(因为添加了@Component注解,则其id默认为类名小写)
最后编写Controller和jsp:
@Controller public class Test { @RequestMapping("/test") public String testInterceptor(String name,Model model) { System.out.println("Test.testInterceptor"); model.addAttribute("result",name); return "test"; } } <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %> <!DOCTYPE html> <html> <head> <title>Title</title> </head> <body> <h1>你好</h1> <h1>${requestScope.result}</h1> </body> </html>
当我们访问http://localhost:8888/sm/test?name=张甲时,控制台输出:
Interceptor.preHandle Test.testInterceptor Interceptor.postHandle Interceptor.afterCompletion
如果我们将preHandle的返回值修改为false,即拦截, 则控制台输出:
Interceptor.preHandle
二. 总结
1. 配置拦截器
-
添加@Component注解,并实现HandlerInterceptor 接口
2. 配置spring-mvc.xm
<mvc:interceptors> <ref bean="interceptor" /> </mvc:interceptors>
请登录之后再进行评论