将JSON发送到Spring MVC控制器

时间:2022-08-03 18:03:07

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

我尝试将JSON发送给Spring MVC控制器。在Spring MVC端,一切都被正确配置。

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:

在Tomcat中,我得到以下错误:

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']]

org.springframework.web.servlet.mvc.support。DefaultHandlerE xceptionResolver handleNoSuchRequestHandlingMethod警告:没有为servlet请求找到匹配的处理程序方法:path '/application/save',方法'POST',参数映射['name' ->数组['myName']]

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

你知道我哪里出错了吗?我对JSON很陌生。我正在尝试向Spring MVC控制器发送JSON。

@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.

当调用/应用程序/运行/保存时,我得到一个JSON响应。但是@RequestBody不能工作。


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:

我仍然没有运气。读过许多相似的问题。要求是服务器只接受应用程序/json类型。我使用的是Spring MVC控制器。如前所述,代码通过@ResponseBody以JSON形式返回响应。我想通过Spring MVC控制器中的@RequestBody获取信息。我正在使用JSP将JSON发送给Spring MVC控制器。我的代码和Spring MVC如下:

I am new to JSON and Javascript.

我是JSON和Javascript的新手。

JSP - index.jsp

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:

运行时,我不会得到任何输出。在Chrome中我得到404未发现错误,在Tomcat中我得到以下错误:

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?

JSP部分有问题吗?

web.xml

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

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.

调用/应用程序/删除时,返回JSON。我知道我的杰克逊处理器配置正确。问题在@RequestBody中。

Where am I going wrong? Please help me.

我哪里出错了?请帮助我。

4 个解决方案

#1


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:

在Tomcat中,我得到以下错误:

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']]

org.springframework.web.servlet.mvc.support。DefaultHandlerE xceptionResolver handleNoSuchRequestHandlingMethod警告:没有为servlet请求找到匹配的处理程序方法:path '/application/run',方法'POST',参数映射['name' ->数组['myName']]

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

在您发布的HTML中,有一个

,设置为POST到/application/run。

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

但是,在@Controller类中,没有任何方法绑定到这个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.

因为您已经用@RequestMapping(“/run/*”)注释了类,并且这个方法也用@RequestMapping(“save”)注释,所以save()方法实际上绑定到URL /run/save——它既不是您用$.ajax()发送数据到的URL,也不是表单指向的URL。

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.

我建议在org.springframework上登录。web日志记录器要调试——当应用程序启动时,Spring将记录每个方法映射到的每个URL。

#2


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.

    由于您的控制器有@RequestMapping("/run/*"),您可能需要将其更改为@RequestMapping("/run/"),在jsp表单操作中,您可能需要更改

  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 {...}

    您可能需要在控制器的save方法中定义@RequestParam,如public @ResponseBody Response save(@RequestParam(required=true, value="name") String name, @RequestBody用户)抛出异常{…}

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

因为它清楚地表明,您提交的请求没有附加处理程序。

#3


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,

dataType:“json”指定了您期望从服务器得到的格式,

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

如果您发布您的处理程序代码,最好提供帮助。

#4


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!

控制器中没有映射到您/应用程序/运行的方法。我不确定你要调用哪个,但是你需要在url中添加find或save。或者创建一个映射到/application/run的方法。干杯!

#1


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:

在Tomcat中,我得到以下错误:

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']]

org.springframework.web.servlet.mvc.support。DefaultHandlerE xceptionResolver handleNoSuchRequestHandlingMethod警告:没有为servlet请求找到匹配的处理程序方法:path '/application/run',方法'POST',参数映射['name' ->数组['myName']]

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

在您发布的HTML中,有一个

,设置为POST到/application/run。

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

但是,在@Controller类中,没有任何方法绑定到这个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.

因为您已经用@RequestMapping(“/run/*”)注释了类,并且这个方法也用@RequestMapping(“save”)注释,所以save()方法实际上绑定到URL /run/save——它既不是您用$.ajax()发送数据到的URL,也不是表单指向的URL。

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.

我建议在org.springframework上登录。web日志记录器要调试——当应用程序启动时,Spring将记录每个方法映射到的每个URL。

#2


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.

    由于您的控制器有@RequestMapping("/run/*"),您可能需要将其更改为@RequestMapping("/run/"),在jsp表单操作中,您可能需要更改

  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 {...}

    您可能需要在控制器的save方法中定义@RequestParam,如public @ResponseBody Response save(@RequestParam(required=true, value="name") String name, @RequestBody用户)抛出异常{…}

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

因为它清楚地表明,您提交的请求没有附加处理程序。

#3


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,

dataType:“json”指定了您期望从服务器得到的格式,

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

如果您发布您的处理程序代码,最好提供帮助。

#4


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!

控制器中没有映射到您/应用程序/运行的方法。我不确定你要调用哪个,但是你需要在url中添加find或save。或者创建一个映射到/application/run的方法。干杯!