繁体   English   中英

Spring MVC 3 JSON

[英]Spring MVC 3 JSON

我一直坚持这个问题很长一段时间。 我查看了互联网上的资源,但找不到我出错的地方。 我已经配置了Spring MVC来发送和接收JSON。 当我从Web浏览器为@ResponseBody调用RESTful服务时,返回的Object将作为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>    

历史service.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。

的index.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 Controller,以便可以将@RequestBody从JSON反序列化为Java。

我希望你能提供帮助。

您没有发布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/

在HTML表单上chage accept =“application / json”enctype =“application / json”

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

  1. 在你的html表单或js post函数上设置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:服务器拒绝此请求,因为请求实体所采用的方法所请求的资源不支持该格式()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM