All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.paas.aspect.ResponseBodyAspect Maven / Gradle / Ivy

package com.paas.aspect;

import com.alibaba.fastjson.JSON;
import com.paas.service.ModifyRspBodyService;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @ClassName ResponseBodyAspect
 * @Date 2020/12/8 15:10
 * @Auther wangyongyong
 * @Version 1.0
 * @Description 返回请求体拦截
 */
@ControllerAdvice
public class ResponseBodyAspect implements ResponseBodyAdvice
{

    public void setModifyRspBodyService(ModifyRspBodyService modifyRspBodyService)
    {
        this.modifyRspBodyService = modifyRspBodyService;
    }

    private ModifyRspBodyService modifyRspBodyService;

    @Override
    public boolean supports(MethodParameter methodParameter, Class> aClass)
    {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse)
    {
        Object rsp = body;
        if (body == null || (serverHttpResponse instanceof ServletServerHttpResponse && ((ServletServerHttpResponse) serverHttpResponse).getServletResponse().getStatus() != HttpStatus.OK.value()))
        {
            int status = ((ServletServerHttpResponse) serverHttpResponse).getServletResponse().getStatus();
            if (body instanceof byte[])
            {
                rsp = modifyRspBodyService.handleRspBody(status, (byte[]) body);
            }
            else
            {
                rsp = modifyRspBodyService.handleRspBody(status, JSON.toJSONBytes(body));
            }
            serverHttpResponse.setStatusCode(HttpStatus.OK);
        }
        return rsp;
    }
}