Springboot 利用Aspect 解決NULL 返還爲""

廢話就很少說了直接上代碼:web

/**
 * Controller層AOP,記錄請求和返回結果日誌掃描controller日誌
 *
 * @author reasahi
 * @version 1.0.0
 */
@Aspect
@Component
public class WebLogAspect {

    /**
     * 日誌
     */
    private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
    @Resource
    private MappingJackson2HttpMessageConverter converter;

    /**
     * 同步計算每次請求時間
     */
    ThreadLocal<Long> startTime = new ThreadLocal<>();
// 要掃描多個Controller  使用這種方式進行處理,若是你的包裏面分了多個Controller;若是隻有一個刪除一個execution留一個就好了
    @Pointcut("execution(public * com.exclmpl.controller.*.*(..)) || execution(public * com.exclmpl.webController.*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        // 接收到請求,記錄請求內容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 記錄下請求內容
        logger.info("請求鏈接 : " + request.getRequestURL().toString());
        logger.info("請求方式 : " + request.getMethod());
        logger.info("請求IP: " + IpHost.getIpAddr(request));
        logger.info("請求類: " + joinPoint.getSignature().getDeclaringTypeName() + "."
                + joinPoint.getSignature().getName());
        // logger.info("請求參數 : " + params);
        logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 處理完請求,返回內容
        logger.info("請求返還內容 : " + ret);
        logger.info("耗時 : " + (System.currentTimeMillis() - startTime.get()) + "毫秒");
    }


    @Around(value = "webLog()")
    @ResponseBody
    public void formatResult2JSON(ProceedingJoinPoint pjp) throws Throwable {

        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        HttpOutputMessage outputMessage = new ServletServerHttpResponse(response);
        //移除全部字段爲null的字段,其實就是使用了toString 以後移除 全部的null字段,可是這樣處理的後果就是全部返還字段內不能帶有null這樣小寫的字段,不然將會所有被移替換掉
        String result=pjp.proceed().toString().replaceAll("null", "\"\"");
        converter.write(JSONObject.fromObject(result), MediaType.APPLICATION_JSON_UTF8, outputMessage);
        shutdownResponse(response);
    }

    @AfterThrowing(pointcut = "webLog()", throwing = "error")
    public void handleForException(JoinPoint jp, Throwable error) throws Throwable {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        HttpOutputMessage outputMessage = new ServletServerHttpResponse(response);
//這裏可能會報錯,緣由是由於你在 try ctah模塊裏面用
e.printStackTrace();

若是你不須要正式環境下有這個,那麼最好註銷或者使用e.getMessage();app

converter.write(JSONObject.fromObject(error.getMessage()), MediaType.APPLICATION_JSON_UTF8, outputMessage);
        shutdownResponse(response);
    }

    private void shutdownResponse(HttpServletResponse response) throws IOException {
        response.getOutputStream().close();
    }
}
相關文章
相關標籤/搜索