Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify request body before reaching controller in spring boot

I have a spring boot application. I change the request body of every post request. Is it possible to modify the request body before the request reaches the controller. Please include an example.

like image 273
BlueCloud Avatar asked Jun 19 '18 15:06

BlueCloud


People also ask

Can we pass request body in get method in spring boot?

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. The request URI should contain everything needed to formulate the response.

What does @RequestBody do 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.

Can we make request body optional?

It is typical to specify an input body parameter when performing an HTTP PUT, POST, or PATCH request to a resource; otherwise error-9106 is raised. You can set WSOptional on the ATTRIBUTES() clause of an input body parameter if a body is not always required.

How do I request a body from Spring?

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. We've then returned this name back, with a greeting message.


1 Answers

Another alternative would be adding an attribute to the HttpServletRequest object. And after that you can read that attribute in the Controller class with @RequestAttribute annotation.

In the Interceptor

@Component
    public class SimpleInterceptor extends HandlerInterceptorAdapter {

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws ServletException, IOException {
            String parameter = request.getParameter("parameter");
            if (parameter == "somevalue") {
                request.setAttribute("customAttribute", "value");
            }

            return true;
        }

    }

In the Controller

@RestController
@RequestMapping("")
public class SampleController {


    @RequestMapping(value = "/sample",method = RequestMethod.POST)
    public String work(@RequestBody SampleRequest sampleRequest, @RequestAttribute("customAttribute") String customAttribute) {
        System.out.println(customAttribute);
        return "This works";
    }
}

This has advantage of not modifying the request body.

like image 123
Abhinay Dronavally Avatar answered Sep 17 '22 17:09

Abhinay Dronavally