0

I am trying to understand Spring REST and REST services. I have created a controller for POST request like this:

@RequestMapping(method = RequestMethod.POST, path = "newItem")
public ResponseEntity<Item> createItem(
        @RequestParam(value = "name") String name,
        @RequestParam(value = "date") String date,
        @RequestParam(value = "location") String location) {

    Item item = new Item(name, date, location);

        //save into database
}

My question is: What if my Item has let's say 15 attributes. Do I need to create @RequestParam for each of it? Or is that another way of doing it? Could you give me some point where to start?

2 Answers 2

1

What if my Item has let's say 15 attributes. Do I need to create @RequestParam for each of it? Or is that another way of doing it? Could you give me some point where to start?

POST request data should be part of body, they should n't be consumed using @RequestParam, so change your controller method as shown below:

@RequestMapping(method = RequestMethod.POST, path = "newItem")
public ResponseEntity<Item> createItem(@RequestBody Item item) {

    Item item = new Item(name, date, location);
        //save into database
    }

So, when the request is received by the Spring DispatcherServlet, the item object will be populated (called deserialization) with the request data.

You can look here for more details @RequestBody

Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly it. The one thing for others. Make your model class with one public constructor with no arguments. This will allow the framework to create object by any number of attributes present in the @Requestbody.
0

Usuarl approach in case of POST it to send data in request body.

@RequestBody String postReqeust

Also, spring provide several converters of request body to object. For example, you can define class Itm that describes json object and define methods

public ResponseEntity<Item> createItem( @RequestBody NewItemReqeust request)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.