2

I am trying to send JSON to a Spring MVC Controller. On the Spring MVC side, everything is configured correctly.

Below is the code but doesn't seem to run:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>  
<script type="text/javascript">
  $('#myForm').on('submit', function(e) { 
    e.preventDefault(); 
    var frm = $("#myForm"); 
    var dat = frm.serialize(); 
    $.ajax({ 
    type: 'POST', 
    url: $('#myForm').attr('action'), 
    data: dat, 
    contentType: 'application/json' 
    success: function(hxr) { 
        alert("Success: " + xhr); 
    } 
}); 
});   
 </script>   
</head>
<body>
<h2>Application</h2>
<form id="myForm" action="/application/save" method="POST" accept="application/json" onclick="i()">
                <input type="text" name="name" value="myName">
    <input type="submit" value="Submit">
</form>

In Tomcat I get the following error:

org.springframework.web.servlet.mvc.support.DefaultHandlerE xceptionResolver handleNoSuchRequestHandlingMethod WARNING: No matching handler method found for servlet request: path '/application/save', method 'POST', parameters map['name' -> array['myName']]

Any ideas where I am going wrong? I am new to JSON. I am trying to to send JSON to Spring MVC controller.

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

    @RequestMapping(value = "save", method = RequestMethod.POST, headers = {"content-type=application/json"})
public @ResponseBody Response save(@RequestBody User user) throws Exception {
    Response userResponse = new Response();
    System.out.println("UserId :" + " " + user.getName());
    return userResponse;
}
}

@RequestMapping(value = "find", method = RequestMethod.GET)
public @ResponseBody Response find() {
    System.out.println("Run");
    Response userResponse = new Response();
    userResponse.setVersionNumber("1.0");
    return userResponse;
}

When invoking /application/run/save I get a JSON response. However the @RequestBody does not work.


I still have had no luck. Have read some many similiar problems. The requirement is that the server will only accept application/json types. I am using a Spring MVC Controller. As mentioned earlier, the code sends a response back as JSON through @ResponseBody. I want to get information through the @RequestBody in my Spring MVC Controller. I am using JSP to send JSON to Spring MVC Controller. My code and Spring MVC can be seen below:

I am new to JSON and Javascript.

JSP - index.jsp

<%@page language="java" contentType="text/html"%>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>  
<script type="text/javascript">
    $('#myForm').on('submit', function(e) { 
    var frm = $("#myForm");
   var dat = JSON.stringify(frm.serializeArray()); 

$.ajax({ 
     type: 'POST', 
     url: $('#myForm').attr('action'), 
     data: dat,
     contentType: 'application/json',
     dataType: 'json',
     error: function() {
        alert('failure');
     }
     success: function(hxr) { 
         alert("Success: " + xhr); 
     }
  }); 
); 
}; 
</script> 
</head>
<body>
<h2>Application</h2>
<form id="myForm" action="/application/save" method="POST" accept="application/json" onclick="i()">
    <input type="text" name="userId" value="User">
    <input type="submit" value="Submit">
</form>
</body>
</html>

When running this I am not getting any output. In the Chrome I get 404 Not found error and in Tomcat I get the following error:

org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver     handleNoSuchRequestHandlingMethod
WARNING: No matching handler method found for servlet request: path '/application/sa
 ve', method 'POST', parameters map['userId' -> array<String>['User']]

Is something wrong here in the JSP part?

web.xml

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
     version="2.5">

     <display-name>WebApp</display-name>

     <context-param>
        <!-- Specifies the list of Spring Configuration files in comma separated format.-->
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/service.xml</param-value>
     </context-param>

     <listener>
        <!-- Loads your Configuration Files-->
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
     </listener>

     <servlet>
        <servlet-name>application</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
     </servlet>

     <servlet-mapping>
        <servlet-name>application</servlet-name>
        <url-pattern>/</url-pattern>
     </servlet-mapping>

     <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
     </welcome-file-list>    
</web-app>

service.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

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

    <mvc:annotation-driven/>

    <context:annotation-config/>

    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>

    <bean id="jacksonMessageChanger" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes" value="application/json"/>
    </bean>

    <!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jacksonMessageChanger"/>
            </list>
        </property>
    </bean>-->

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <util:list id="beanList">
                <ref bean="jacksonMessageChanger"/>
            </util:list>
        </property>
    </bean>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="mediaTypes">
            <map>
                <entry key="json" value="application/json"/>
            </map>
        </property>
    </bean>-->  
</beans>

Controller

package com.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestBody;
import com.webchannel.domain.User;
import com.webchannel.domain.UserResponse;

