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

org.springframework.web.servlet.mvc.method.annotation.MediaTypeResponseBodyAdvice Maven / Gradle / Ivy

package org.springframework.web.servlet.mvc.method.annotation;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;

@ControllerAdvice
public class MediaTypeResponseBodyAdvice implements ResponseBodyAdvice {
  private Map mediaType = new LinkedHashMap();

  @Override
  public boolean supports(MethodParameter returnType, Class> converterType) {
    return ResourceHttpMessageConverter.class.isAssignableFrom(converterType);
  }

  @Override
  public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class> selectedConverterType, ServerHttpRequest request,
      ServerHttpResponse response) {
    HttpHeaders headers = response.getHeaders();
    MediaType contentType = headers.getContentType();
    if (contentType != null) {
      for (Entry entry : this.mediaType.entrySet()) {
        if (entry.getKey().includes(contentType)) {
          headers.setContentType(entry.getValue());
          break;
        }
      }
    }
    return body;
  }

  public Map getMediaType() {
    return mediaType;
  }

  public void setMediaType(Map mediaType) {
    this.mediaType = mediaType;
  }
}