Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the HTTP Request body content in a Spring Boot Filter?

I want to get the raw content that is posted towards a RestController. I need it to do some processing on the raw input.

How can I get the raw body content without interfering with the Filter Chain?

like image 952
Marco Avatar asked Mar 19 '15 18:03

Marco


People also ask

How do you read a body request in Spring boot?

To retrieve the body of the POST request sent to the handler, we'll use the @RequestBody annotation, and assign its value to a String. This takes the body of the request and neatly packs it into our fullName String.

How do I request body data in Spring?

Simply put, the @RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the inbound HttpRequest body onto a Java object. Spring automatically deserializes the JSON into a Java type, assuming an appropriate one is specified.

Does Spring @RequestBody support the GET method?

HTTP's GET method does not include a request body as part of the spec. Spring MVC respects the HTTP specs. Specifically, servers are allowed to discard the body.


1 Answers

Here is a sample of controllerAdvice where you can access RequestBody and RequestHeader as you do in your controller. The Model attribute method is basically to add model attributes which are used across all pages or controller flow. It gets invoked before the controller methods kick in. It provides cleaner way of accessing the RESTful features rather than convoluted way.

@ControllerAdvice(annotations = RestController.class)
public class ControllerAdvisor {

    @ModelAttribute
    public void addAttributes(HttpServletRequest request, HttpServletResponse response,Model model, @RequestBody String requestString, @RequestHeader(value = "User-Agent") String userAgent) {
        // do whatever you want to do on the request body and header. 
        // with request object you can get the request method and request path etc.
        System.out.println("requestString" + requestString);
        System.out.println("userAgent" + userAgent);
        model.addAttribute("attr1", "value1");
        model.addAttribute("attr2", "value2");
    }   

}
like image 196
minion Avatar answered Sep 23 '22 19:09

minion