jQuery ajax函数发送正确的值,但RestController接收null

这些代码是我的Spring Boot项目的RestController,


@RestController

@RequestMapping(value="/rest/user")

public class UserRestController {


    @Autowired

    private UserService userService;


    @PostMapping("login")

    public ResponseEntity<Boolean> authenticated(@RequestBody User user) {


        System.out.println(user.getUsername() +":"+ user.getPassword()); //This line returns NULL password value


        Boolean blogin = userService.authenticate(user.getUsername(), user.getPassword());

        if(!blogin)

            return new ResponseEntity<Boolean>(blogin, HttpStatus.NOT_ACCEPTABLE);


        return new ResponseEntity<Boolean>(blogin, HttpStatus.OK);

    }

}

下面的代码是JQuery ajax Java脚本代码。


function ajax_login_submit() {


    var user = {

            username: $("#username").val(),

            password: $("#password").val()

        }; 


    console.log(user);


    $.ajax({

        type: "POST",

        contentType: "application/json; charset=utf-8",

        url: "rest/user/login",

        data: JSON.stringify(user),

        dataType: 'json',

        success: function (data) {


            var resultJson = JSON.stringify(data);

            $('#helloUserDiv').html(resultJson);

            console.log("SUCCESS : ", data);

            alert(data);


        },

        error: function (e) {


            var resultJson = e.responseText;

            $('#helloUserDiv').html(resultJson);

            console.log("ERROR : ", e);

        }

    });

}

console.log(user); 的Java脚本返回正确的值。


{"username":"joseph","password":"password"}

但是在RestController代码中,密码值缺少“ NULL”。该行System.out.println(user.getUsername() + ":" + user.getPassword());返回奇怪的值,"joseph:null" 是否有可能JQuery ajax方法不将json值传输到REST服务器?如果我犯了一些错误,请告诉我如何将json值正确发送到REST服务器。


RISEBY
浏览 287回答 1
1回答

DIEA

试试这个:&nbsp;$.ajax({&nbsp; &nbsp; &nbsp; &nbsp; type: "POST",&nbsp; &nbsp; &nbsp; &nbsp; contentType: "application/json",&nbsp; &nbsp; &nbsp; &nbsp; url: "rest/user/login",&nbsp; &nbsp; &nbsp; &nbsp; data: JSON.stringify({"username": $("#username").val(), "password": $("#password").val()}),&nbsp; &nbsp; &nbsp; &nbsp; dataType: 'json',&nbsp; &nbsp; &nbsp; &nbsp; success: function (data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var resultJson = JSON.stringify(data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#helloUserDiv').html(resultJson);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("SUCCESS : ", data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(data);&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; error: function (e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var resultJson = e.responseText;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#helloUserDiv').html(resultJson);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("ERROR : ", e);&nbsp; &nbsp; &nbsp; &nbsp; }});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript