2

I am using Spring MVC and JSP to send JSON to Spring MVC Controller. Actually, my JSON works for 1 method but does not work for another and I don't understand why. The code is below:

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="[email protected]">
    <input type="text" name="to" value="[email protected]">
    <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>

The 1st form works correctly and is deserilized in Spring MVC. A sample of that code is:

@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;
}

For the 2nd form I am getting exceptions:

@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());
}
}

Below is the stack trace:

 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)

I have tried using the POST too, but still the same problem. I need to use JSP to send JSON data to the Spring MVC Controller.

I am not sure where the problem is.

beans.xml

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

    <mvc:annotation-driven/>

    <context:annotation-config/>

Any ideas?

EDIT

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 sent is in form2 which is #emailForm.

7
  • How does your Email class look like and what JSON is sent to that controller? Please edit your question and add these two details. Commented Sep 20, 2012 at 16:07
  • Please see changes above. JSON can be seen in emailForm form tag. Commented Sep 20, 2012 at 16:15
  • 1
    Just so you know, you don't need to stringify your object literal. jQuery will accept an object-literal just fine. Commented Sep 20, 2012 at 16:26
  • 2
    Are you sure that the data is reaching the controller? Take a look at your net tab. This exception can happen if you're sending an empty POST or GET. Commented Sep 20, 2012 at 16:28
  • yes, I am sure the data is reaching the controller for the application/save method. I tried with POST for the emailService and the data reaches the server. However, the problem is with GET only. Any ideas? Commented Sep 20, 2012 at 20:03

3 Answers 3

1

You should check if you have set "content-length" header.

Sign up to request clarification or add additional context in comments.

Comments

1

I ran into the same problem, but I used curl to verify the server side function.

The initial data section in my curl command is

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

After I changed the command to

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

then it worked.

Hope this gives some hints.

1 Comment

My cause was extra arguments after request body argument in the method.
0

I had this problem when I tried to use POST method with path parameter, but I forgot to put '@PathParam("id") Integer id', I just had 'Integer id ' in parameters.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.