- 跟过滤器比较像的技术
- 发送请求时被拦截器拦截,在控制器的前后添加额外功能
2.1 与AOP不同,AOP在特定方法前后扩充。(对ServiceImpl)
2.2 拦截器,请求的拦截,针对点事控制器方法。(对Controller) - SpringMVC拦截器与Filter的区别
3.1 拦截器只能拦截Controller
3.2 Filter可以拦截任何请求
springmvc.xml配置
- 所有的进入控制器的请求都会被拦截
<!-- 拦截器 -->
<mvc:interceptors>
<bean class="com.lee.interceptor.DemoInterceptor"></bean>
</mvc:interceptors>
- 特定的控制器请求被拦截
<!-- 拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/demo"/>
<mvc:mapping path="/demo1"/>
<bean class="com.lee.interceptor.DemoInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
拦截器类
public class DemoInterceptor implements HandlerInterceptor{
//在进入控制器之前执行,如果返回值false,则阻止进入控制器
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
// TODO Auto-generated method stub
System.out.println("inteceptor-preHandle");
return true;
}
//控制器执行完成,进入jsp之前
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
System.out.println("inteceptor-postHandle");
}
//jsp执行完之后
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
System.out.println("inteceptor-afterHandle");
}
}
控制器
@RequestMapping("demo")
public String demo() {
System.out.println("controller-demo.exe");
return "index";
}
jsp
<% System.out.println("来自网页-index.jsp"); %>
当访问demo时,控制台输出结果
inteceptor-preHandle
controller-demo.exe
interceptor-postHandle
来自网页-index.jsp
interceptor-afterHandle
详解拦截器三个方法的参数
preHandle
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
// TODO Auto-generated method stub
System.out.println("arg2:" + arg2);
System.out.println("preHandle");
return true;
}
arg2 是请求的控制器方法(包括返回值,名称等):
arg2:public java.lang.String com.lee.controller.MainController.demo(org.springframework.ui.Model)
postHandle
主要功能1:日志记录
主要功能2:敏感词语过滤
SpringMVC过滤器可以修改model,而struts2不可以
例如:过滤“祖国”关键字
@RequestMapping("demo")
public String demo(Model model) {
model.addAttribute("model", "我爱祖国");
System.out.println("demo.exe");
return "index";
}
//控制器执行完成,进入jsp之前
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
System.out.println("往" + arg3.getView() + "跳转");
System.out.println("model:" + arg3.getModel().get("model"));
String word = arg3.getModel().get("model").toString();
String newWord = word.replace("祖国", "**");
System.out.println(word);
arg3.getModel().put("model", newWord);//这里struts2的后置拦截器不能修改,而SpringMVC可以
System.out.println("postHandle");
}
页面结果
我爱**
afterCompletion
主要功能:记录异常,可以把异常写到日志中
arg2同上,arg3表示发生的异常
//jsp执行完成之后
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("afterHandle" + arg3.getMessage());
}