基于SpringBoot
拦截器自定义拦截器
``` @Component public class LoginInterceptor implements HandlerInterceptor {
@Autowiredprivate LoginService loginService;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = request.getHeader("Authorization"); SysUser sysUser = loginService.checkToken(token); if (sysUser == null){ Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录"); response.setContentType("application/json;charset=utf-8"); response.getWriter().print(JSON.toJSonString(result)); return false; } //是登录状态,放行 return true;}
} ```
注册拦截器,实现implements WebMvcConfigurer,重写 preHandle()
``` @Configuration public class WebMVCConfig implements WebMvcConfigurer {
@Autowiredprivate LoginInterceptor loginInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor) .addPathPatterns("/test");}
} ```
过滤器编写filter
```java @WebFilter(filterName = "testFilter", urlPatterns = "/*") public class TestFilter implements Filter {
@Overridepublic void init(FilterConfig filterConfig){}// 主要的业务代码编写方法@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("我是过滤器的执行方法,客户端向Servlet发送的请求被我拦截到了"); filterChain.doFilter(servletRequest, servletResponse); System.out.println("我是过滤器的执行方法,Servlet向客户端发送的响应被我拦截到了");}// 在销毁Filter时自动调用@Overridepublic void destroy() { System.out.println("我是过滤器的被销毁时调用的方法!,活不下去了................" );}
} ```
主启动类加@ServletComponentScan 注解
```java @SpringBootApplication @ServletComponentScan public class SpringBootApplication {
public static void main(String[] args) { SpringApplication.run(SpringBootApplication.class, args);}
} ```
两者区别过滤器先执行,拦截器后执行