Springboot AOP 拦截 直接返回结果数据

  • Post author:
  • Post category:其他


示例代码:

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = attributes.getResponse();
        //校验
        Boolean statusCheck = XXXXXStatusCheck(response);
        if (!statusCheck) {
            Result<Boolean> result = new Result<>();
            result.setData(false);
            result.setSuccess(false);
            result.setResultCode(ResultCode.XXXXX_NOT_CONFIG);
            returnData(result,response);
        }
        return joinPoint.proceed();
    }

    /**
     * 返回数据
     *
     * @param result
     * @param response
     * @throws IOException
     */
    public void returnData(Result<Boolean> result, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        //这里传提示语可以改成自己项目的返回数据封装的类
        response.getWriter().println(objectMapper.writeValueAsString(result));
        return;
    }

代码简析: