2

我正在使用 Spring MVC 和 JSP 将 JSON 发送到 Spring MVC 控制器。实际上,我的 JSON 适用于一种方法,但不适用于另一种方法,我不明白为什么。代码如下:

JSP - index.jsp

<%@page language="java" contentType="text/html"%>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>  
<script type="text/javascript">
$(function() {  
$('#myForm').submit(function() { 
    var form = $( this ), 
        url = form.attr('action'), 
        userId = form.find('input[name="userId"]').val(),
        dat = JSON.stringify({ "userId" : userId }); 

    $.ajax({ 
        url : url, 
        type : "POST", 
        traditional : true, 
        contentType : "application/json", 
        dataType : "json", 
        data : dat, 
        success : function (response) { 
            alert('success ' + response); 
        }, 
        error : function (response) { 
            alert('error ' + response); 
        }, 
    }); 

    return false; 
   }); 
 }); 
</script>

<script type="text/javascript">
$(function() {  
$('#emailForm').submit(function() { 
    var form = $( this ), 
        url = form.attr('action'), 
        from = form.find('input[name="from"]').val(),
        to = form.find('input[name="to"]').val(),
        body = form.find('input[name="body"]').val(),
        subject = form.find('input[name="subject"]').val(),
        fileName = form.find('input[name="fileName"]').val(),
        location = form.find('input[name="location"]').val(),
        dat = JSON.stringify({ "from" : from,"to" : to,"body" : body,"subject" : subject,"fileName" : fileName,"location" : location }); 

    $.ajax({ 
        url : url, 
        type : "GET", 
        traditional : true, 
        contentType : "application/json", 
        dataType : "json", 
        data : dat, 
        success : function (response) { 
            alert('success ' + response); 
        }, 
        error : function (response) { 
            alert('error ' + response); 
        }, 
    }); 

    return false; 
   }); 
}); 
</script> 
</head>
<body>
<h2>Application</h2>
<form id="myForm" action="/application/history/save" method="POST">
    <input type="text" name="userId" value="JUnit">
    <input type="submit" value="Submit">
</form>
<form id="emailForm" action="/application/emailService/sendEmail" method="GET">
    <input type="text" name="from" value="name@localhost.com">
    <input type="text" name="to" value="user@localhost.com">
    <input type="text" name="body" value="JUnit E-mail">
    <input type="text" name="subject" value="Email">
    <input type="text" name="fileName" value="attachment">
    <input type="text" name="location" value="location">
    <input type="submit" value="Send Email">
</form>
</body>
</html>

第一种形式可以正常工作并在 Spring MVC 中反序列化。该代码的示例是:

@Controller
@RequestMapping("/history/*")
public class HistoryController {

@RequestMapping(value = "save", method = RequestMethod.POST, headers = {"content-type=application/json"})
public @ResponseBody UserResponse save(@RequestBody User user) throws Exception {
    UserResponse userResponse = new UserResponse();
    return userResponse;
}

对于第二种形式,我得到了例外:

@Controller
@RequestMapping("/emailService/*")
public class EmailController {

@RequestMapping(value = "sendEmail", method = RequestMethod.GET, headers = {"content-type=application/json"})
public void sendEmail(@RequestBody Email email) {
    System.out.println("Email Body:" + " " + email.getBody());
    System.out.println("Email To: " + " " + email.getTo());
}
}

下面是堆栈跟踪:

 java.io.EOFException: No content to map to Object due to end of input
org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2022)
org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1974)
org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1331)
org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:135)
org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:154)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.readWithMessageConverters(HandlerMethodInvoker.java:633)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestBody(HandlerMethodInvoker.java:597)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:346)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

我也尝试过使用 POST,但仍然是同样的问题。我需要使用 JSP 将 JSON 数据发送到 Spring MVC 控制器。

我不确定问题出在哪里。

豆类.xml

<context:component-scan base-package="com.web"/>

    <mvc:annotation-driven/>

    <context:annotation-config/>

有任何想法吗?

编辑

public class Email implements Serializable {

private String from;
private String to;
private String body;
private String subject;
private String fileName;
private String location;

public Email() {

}

// Getters and setters
}

发送的 JSON 格式为 form2,即 #emailForm。

4

3 回答 3

1

我遇到了同样的问题,但我使用 curl 来验证服务器端功能。

我的 curl 命令中的初始数据部分是

-d "{'id':'123456', 'name':'QWERT'}"

在我将命令更改为

-d '{"id":"123456", "name":"QWERT"}'

然后它起作用了。

希望这能给一些提示。

于 2013-05-23T17:14:11.560 回答
1

您应该检查是否设置了“内容长度”标头。

于 2013-11-10T21:31:33.263 回答
0

当我尝试使用带有路径参数的 POST 方法时遇到了这个问题,但是我忘了放'@PathParam("id") Integer id',我只是有'Integer id 'in 参数。

于 2020-02-04T15:40:11.763 回答