简体   繁体   English

模型属性在Spring Boot MVC中变为空?

[英]model attributes are coming null in Spring Boot MVC?

I am using Spring 4 with mapped methods as follows 我正在使用Spring 4和以下映射方法

@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 并且所有UserPasswordResetRequestDTO属性都为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? 我一直在搜索,我发现一些相关的问题,区别在于它们是PUT方法(然后,由于Spring 3.1可以使用HttpPutFormContentFilter完成),但这是一篇文章,我找不到任何问题...我是什么做错了吗?


EDIT 编辑

I've tried changing @RequestBody with @ModelAttribute and it just mapped "userId" attribute (coming from url), leaving null the rest of attributes. 我尝试用@ModelAttribute更改@RequestBody,它只是映射了“ userId”属性(来自url),其余属性都为null。 Just the same as @RequestBody did with the difference of userId 与@RequestBody一样,只是userId有所不同

I am really really disconcerted 我真的很不高兴

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"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM