拦截器是AOP具体的应用
只能使用SpringMVC自己的组件有效
之拦截访问控制器方法的请求,
如果访问的是jsp、html、css、img、js这一类的静态资源,则不会拦截
演示:
编写一个拦截器的测试,控制器的方法
package cn.dai.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @author ArkD42 * @file SpringMVC * @create 2020 - 05 - 07 - 19:39 */ @RestController public class TestController { @GetMapping("/visit") public String test(){ System.out.println("The TestController.test() has bean browsed !!!"); return "browsed access!!!"; } }
编写拦截器实现类,实现拦截方法
package cn.dai.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author ArkD42 * @file SpringMVC * @create 2020 - 05 - 07 - 19:35 */ public class SpringMvcInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("- - - - 拦截前 - - - -"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("- - - - 处理后 - - - -"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("- - - - 清理 - - - -"); } }
注册到SpringMVC中
<!-- 拦截器 --> <mvc:interceptors> <mvc:interceptor> <!-- /** 表示所有的请求,/*只表示当前一个路由的情况下实现 --> <mvc:mapping path="/**"/> <!-- 具体是哪个类来完成的 --> <bean class="cn.dai.interceptor.SpringMvcInterceptor" /> </mvc:interceptor> </mvc:interceptors>
访问结果