0

我被这个问题困扰了很长时间。我查看了 Internet 上的资源,但找不到我哪里出错了。我已将 Spring MVC 配置为发送和接收 JSON。当我从 Web 浏览器为 @ResponseBody 调用 RESTful 服务时,返回的对象以 JSON 形式返回。但是,当尝试调用 @RequestBody 时,我无法做到。

下面是代码:

web.xml

<?xml version="1.0" encoding="UTF-8"?> 
     <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/history-service.xml</param-value>
     </context-param>

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

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

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

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

历史服务.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans>     
    <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.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>-->  

控制器类

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

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

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

调用 /webapp/history/delete 时,我可以收到 JSON。

索引.jsp

    <%@page language="java" contentType="text/html"%>
 <html>
 <head>
 </head>
 <body>
 <h2>WebApp</h2>
<form action="/webapp/history/save" method="POST" accept="application/json">
    <input name="userId" value="Hello">
    <input name="location" value="location">
    <input name="emailAddress" value="hello@hello.com">
    <input name="commitMessage" value="I">
    <input type="submit" value="Submit">
</form>
</body>
</html>

但是,在调用 /save 时出现以下错误:

org.springframework.web.servlet.mvc.support.DefaultHandlerE
xceptionResolver handleNoSuchRequestHandlingMethod
WARNING: No matching handler method found for servlet request: path '/history/sa
ve', method 'POST', parameters map['location' -> array<String>['location'], 'use
rId' -> array<String>['Hello'], 'emailAddress' -> array<String>['hello@hello.com'], 'commitMessage' -> array<String>['I']]

我不确定我哪里出错了。我要做的就是通过 JSP 将 JSON 发送到 Spring MVC 控制器,这样@RequestBody 就可以从 JSON 反序列化为 Java。

我希望你能帮忙。

4

2 回答 2

1

您没有发布 JSON 数据。您必须使用 javascript 或其他东西将表单输入转换为 JSON。Jquery 对此非常有用。或更改您的控制器以接受

headers = "content-type=application/x-www-form-urlencoded"

仅供参考,您可以在提交表单时使用 FF 或 Chrome 的开发人员工具查看标题。特别是网络面板(适用于 Chrome)。 https://developers.google.com/chrome-developer-tools/docs/network

我相信它是 Firefox 中的 Web 控制台。https://developer.mozilla.org/en-US/docs/Tools/Web_Console?redirectlocale=en-US&redirectslug=Using_the_Web_Console

使用 Jquery 发布表单输入:

<script type="text/javascript">
   $(function() {
     var frm = $("#MyForm); // In the JSP/HTML give your form an id (<form id="MyForm" ...)
     var dat = JSON.stringify(frm.serializeArray());

     $.ajax({
          type: 'POST',
          url: url,
          data: dat,
          success: function(hxr) {
              alert("Success: " + xhr);
          }

          dataType: 'json'
       });
     );
 });
</script>

更多信息在这里: http ://api.jquery.com/jQuery.post/

于 2012-09-17T15:21:07.093 回答
1

在 HTML 表单上将accept ="application/json"更改为enctype="application/json"

Spring 无法解析您发布的数据,因为您没有设置当前标题。使用 @RequestBody 时,默认接受 enctype 是 application/json。尝试其中之一:

  1. 在您的 html 表单或 js 发布功能上设置 post headers="content-type=application/json"。
  2. 将您的控制器设置为接受 headers="content-type=application/x-www-form-urlencoded"。

编辑

enctype 必须与标头相同。好的,代码现在看起来像其中之一:

// the one
@RequestMapping(value = "save", method = RequestMethod.POST)
public @ResponseBody UserResponse save(@RequestBody User user) throws Exception {
    UserResponse userResponse = new UserResponse();
    return userResponse;
}


</form>
<form action="/webapp/history/save" method="POST" enctype="application/x-www-form-urlencoded">
    <input name="userId" value="user">
    <input name="location" value="location">
    <input name="emailAddress" value="hello@hello.com">
    <input name="commitMessage" value="I">
    <input type="submit" value="Submit">
</form>


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


</form>
<form action="/webapp/history/save" method="POST" enctype="application/json">
    <input name="userId" value="user">
    <input name="location" value="location">
    <input name="emailAddress" value="hello@hello.com">
    <input name="commitMessage" value="I">
    <input type="submit" value="Submit">
</form>

尝试上述之一。

我收到以下错误:

HTTP 错误 415:服务器拒绝此请求,因为请求实体的格式不受所请求方法 () 的请求资源支持。

于 2012-09-17T15:42:23.083 回答