25 Nisan 2022 Pazartesi

SpringMVC ResponseBodyAdvice Arayüzü - Response Nesnesi Değiştiren Interceptor

Giriş
Şu satırı dahil ederiz
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
Spring ile hazır gelen advice'lardan bir tanesi. Açıklaması şöyle
It helps us to modify the message i.e response object before it is written to the Response body.
supports metodu
İmzası şöyle
boolean supports(MethodParameter returnType,
                 Class<? extends HttpMessageConverter<?>> converterType)
Açıklaması şöyle
The MethodParameterargument helps us to check from which class and method the Request is coming and return the boolean value.  Based on it the BeforeBodyRead Method is Called.
beforeBodyWrite metodu
İmzası şöyle
T beforeBodyWrite(@Nullable T body,
                  MethodParameter returnType,
                  MediaType selectedContentType,
                  Class<? extends HttpMessageConverter<>> selectedConverterType,
                  ServerHttpRequest request,
                  ServerHttpResponse response)
Örnek
Şöyle yaparız
@RestControllerAdvice
public class DemoControllerAdvice implements 
  ResponseBodyAdvice<Map<String, String>> {

  @Override
  public boolean supports(
    MethodParameter returnType, 
    Class<? extends HttpMessageConverter<?>> converterType) {

    String className = returnType.getContainingClass().toString();
    String methodName = returnType.getMethod().toString();
    if (className.contains("DemoController_") && 
        methodName.contains("ResponseModification")) {
      return true;
    }
    return false;
  }

  @Override
  public Map<String, String> beforeBodyWrite(
    Map<String, String> body, 
    MethodParameter returnType,
    MediaType selectedContentType, 
    Class<? extends HttpMessageConverter<?>> selectedConverterType,
    ServerHttpRequest request, 
    ServerHttpResponse response) {

    body.put("body_data", "Age of the Person is 25 years");
    return body;
  }
}
Örnek
Şöyle yaparız. Burada @RestControllerAdvice yerine @ControllerAdvice kullanılıyor
@ControllerAdvice
public class ResponseBodyInterceptor implements ResponseBodyAdvice<Object> { @Override public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { return true; } @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { ... return body; } }

Hiç yorum yok:

Yorum Gönder