Search code examples
javaspringspring-mvcspring-restcontroller

neither @RequestBody nor @RequestParam work


I want to make a PUT call in spring.

this is my controller code:

@RequestMapping(value = "/magic", method = RequestMethod.PUT)
    TodoDTO magic(@RequestBody String id){
        return service.magic(id);
    }

because i want to pass a id string in the call.

the problem is, i receive this

{
  "timestamp": 1486644310464,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "java.lang.NullPointerException",
  "message": "{\n\t\"id\":\"589c5e322abb5f28631ef2cc\"\n}",
  "path": "/api/todo/magic"
}

if i change the code like this:

@RequestMapping(value = "/magic", method = RequestMethod.PUT)
    TodoDTO magic(@RequestParam(value = "id") String id){
        return service.magic(id);
    }

i receive

{
  "timestamp": 1486644539977,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MissingServletRequestParameterException",
  "message": "Required String parameter 'id' is not present",
  "path": "/api/todo/magic"
}

i make the same call, a PUT at link http://localhost:8080/api/todo/magic with the body

{
    "id":"589c5e322abb5f28631ef2cc"
}

which is the id of one object in my db.

my question is, how can i achieve my goal? if i pass the param in the link, like api/todo/magic/589c5e322abb5f28631ef2cc, with @PathVariable, it works


Solution

  • Create your own custom class like below

    Class Request
    {
    private String id;
    //getter and setter
    }
    

    And change method to

    @RequestMapping(value = "/magic", method = RequestMethod.PUT)
        TodoDTO magic(@RequestBody Request request){
            return service.magic(request.getId());
        }
    

    You can take id in url also and use @Pathvariable in method signature

    @RequestMapping(value = "/magic/{id}", method = RequestMethod.PUT)
            TodoDTO magic(@PathVariable String id){
                return service.magic(request.getId());
            }