jscherman
jscherman

Reputation: 6179

model attributes are coming null in Spring Boot MVC?

I am using Spring 4 with mapped methods as follows

@RestController
@RequestMapping("/v3/users")
public class UserController { 

...

    @RequestMapping(value = "/{userId}/reset_password", method =     RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Void> resetPassword(
        @PathVariable("userId") Long userId, @RequestBody     UserPasswordResetRequestDTO data) {
        // Logic here 
        return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
    }
}

public class UserPasswordResetRequestDTO {

    private Long userId;
    private String oldPassword;
    private String newPassword;

    // Getters and setters

}

then, i do this request:

POST /v3/users/6/reset_password HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 8afe6ef8-a4cd-fc9d-a6cc-b92766a56bd6

{"oldPassword":"actualPassword", "newPassword":"newOne"}

And all UserPasswordResetRequestDTO attributes are coming null

I've been searching and i find some related problems with the difference that those were PUT methods (then since Spring 3.1 can be done with HttpPutFormContentFilter), but this is a post and i couldn't find any problem... what i am doing wrong?


EDIT

I've tried changing @RequestBody with @ModelAttribute and it just mapped "userId" attribute (coming from url), leaving null the rest of attributes. Just the same as @RequestBody did with the difference of userId

I am really really disconcerted

Upvotes: 1

Views: 2091

Answers (1)

jscherman
jscherman

Reputation: 6179

Finally, i discovered what was going on. I had this jackson config

@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    builder.propertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    builder.serializationInclusion(Include.NON_NULL);
    return builder;
}

which was causing the conversion from camel case to underscores on serialization and deserealization. So there was nothing wrong with code, just an invalid request, which in this case had to be this one:

POST /v3/users/6/reset_password HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 8afe6ef8-a4cd-fc9d-a6cc-b92766a56bd6

{"old_password":"actualPassword", "new_password":"newOne"}

Upvotes: 1

Related Questions