拦截器:实现接口handlerinterceptor
@Component
public class MyInterceptor implements HandlerInterceptor {
@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {
//url中包含Login就不拦截if (request.getRequestURI().contains("get")) {
System.out.println("不拦截");return true;}//即url没Login也没登陆,就重新跳转到login.html登陆页面System.out.println("拦截");request.getRequestDispatcher("/index.html").forward(request, response);return false;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response,Object handler, Exception ex) throws Exception {
}
}
因为拦截器是spring的所以要在spring配置
与扩展视图一样,都是在webmvcconfigurarer配置注册的
反正就是以前mvc是xml配置,现在是类配置
@Configuration
public class MyConfiguration implements WebMvcConfigurer {
@Overridepublic void addInterceptors(InterceptorRegistry registry) {
//将我们自定义的拦截器加入配置InterceptorRegistration interceptor = registry.addInterceptor(new MyInterceptor());//设置拦截的urlinterceptor.addPathPatterns("/user/**");}
}