拦截器HandlerInterceptor

时间:2024-7-22    作者:老大夫    分类:


  • 编写HandlerInterceptor

创建一个拦截器类实现HandlerInterceptor接口

主要有三大方法

preHandle(..) — callback before the actual handler is run that returns a boolean. If the method returns true, execution continues; if it returns false, the rest of the execution chain is bypassed and the handler is not called.

postHandle(..) — callback after the handler is run.

afterCompletion(..) — callback after the complete request has finished.

web-admin模块中创建com.atguigu.lease.web.admin.custom.interceptor.AuthenticationInterceptor类,内容如下,有关HanderInterceptor的相关内容,可参考官方文档

package com.atguigu.lease.web.admin.custom.Interceptor;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

//token校验拦截器
public class AuthenticationInterceptor implements HandlerInterceptor {
    //ture 放行  false到此为止
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //请求头中拿token
        String token = request.getHeader("access-token");
        if(token==null){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        //顺利解析之后就true放行,如果出错在方法里设置了抛出异常
        JwtUtil.parseToken(token);
        return true;
    }
}
**注意**:

我们约定,前端登录后,后续请求都将JWT,放置于HTTP请求的Header中,其Header的key为`access-token`。
  • 注册HandlerInterceptor

    web-admin模块com.atguigu.lease.web.admin.custom.config.WebMvcConfiguration中增加如下内容3

在配置类中使用addInterceptors(InterceptorRegistry registry)方法

    @Autowired
    private AuthenticationInterceptor authenticationInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this.authenticationInterceptor).addPathPatterns("/admin/**").excludePathPatterns("/admin/login/**");
    }


扫描二维码,在手机上阅读

推荐阅读: