将json传递给java时,格式不受支持

时间:2016-09-05 09:14:30

标签: javascript java json spring-mvc

我需要将一个对象从JavaScript传递给Java控制器。我这样做:

//java code
@RequestMapping(value="/mailsend" , method=RequestMethod.POST)
public int getBranchById(@RequestBody Modelmail details) throws IOException{
System.out.println(details); 

以下是javascript代码

 submitSuccess: function($form, event) {
        event.preventDefault(); // prevent default submit behaviour
        // get values from FORM
        var name = $("input#name").val();
        var email = $("input#email").val();
        var phone = $("input#phone").val();
        var message = $("textarea#message").val();
        var firstName = name; // For Success/Failure Message
        // Check for white space in name for Success/Fail message
        if (firstName.indexOf(' ') >= 0) {
            firstName = name.split(' ').slice(0, -1).join(' ');
        }

        var details={"name":name,"email":email,"phone":phone,"message":message}
        //var obj = JSON.parse(details);
        $.ajax({
            url: "./mailsend",
            type: "POST",
            data: details,
            cache: false,
            success: function() {

    }}

即使我添加了以下依赖项:

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>

现在我没有按照我的期望在Java中获取Java对象。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

要修复4xx不支持的媒体,您可以通过将以下行设置为app.properties来激活Spring日志:

log4j.category.org.springframework=ALL

激活Spring日志后,再次发出相关请求并检查日志输出以查看错误位置。

答案 1 :(得分:0)

更改ajax调用以包含内容类型标头,并将数据删除

 $.ajax({
    headers: { 
            'Accept': 'application/json',
            'Content-Type': 'application/json' 
        },
                url: './mailsend',
                type: 'POST',
                data: JSON.stringify(details),
                cache: false,
                dataType: 'json',
                success: function() {

        }
}