1

I'm new to the Spring Boot filter

I'need to modify the response produced by the servlet(impl) to some pattern.

For example, GetProductImpl will give the response of

{
      "id": 72167,
      "merchantId": 3,
      "amount": 1,
      "state": "Unused"
}

So before it gets to send back to client i need to modify it to (it's kind of put the response under module)(for all response by all servlet)

{
"module":[{
      "id": 72167,
      "merchantId": 3,
      "amount": 1,
      "state": "Unused"
    }],
"success":true,
"errorCode":null,
"notSuccess":false
}

i looking for any method that can let me do this, because it's no point to do it inside the impl because if like that i need to do for all the impl (which is a lot and not viable).

If anyone have any other method that can achieve this also can because i don't know what approach to take to do this(java example also will do).

Thank you.

My current approach of using filter seems to hit the wall because i using addFilter, addFilterBefore or even addFilterAfter, all of them need to have the out filter class which i don know what it is and focus on web security stuff (UsernamePasswordAuthenticationFilter::class.java).

.addFilterBefore(JWTAuthenticationFilter(tokenAuthenticationService, objectMapper), UsernamePasswordAuthenticationFilter::class.java)
SicaYoumi
  • 176
  • 1
  • 3
  • 20
  • Possible duplicate of [Spring MVC: How to modify json response sent from controller](https://stackoverflow.com/questions/25020331/spring-mvc-how-to-modify-json-response-sent-from-controller) – dnsh Oct 03 '18 at 08:46
  • 1
    Use `ResponseBodyAdvice`. You can't use filters. You must get in before the response has been written to the output stream because after that it's too late to do it without wrapping the original http response object (ugly). – Andy Brown Oct 03 '18 at 09:38

1 Answers1

0

@Add Custom Filter class by Implementing filter interface. Override do filter method to modify your response.

Define a bean @Component annotation and @Order annotation to mark the filter execution execution order if you are using more than one filter.

@Component
@Order(1)
public class CustomFilter implements Filter {

  @Override
    public void doFilter(
      ServletRequest request, 
      ServletResponse response, 
      FilterChain chain) throws IOException, ServletException {

  HttpServletRequest req = (HttpServletRequest) request;
  HttpServletResponse res = (HttpServletResponse) response;
  chain.doFilter(request, response);
        // Modify your response  
        res.getContentType();
    }
}
amrendra
  • 19
  • 6