理解:相称于filter 过滤器,但是springmvc管理
跟AOP区分开,AOP在特定方法前后扩充(对Servicelmpl)
拦截器,要求的拦截,针对的是掌握器方法(对Controller)
3.SpringMVC拦截器和Filter的差异
拦截器只能拦截Controller
Filter可以拦截任何要求
demo:
拦截器类(全放行状态):
package com.wq.interceptor;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class DemoIntercepto implements HandlerInterceptor { //在进入掌握器之前实行 //如果返回值为false ,阻挡进入掌握器 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("a"); return true; } //掌握器实行完成,进入JSP之前实行 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("b"); } //JSP实行完成后实行 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("c"); }}
springmvc配置
<!--配置拦截器--> <mvc:interceptors> <!--<bean class="com.wq.interceptor.DemoIntercepto"> </bean>--> <mvc:interceptor> <mvc:mapping path="/demo"/> <mvc:mapping path="/demo1"/> <mvc:mapping path="/demo2"/> <bean class="com.wq.interceptor.DemoIntercepto"> </bean> </mvc:interceptor> </mvc:interceptors>
掌握器:
/掌握器-拦截器/ @RequestMapping("demo") public String demo(){ System.out.println("实行demo掌握器"); return "jsp/error"; }
JSP
<% System.out.println("未拦截进入JSP");%>hallo JSP
结果:
总结:
实现自定义拦截器的步骤
新建Handllerinterceptor
在springmvc配置拦截须要配置须要拦截的掌握器
拦截器栈
1.多个拦截器同时生效,组成了拦截器栈‘
2.顺序:前辈后出。
3.实行顺序和在springmvc配置有关
4.设置先配置拦截器A再配置拦截器B,实行顺序为
preHandle(A)-->preHandle(B)--->掌握器方法--->postHandle(B)--->postHandle(A)-->
JSP --->afterCompletion(B)--->afterConpletion(A)