【问题标题】:Spring MVC request with null response in Json to Java object conversion在 Json 中具有空响应的 Spring MVC 请求到 Java 对象的转换
【发布时间】:2016-03-21 05:59:37
【问题描述】:

我在 spring mvc 中的 ajax 请求

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/json2/20150503/json2.js"></script>
    <script>
    $(document).ready(function(){
        var producer = "producer";
        var model = "model";
        var price = "1";
        var ResponseModel = {};
        ResponseModel.producer=producer;
        ResponseModel.model=model;
        ResponseModel.price=price;
        $.ajax({
            url : '/ajaxtest',
            data: JSON.stringify({"editUserRequest":ResponseModel}),
            type: "POST",
            async: true,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },

            success : function(data) {
                alert("success");
                console.log(data);
            },
            error:function(data) {
                alert("errorxxx");
                console.log(data);
            }
        });
    });
</script> 

型号

@JsonSerialize
public class ResponseModel implements Serializable {
    public ResponseModel(){}
    public String getProducer() {
        return producer;
    }

    public void setProducer(String producer) {
        this.producer = producer;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    private String producer;
    private String model;
    private String price;
}

和spring MVC控制器

@Controller
@RequestMapping("/")
public class HelloController {
    @RequestMapping(method = RequestMethod.GET)
    public String printWelcome(ModelMap model) {
        model.addAttribute("message", "Hello world!");
        return "hello";
    }
    //@ModelAttribute(value="editUserRequest")
    @RequestMapping(value = "/ajaxtest", method = RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody
    String getTime(@ModelAttribute(value="editUserRequest")  ResponseModel editUserRequest,HttpServletRequest request,HttpServletResponse response) {


        String result = editUserRequest.getModel()+editUserRequest.getPrice()+editUserRequest.getProducer();
        //String result = "editUserRequest";
        //System.out.println("Debug Message from CrunchifySpringAjaxJQuery Controller.." + new Date().toString());
        return result;
    }
}

web.xml 是

<web-app version="2.4"
    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_4.xsd">

    <display-name>Spring MVC Application</display-name>

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

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

而调度器 servlet 是

<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/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.springapp.mvc"/>
    <context:annotation-config />
    <mvc:annotation-driven />
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>


</beans>

在 firebug 中发送 ajax 请求后,它通过 post 显示 null 结果是由 ajax 错误中的土地成功完成的。

我有 pom.xml 和 &lt;jackson.version&gt;2.6.3&lt;/jackson.version&gt;

<!-- Need this for json to/from object -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>

但不能使用它在 Spring MVC 4 json 中映射到 java 对象。怎么解决??

【问题讨论】:

  • sysout result 变量,看看返回的变量是什么......!!此外,您只返回一个字符串响应,而不是 JSON 结构响应。如果您需要发送 JSON 响应,请将其返回为 Map..
  • 你能把请求发送到控制器方法吗?
  • 是的,我可以成功发送 ajax,但在 intellij 中调试显示对象 editUserRequest 全部为空值

标签: java ajax spring spring-mvc


【解决方案1】:

好的,我已经在我的机器上复制了您的问题。要将ajax调用中的数据以对象的形式发送到spring mvc,您需要对ajax调用进行一些更改,并且需要将@ModelAttribute更改为@RequestBody。请参阅下面的更新代码

    $(document).ready(function(){
    var producer = "producer";
    var model = "model";
    var price = "1";
    var editUserRequest = new Object();
    editUserRequest.producer=producer;
    editUserRequest.model=model;
    editUserRequest.price=price;
    $.ajax({
        url : 'ajaxtest',
        data: JSON.stringify(editUserRequest),
        type: "POST",
        contentType : 'application/json; charset=utf-8',
        dataType : 'json',

        success : function(data) {
            alert("success");
            console.log(data);
        },
        error:function(data) {
            alert("errorxxx");
            console.log(data);
        }
    }); 

});

Spring 控制器方法

@RequestMapping(value = "ajaxtest", method = RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
ResponseModel getTime(@RequestBody  ResponseModel editUserRequest) {


    String result = editUserRequest.getModel()+editUserRequest.getPrice()+editUserRequest.getProducer();
    //String result = "editUserRequest";
    //System.out.println("Debug Message from CrunchifySpringAjaxJQuery Controller.." + new Date().toString());
    return editUserRequest;
}

因为在 ajax 调用中,您期待 JSON 响应,并且您从 spring 控制器返回一个纯字符串。它转到 ajax 调用中的错误处理程序。我已将 spring 控制器方法的响应类型更改为 ResponseModel,以便响应为 JSON 格式,并且在 ajax 调用中,控件转到成功处理程序。

【讨论】:

    猜你喜欢
    • 2011-06-08
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多