控制器无法从JQuery.ajax接收JSON

时间:2016-08-12 08:31:59

标签: jquery json spring

我已经检查了我的web.xml和spring-servlet.xml,我找不到任何错误。然后我检查了我的Controller和.ajax(),但仍然无法弄清楚是否有任何错误。我尝试JSON.stringify@RequestParam,在json handler中添加spring-servlet.xml。甚至将@RequestBody更改为@RequestBody(required = false)。他们都没有工作,仍然得到这个消息:

org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.handleHttpMessageNotReadable Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.Test.Controller.Login.login(com.Test.Model.User)

这是我的控制器:

@RequestMapping(value = "/main", method = RequestMethod.GET)
public String login (@RequestBody User user) {

    boolean result = userSer.login(user);

    if (result)
        return "success";
    else 
        return "fail";
}

我的阿贾克斯:

    function login() {
        //I can read the value in chrome's debug.
        var user = {
            "username": $("#username").val(),
            "password": $("#password").val()
        };

        $.ajax( {
            url: "/login/main",
            type: "GET",
            dataType: "json",
            //contentType:"application/json",
            data: JSON.stringify(user),
            success: function () {
                alert("success")
            },
            error:  function () {
                alert("fail")
            }
        } );
    }

我试图自己解决这个问题,但仍然无法弄清楚。

1 个答案:

答案 0 :(得分:0)

首先,如果要发送JSON Body,则需要使用POST。 GET只有URL中的变量,这对您不起作用。同样在Web开发中,一般的共识是您使用POST从用户提交数据。

我已成功使用此功能,测试是使用邮递员完成的:

POST: {
   "username":"00346845869585",
   "password":"test"
}


@Controller
@EnableAutoConfiguration
public class SampleController {

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

    public static class User {
        private String username;
        private String password;

        public String getUsername() {
            return username;
        }

        public String getPassword() {
            return password;
        }

        public User setUsername(String username) {
            this.username = username;
            return this;
        }

        public User setPassword(String password) {
            this.password = password;
            return this;
        }
    }


    @RequestMapping(value = "/main", method = RequestMethod.POST)
    @ResponseBody
    public String login(@RequestBody User user) {

        boolean result = user.getPassword().equals("test");

        if (result)
            return "success";
        else
            return "fail";
    }


    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
} 

和javascript:

<html>
<head>
    <title>Title</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>

<form>
    <input type="text" id="username"/>
    <input type="password" id="password"/>

    <input type="submit" id="submit"/>

</form>

<script>

    function login() {
        var user = {
            "username": $("#username").val(),
            "password": $("#password").val()
        };

        $.ajax({
            url: "/main",
            type: "POST",
            data: JSON.stringify(user),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function () {
                alert("success")
            },
            error: function () {
                alert("fail")
            }
        });
    }

    $("#submit").click(function () {
        login();
        return false
    });

</script>

</body>
</html>