Filter 为客户端抛出的异常

说明:

实现方法为请求转发

一. Filter

@Component
public class JWTFilter implements Filter {

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        /* 1. 是否校验token路径,包含为不做验证,不包含则验证,校验路径与shiro保持一致 */
        if (!request.getRequestURI().contains(TokenConstants.TOKEN_NOT_CHECK_URL)) {
            // 2. 获取token
            String accessToken = request.getHeader(TokenConstants.TOKEN_REQUEST_KEY);

            // 3. 校验token是否为空
            if (StringUtils.isEmpty(accessToken)) {
                // 转发到token为空的客户端异常
                request.getRequestDispatcher("/token/tokenNullError").forward(request, response);
            } else {
                // 3.1 校验token格式
                if (accessToken.contains(TokenConstants.TOKEN_REQUEST_HEAD)) {
                    accessToken = accessToken.replace(TokenConstants.TOKEN_REQUEST_HEAD, "");
                }
                // 3.2 校验token是否有效
                boolean verify = TokenUtils.verify(accessToken);
                if (!verify) {
                    // 转发到token为校验失败的客户端异常
                    request.getRequestDispatcher("/token/tokenCheckErr").forward(request, response);
                } else {
                    // 3.3 获取token中的用户信息
                    DecodedJWT decode = JWT.decode(accessToken);
                    // 账户等解析工作
                    String userName = decode.getClaim("userName").asString();
                    request.setAttribute("userName", userName);
                    filterChain.doFilter(request, response);
                }
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }
}

二. Filter 使用的请求转发类

@RestController
@RequestMapping("/token")
public class TokenCheckErrException {

    /**
     * token校验失败
     */
    @RequestMapping("tokenCheckErr")
    public void tokenCheckErr() {
        throw new BaseException(HttpStatusEnums.TOKEN_ERR);
    }

    /**
     * token为空
     */
    @RequestMapping("tokenNullError")
    public void tokenNullError() {
        throw new BaseException(HttpStatusEnums.CLI_ERR_TOKEN_NULL);
    }
}