@Controller
@RequestMapping("/application/*")
public class SaveController {

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

@RequestMapping(value = "delete", method = RequestMethod.GET)
public @ResponseBody UserResponse delete() {
    System.out.println("Delete");
    UserResponse userResponse = new UserResponse();
    userResponse.setSuccess(true);
    userResponse.setVersionNumber("1.0");
    return userResponse;
}
}

When invoking /application/delete I get JSON returned. So I know my JacksonProcessor is configured correctly. The problem is in @RequestBody.

Where am I going wrong? Please help me.

6
  • within your code you do not seem to be doing anything with created dat. Isn't it? Commented Sep 17, 2012 at 17:57
  • so should in my <form> tag should I have a parameter called <input type="name">? Commented Sep 17, 2012 at 17:58
  • Ok, I have modified. Please see above and let me know where I am going wrong. It still does not work. Commented Sep 17, 2012 at 18:08
  • Can you try replacing $(function i() { with function i() { and });</script> with }</script>? Commented Sep 17, 2012 at 18:12
  • 2
    Why exactly do you want to send JSON? What's the concrete functional requirement? Does that Spring MVC controller only accept a request body in JSON format instead of the standard application/x-www-form-urlencoded like as standard forms and standard ajax requests send? Your concrete problem suggests that the Spring MVC controller doesn't accept a request body in JSON format at all. Just use var dat = frm.serialize(); the usual way then. Commented Sep 17, 2012 at 18:33

4 Answers 4

1

This question is a bit hard to follow since there seems to be a few different problems.

But looking just at this problem:

In Tomcat I get the following error:

org.springframework.web.servlet.mvc.support.DefaultHandlerE xceptionResolver handleNoSuchRequestHandlingMethod WARNING: No matching handler method found for servlet request: path '/application/run', method 'POST', parameters map['name' -> array['myName']]

In the HTML you posted, you have a <form> that is set to POST to /application/run.

However, in your @Controller class, you do not have any method bound to this URL.

Because you've annotated the class with @RequestMapping("/run/*") and the method is annotated with @RequestMapping("save"), the save() method is actually bound to the URL /run/save - which is neither the URL you are sending data to with $.ajax() nor the URL the form is pointing at.

I would suggest turning up logging on the org.springframework.web loggers to DEBUG - when your app starts up Spring will log every URL that each method is mapped to.

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

2 Comments

sorry, it should be run/save but still same problem.
I don't think you need the * in the @RequestMapping(/application/*). Did you take my suggestion to turn up logging to examine exactly which methods are bound to exactly which URLs?
1

I think you may need make couple of changes

  1. Since your controller has @RequestMapping("/run/*"), you may need to change this to @RequestMapping("/run/") and in the jsp form action you may need to change <form id="myForm" action="/application/run/save" method="POST" accept="application/json" onclick="i()">, since you have defined @RequestMapping(value = "save", method = RequestMethod.POST, headers = {"content-type=application/json"}) for the 'save` method in the controller.

  2. You may need to define the @RequestParam in the save method in controller like public @ResponseBody Response save(@RequestParam(required=true, value="name") String name, @RequestBody User user) throws Exception {...}

Since it clearly says that there is no handler attached to the request you are submitting.

1 Comment

Ok, please see edited code. I have also tried RequestMapping("/run/") but still same error. I actually do not want to fetch from RequestParam. I want the JSON to be deserialized through the RequestBody
0

Try the following

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>  
<script type="text/javascript">
$('#myForm').on('submit', function(e) {
    e.preventDefault();
    var frm = $("#myForm");
    var dat = frm.serialize();
    $.ajax({
        type: 'POST',
        url: $('#myForm').attr('action'),
        data: dat,
        contentType: 'application/json'
        success: function(hxr) {
            alert("Success: " + hxr);
        }
    });
});    
</script>   
</head>
<body>
<h2>Application</h2>
<form id="myForm" action="/application/run" method="POST">
    <input type="text" name="name" value="myName">
    <input type="submit" value="Submit">
</form>​

The dataType:'json' is specifying what the format you are expecting from the server,

And it would be better to assist if you post your handler code.

3 Comments

Please note the hxr typo (which is after all also a misnamed variable by the way, it does not represent the XMLHttpRequest object at all).
yep, thanks @BalusC, it will be the data returned from the server.
still it does not work. Please see above changes. BalusC is the requirement is that the server only accepts and sends JSON. I can send JSON but can't receive. I would like to receive in @RequestBody. Please help.
0

There is no method in the controller mapped to your /application/run. I'm not sure which one you want to call, but to the url you have to add find orsave. Or create a method mapped to /application/run. Cheers!

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.