使用@RequestBody从ajax接收数据并将其绑定到'User',但是失败

时间:2019-03-02 15:39:11

标签: ajax spring-boot spring-mvc data-binding

我使用AJAX通过@RequestBody批注将数据提交到Spring Boot后端以接受它。但是,这样做时,它显示出followinginng错误,这使我感到困惑:

  

不存在必需的字符串参数“用户名”

控制台输出

Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'username' is not present]

AJAX代码

$("#submitBTN").click(
    function(){
        $.ajax({
            type:"post",
            async:false,
            url:"/user/doSignIn?verification="+$("input[name='verificationCode']").val(),
            contentType: "application/json;charset=utf-8",//必须加
            data: JSON.stringify({
                'username': $("input[name='username']").val(),
                'password':$("input[name='password']").val(),
                'email': $("input[name='email']").val()
            }),
            success:function(r){
                if(r.code==window.ResponseStatus.OK){
                    $(window).attr('location',+'/index');
                }else{
                    console.log(r.msg);
                }
            }
        });
    }
);

实体用户

@Entity
public class User {
    // 自增id
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    // 用户名
    @Pattern(regexp = "^.{4,14}$",groups = UserSignUp.class)
    @Column(length = 14)
    private String username;
    // 密码
    @Pattern(regexp = "^[0-9a-zA-Z!@#$%^&*.]{6,25}$")
    @Column(length = 25)
    private String password;
    // 邮箱
    @Email
    private String email;
    // 电话号码
    @Pattern(regexp = "^\\d{11}$",groups = UserSignUp.class)
    @Column(length = 11)
    private String phoneNumber;
    // 所属用户组
    private byte userGroup;

RequestHandler代码

@PostMapping(value = "/doSignUp")
public FOResponse doSignUp(@RequestBody User user,
                           BindingResult result,
                           @RequestParam String verificationCode,
                           HttpSession session){...}

0 个答案:

没有答案