1、定义拦截器
实现 HandlerInterceptor 接口,重写里面重要的三个比较常用的方法
preHandle():在请求处理之前进行调用(Controller方法调用之前)
postHandle():请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
afterCompletion():在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
package com.example.demoinitializr.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 TestInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("执行了TestInterceptor的preHandle方法"); String url = request.getRequestURI(); String username = request.getParameter("username"); String password = request.getParameter("password"); String parameter = request.getQueryString(); String token = request.getHeader("token"); System.out.println(parameter); System.out.println(token); if(url=="/user/login"){ return true; } if(username == "admin" && password == "123456"){ return true; } else { } return HandlerInterceptor.super.preHandle(request, response, handler); } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("执行了TestInterceptor的postHandle方法"); HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("执行了TestInterceptor的afterCompletion方法"); HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } }
2、配置拦截器
继承 WebMvcConfigurer 类,并重写其中的方法 addInterceptors,在主类加上@Configuration在启动的时候在会被加载
package com.example.demoinitializr.config; import com.example.demoinitializr.Interceptor.TestInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(TestInterceptor()).addPathPatterns("/**"); //注册TestInterceptor拦截器 //InterceptorRegistration registration = registry.addInterceptor(new TestInterceptor()); //registration.addPathPatterns("/**"); //所有路径都被拦截 } @Bean public TestInterceptor TestInterceptor() { return new TestInterceptor(); } }
*
*
*