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

wang.ramboll.extend.apiversion.advice.ApiVersionTransmitAdvice Maven / Gradle / Ivy

The newest version!
package wang.ramboll.extend.apiversion.advice;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
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.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import wang.ramboll.extend.apiversion.http.converter.AbstractJsonHttpMessageConverter;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求API版本号传递Advice
 * @author WangRuibo
 */
@ControllerAdvice
public class ApiVersionTransmitAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Class> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        ServletServerHttpRequest req=(ServletServerHttpRequest)serverHttpRequest;
        HttpServletRequest servletRequest = req.getServletRequest();
        String apiVersion = servletRequest.getHeader(AbstractJsonHttpMessageConverter.API_VERSION_HEADER_NAME);
        if(StringUtils.isNotBlank(apiVersion)) serverHttpResponse.getHeaders().set(AbstractJsonHttpMessageConverter.API_VERSION_HEADER_NAME,apiVersion);
        return o;
    }
}