Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accept JSON POST parameters as @RequestParam in Spring Servlet?

I'm trying to create a POST servlet that should be called with JSON request. The following should work, but does not. What might be missing?

@RestController
public class MyServlet {
    @PostMapping("/")
    public String test(@RequestParam String name, @RequestParam String[] params) {
        return "name was: " + name;
    }
}

JSON POST:

{
   "name": "test",
   "params": [
      "first", "snd"
   ]
}

Result: name is always null. Why?

"Response could not be created: org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'name' is not present"

like image 781
membersound Avatar asked Jan 03 '23 20:01

membersound


1 Answers

In general I don't pass a request param in a POST method. Instead, I am using a DTO to pass it in the body like:

@RequestMapping(value = "/items", method = RequestMethod.POST)
    public void addItem(@RequestBody ItemDTO itemDTO) 

Then, you need to create the ItemDTO as a POJO with the necessary fields.

like image 103
stzoannos Avatar answered Jan 07 '23 10:01

stzoannos