Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between @RequestBody and @RequestParam?

I have gone through the Spring documentation to know about @RequestBody, and they have given the following explanation:

The @RequestBody method parameter annotation indicates that a method parameter should be bound to the value of the HTTP request body. For example:

@RequestMapping(value = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
  writer.write(body);
}

You convert the request body to the method argument by using an HttpMessageConverter. HttpMessageConverter is responsible for converting from the HTTP request message to an object and converting from an object to the HTTP response body.

DispatcherServlet supports annotation based processing using the DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter. In Spring 3.0 the AnnotationMethodHandlerAdapter is extended to support the @RequestBody and has the following HttpMessageConverters registered by default:

...

but my confusion is the sentence they have written in the doc that is

The @RequestBody method parameter annotation indicates that a method parameter should be bound to the value of the HTTP request body.

What do they mean by that? Can anyone provide me an example?

The @RequestParam definition in spring doc is

Annotation which indicates that a method parameter should be bound to a web request parameter. Supported for annotated handler methods in Servlet and Portlet environments.

I have become confused between them. Please, help me with an example on how they are different from each other.

like image 912
Manoj Singh Avatar asked Jan 20 '15 07:01

Manoj Singh


People also ask

Can I use RequestBody and RequestParam together?

The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string. The handler for @RequestParam reads from both the body and the URL query String.

What is a RequestParam?

@RequestParam is a Spring annotation used to bind a web request parameter to a method parameter. It has the following optional elements: defaultValue - used as a fallback when the request parameter is not provided or has an empty value. name - name of the request parameter to bind to.

What is the difference between PathVariable and RequestParam?

1) The @RequestParam is used to extract query parameters while @PathVariable is used to extract data right from the URI.


3 Answers

@RequestParam annotated parameters get linked to specific Servlet request parameters. Parameter values are converted to the declared method argument type. This annotation indicates that a method parameter should be bound to a web request parameter.

For example Angular request for Spring RequestParam(s) would look like that:

$http.post('http://localhost:7777/scan/l/register?username="Johny"&password="123123"&auth=true')
      .success(function (data, status, headers, config) {
                        ...
                    })

Endpoint with RequestParam:

@RequestMapping(method = RequestMethod.POST, value = "/register")
public Map<String, String> register(Model uiModel,
                                    @RequestParam String username,
                                    @RequestParam String password,
                                    @RequestParam boolean auth,
                                    HttpServletRequest httpServletRequest) {...

@RequestBody annotated parameters get linked to the HTTP request body. Parameter values are converted to the declared method argument type using HttpMessageConverters. This annotation indicates a method parameter should be bound to the body of the web request.

For example Angular request for Spring RequestBody would look like that:

$scope.user = {
            username: "foo",
            auth: true,
            password: "bar"
        };    
$http.post('http://localhost:7777/scan/l/register', $scope.user).
                        success(function (data, status, headers, config) {
                            ...
                        })

Endpoint with RequestBody:

@RequestMapping(method = RequestMethod.POST, produces = "application/json", 
                value = "/register")
public Map<String, String> register(Model uiModel,
                                    @RequestBody User user,
                                    HttpServletRequest httpServletRequest) {... 

Hope this helps.

like image 54
Patrik Bego Avatar answered Oct 19 '22 06:10

Patrik Bego


map HTTP request header Content-Type, handle request body.

  • @RequestParamapplication/x-www-form-urlencoded,

  • @RequestBodyapplication/json,

  • @RequestPartmultipart/form-data,


  • RequestParam (Spring Framework 5.1.9.RELEASE API)

    map to query parameters, form data, and parts in multipart requests.

    RequestParam is likely to be used with name-value form fields

  • RequestBody (Spring Framework 5.1.9.RELEASE API)

    bound to the body of the web request. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request. (e.g. JSON, XML)

  • RequestPart (Spring Framework 5.1.9.RELEASE API)

    used to associate the part of a "multipart/form-data" request

    RequestPart is likely to be used with parts containing more complex content

  • HttpMessageConverter (Spring Framework 5.1.9.RELEASE API)

    a converter that can convert from and to HTTP requests and responses.

    All Known Implementing Classes: ..., AbstractJsonHttpMessageConverter, AbstractXmlHttpMessageConverter, ...

like image 31
山茶树和葡萄树 Avatar answered Oct 19 '22 06:10

山茶树和葡萄树


@RequestParam makes Spring to map request parameters from the GET/POST request to your method argument.

GET Request

http://testwebaddress.com/getInformation.do?city=Sydney&country=Australia

public String getCountryFactors(@RequestParam(value = "city") String city, 
                    @RequestParam(value = "country") String country){ }

POST Request

@RequestBody makes Spring to map entire request to a model class and from there you can retrieve or set values from its getter and setter methods. Check below.

http://testwebaddress.com/getInformation.do

You have JSON data as such coming from the front end and hits your controller class

{
   "city": "Sydney",
   "country": "Australia"
}

Java Code - backend (@RequestBody)

public String getCountryFactors(@RequestBody Country countryFacts)
    {
        countryFacts.getCity();
        countryFacts.getCountry();
    }


public class Country {

    private String city;
    private String country;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}
like image 13
Dulith De Costa Avatar answered Oct 19 '22 07:10

Dulith De Costa