原理
springmv的interceptor的执行流程位置.png从图上可以看出springmvc的拦截器运行在tomcat的拦截器之后,所以实际开发中一般不用springmvc的拦截器。
使用步骤
第一步:编写一个普通类实现 HandlerInterceptor 接口
package com.gzy.web.filter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyFilter implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截器1.............执行前............");
//如果你返回的false 不放行 也就不会后面什么事
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("拦截器1............controller的方法执行完.....");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("拦截器1............视图渲染完毕 之后的.............");
}
}
第二步:配置拦截器
<mvc:interceptors>
<mvc:interceptor>
<!--这里两个*代表全部请求路径-->
<mvc:mapping path="/**"/>
<bean class="com.gzy.web.filter.MyFilter"/>
</mvc:interceptor>
</mvc:interceptors>
测试
package com.gzy.web.servlet;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserController {
@ResponseBody
@RequestMapping("/test")
public String test(){
System.out.println("执行方法了");
return "success";
}
}
网友评论