欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

拦截器与过滤器

时间:2023-08-08

基于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);}

} ```

两者区别

过滤器先执行,拦截器后执行

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。