【问题标题】:Spring is giving httpmessagenotreadableexception to ajax postSpring 正在为 ajax 帖子提供 httpmessagenotreadableexception
【发布时间】:2026-01-05 21:50:01
【问题描述】:

我是 Spring 新手。因此,任何建议将不胜感激。我正在尝试使用 ajax POST 将三个数组发送到 spring 控制器。当我单独发送数组时,它工作得很好。但是每当我尝试使用 POJO 一起发送三个数组时,它都会给我 HttpMessageNotReadableException。下面是我的代码。 我的 POJO:

package scheduler.dao;

import org.springframework.stereotype.Component;

@Component
public class TimeData2 {

    private String[] a1;
    private String[] a2;
    private String[] a3;

    public TimeData2(){

    }   

    public String[] getA1() {
        return a1;
    }

    public void setA1(String[] a1) {
        this.a1 = a1;
    }

    public String[] getA2() {
        return a2;
    }

    public void setA2(String[] a2) {
        this.a2 = a2;
    }

    public String[] getA3() {
        return a3;
    }

    public void setA3(String[] a3) {
        this.a3 = a3;
    }   

}

我的 ajax 调用是:

 myData = {
          "a1": JSON.stringify(first),
          "a2": JSON.stringify(second),
          "a3": JSON.stringify(third)                 
       } ;

      $.ajax({          
            type : "POST",          
            contentType : "application/json; charset=utf-8",
            url : "${pageContext.request.contextPath}/timeEntry?id=1",
            data :  myData, 
            dataType: "json",           
            success : function(response) {
                console.log(response);
            },
            error : function(e) {
                console.log(myData);
               //console.log(jQuery.isPlainObject(myData));
            }
        });

我的控制器是:

 @RequestMapping(value="/timeEntry", method=RequestMethod.POST, headers="Accept=application/json")
     @ResponseBody
     public String getTimeData(@RequestParam(value = "id") String id,
                               @RequestBody TimeData2 myData){
         System.out.println("Enter time");
         //System.out.println(myData.getA1());
         //test String
         String str = "{\"a\":1, \"b\":\"foo\"}";
         return str;
     }

调度程序-servlet.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:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">



    <context:component-scan base-package="scheduler.controllers"></context:component-scan>
    <mvc:annotation-driven></mvc:annotation-driven>
    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsps/"></property>
    <property name="suffix" value=".jsp"></property>
    </bean>


    <bean id="jacksonMessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </bean>
    <bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jacksonMessageConverter" />
        </list>
    </property>
    </bean>
    <mvc:resources location="/staticResources/"
        mapping="/resources/**">
    </mvc:resources>

</beans>

这是来自控制台的日志:

 org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleHttpMessageNotReadable
WARNING: Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unexpected character ('a' (code 97)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.PushbackInputStream@26ee3322; line: 1, column: 2]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('a' (code 97)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.PushbackInputStream@26ee3322; line: 1, column: 2]
Jan 19, 2016 4:36:58 PM org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver logException
WARNING: Handler execution resulted in exception: Could not read document: Unexpected character ('a' (code 97)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.PushbackInputStream@26ee3322; line: 1, column: 2]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('a' (code 97)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.PushbackInputStream@26ee3322; line: 1, column: 2]

有人可以帮忙吗?

【问题讨论】:

  • 试试 myData = [{ "a1": JSON.stringify(first)},{ "a2": JSON.stringify(second)},{ "a3": JSON.stringify(third) } ];
  • @gajendrakumar 我仍然遇到同样的错误。

标签: java jquery ajax spring spring-mvc


【解决方案1】:

我通过使 TimeData2 类实现 Serializable 接口解决了这个问题。我还通过以下方式修改了 ajax 请求:

myData =  {"a1": first, "a2": second, "a3": third};   

      $.ajax({          
            type : "POST",          
            contentType : "application/json; charset=utf-8",
            url : "${pageContext.request.contextPath}/timeEntry?id=1",
            data :  JSON.stringify(myData), 
            dataType: "json",          
            cache: false,    
            processData:false,
            success : function(response) {
                console.log(response);
            },
            error : function(e) {
                console.log(myData);
               //console.log(jQuery.isPlainObject(myData));
            }
        });

如果有人能解释为什么这个 ajax 请求有效而另一个无效,我将不胜感激。

【讨论】:

    最近更新 更多