Java 向Spring MVC控制器发送JSON

Java 向Spring MVC控制器发送JSON,java,jquery,json,jsp,spring-mvc,Java,Jquery,Json,Jsp,Spring Mvc,我正在尝试将JSON发送到SpringMVC控制器。在SpringMVC端,所有配置都是正确的 下面是代码,但似乎没有运行: <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">

我正在尝试将JSON发送到SpringMVC控制器。在SpringMVC端,所有配置都是正确的

下面是代码,但似乎没有运行:

<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>
调用/application/run/save时,我得到一个JSON响应。但是@RequestBody不起作用


我还是没有运气。我读过很多类似的问题。要求是服务器只接受application/json类型。我使用的是Spring MVC控制器。如前所述,代码通过@ResponseBody以JSON的形式发送响应。我想通过SpringMVC控制器中的@RequestBody获取信息。我正在使用JSP向SpringMVC控制器发送JSON。我的代码和Spring MVC如下所示:

我不熟悉JSON和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>
当调用/application/delete时,返回了JSON。所以我知道我的JacksonProcessor配置正确。问题出在@RequestBody中

我哪里做错了?请帮帮我。

试试下面的方法

<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>​

$('#myForm')。关于('submit',函数(e){
e、 预防默认值();
var frm=$(“我的形式”);
var dat=frm.serialize();
$.ajax({
键入:“POST”,
url:$('#myForm').attr('action'),
数据:dat,
contentType:'应用程序/json'
成功:功能(hxr){
警报(“成功:+hxr”);
}
});
});    
应用
​
数据类型:'json'
指定您希望从服务器获得的格式


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

这个问题有点难以理解,因为似乎存在一些不同的问题

但只要看看这个问题:

在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']]
org.springframework.web.servlet.mvc.support.DefaultHandlerE ExceptionResolver handleNoSuchRequestHandlingMethod警告:找不到与servlet请求匹配的处理程序方法:路径'/application/run',方法'POST',参数映射['name'->数组['myName']]

在您发布的HTML中,有一个
设置为
POST
to
/application/run

但是,在
@Controller
类中,没有任何方法绑定到此URL

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


我建议打开
org.springframework.web
loggers以
DEBUG
-当您的应用程序启动时,Spring将记录每个方法映射到的每个URL。

我认为您可能需要做一些更改

  • 由于您的控制器具有
    @RequestMapping(“/run/*”)
    ,您可能需要将其更改为
    @RequestMapping(“/run/”)
    ,并且在jsp表单操作中,您可能需要更改
    ,因为您已经定义了
    @RequestMapping(value=“save”,method=RequestMethod.POST,headers={“content type=application/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;
    }
    
  • 您可能需要在控制器的save方法中定义@RequestParam,如
    public@ResponseBody Response save(@RequestParam(required=true,value=“name”)字符串名,@RequestBody User User)抛出异常{…}


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

    控制器中没有映射到您的
    /application/run
    的方法。我不确定您要调用哪一个,但必须在
    url
    中添加
    find
    save
    。或者创建映射到
    /application/run
    的方法。干杯

    在您的代码中,您似乎没有使用created
    dat
    执行任何操作。不是吗?我的标签中应该有一个名为的参数吗?好的,我已经修改了。请看上面,让我知道我错在哪里。它仍然不起作用。能否尝试将
    $(函数i(){
    替换为
    函数i(){
    });
    替换为
    }
    ?为什么要发送JSON?具体的功能要求是什么?Spring MVC控制器是否只接受JSON格式的请求体,而不是像标准表单和标准ajax请求那样接受标准
    应用程序/x-www-form-urlencoded
    ?您的具体问题表明SpringMVC控制器根本不接受JSON格式的请求体。只需使用var dat=frm.serialize()通常的方式。请注意
    hxr
    输入错误(顺便说一句,这毕竟也是一个命名错误的变量,它根本不代表
    XMLHttpRequest
    对象)。是的,谢谢@BalusC,它将是从服务器返回的数据。它仍然不起作用。请参阅以上更改。BalusC的要求是服务器只接受和发送JSON。我可以发送JSON,但无法接收。我想在@RequestBody中接收。请帮助。好的,请查看已编辑的代码。我也尝试过RequestMapping(“/run/”),但仍然出现相同的错误。实际上,我不想从RequestParam获取。我希望JSON通过RequestBody进行反序列化抱歉,它应该运行/保存,但仍然存在相同的问题。我认为您不需要
    @RequestMapping(/application/*)
    中的
    *
    。你是否接受我的建议,打开日志来检查哪些方法绑定到哪些URL?
    <?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>
    
    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;
    }
    }
    
    <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>​