拦截器与过滤器

拦截器与过滤器,第1张

拦截器与过滤器

基于SpringBoot

拦截器

自定义拦截器

``` @Component public class LoginInterceptor implements HandlerInterceptor {

@Autowired
private LoginService loginService;

@Override
public 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 {

@Autowired
private LoginInterceptor loginInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(loginInterceptor)
            .addPathPatterns("/test");
}

} ```

过滤器

编写filter

```java @WebFilter(filterName = "testFilter", urlPatterns = "/*") public class TestFilter implements Filter {

@Override
public void init(FilterConfig filterConfig){
}

// 主要的业务代码编写方法
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    System.out.println("我是过滤器的执行方法,客户端向Servlet发送的请求被我拦截到了");

    filterChain.doFilter(servletRequest, servletResponse);

    System.out.println("我是过滤器的执行方法,Servlet向客户端发送的响应被我拦截到了");
}

// 在销毁Filter时自动调用
@Override
public void destroy() {
    System.out.println("我是过滤器的被销毁时调用的方法!,活不下去了................" );
}

} ```

主启动类加@ServletComponentScan 注解

```java @SpringBootApplication @ServletComponentScan public class SpringBootApplication {

public static void main(String[] args) {
    SpringApplication.run(SpringBootApplication.class, args);
}

} ```

两者区别

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5722120.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存