天天看點

spring 攔截器 傳回資料_interceptor攔截器傳回json資料

使用Jackson進行傳回

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String token =  request.getHeader("token");//注意:token要放在請求頭中
            JWTUtils jwtUtils = new JWTUtils();
            jwtUtils.verifyToken(token);
            return true;
        }catch (SignatureVerificationException e){
            e.printStackTrace();
        }catch (TokenExpiredException e){
            e.printStackTrace();
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
        }catch (InvalidClaimException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }

        falseResult(response);
        return false;
    }

    public void falseResult(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        ResultBody resultBody = new ResultBody(false,null,"沒有token");
        ObjectMapper objectMapper = new ObjectMapper();
        response.getWriter().println(objectMapper.writeValueAsString(resultBody));
        return;
    }
}
           
spring 攔截器 傳回資料_interceptor攔截器傳回json資料

重點的地方

攔截器傳回的原理其實是“response直接傳回”,如下

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String token =  request.getHeader("token");//注意:token要放在請求頭中
            JWTUtils jwtUtils = new JWTUtils();
            jwtUtils.verifyToken(token);
            return true;
        }catch (SignatureVerificationException e){
            e.printStackTrace();
        }catch (TokenExpiredException e){
            e.printStackTrace();
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
        }catch (InvalidClaimException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }

        response.getWriter().println("interceptor ont allow access!");
        return false;
    }
           

被攔截後,響應體顯示資訊為:

spring 攔截器 傳回資料_interceptor攔截器傳回json資料

借用Jackson的原因

1:嘗試了使用@ResponseBody,發現其隻能在@Controller下使用

2:Jackson友善