java - Json 到 Java 对象转换中带有 null 响应的 Spring MVC 请求

标签 java ajax spring spring-mvc

我在 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

@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 错误。

enter image description here

我的 pom.xml 带有 <jackson.version>2.6.3</jackson.version>

<!-- 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 对象。怎么解决?

最佳答案

好的,我已在我的机器上复制了您的问题。要将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 Controller 方法

@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 Controller 返回一个纯字符串。它会转到 ajax 调用中的错误处理程序。我已将 spring Controller 方法的响应类型更改为 ResponseModel,以便响应将采用 JSON 格式,并且在 ajax 调用中控件将转到成功处理程序。

关于java - Json 到 Java 对象转换中带有 null 响应的 Spring MVC 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36124094/

相关文章:

java - 如何使用一个 gson 反序列化器反序列化具有泛型的不同子类型

java - 关于应进行多少次 API 调用的最佳实践是什么?

java - 即使ECS AWS上有许多可用内核,Runtime.getRuntime()。availableProcessors()仍返回1

java - ClassNotFoundException : net. htmlparser.jericho.来源:新闻通讯

php - 为什么我无法从 AJAX 调用的 PHP 脚本访问 session 变量?

javascript - 在settimeout函数中使用ajax请求json输出

javascript - 使用 jQuery 附加到 HTML 后未加载 SCRIPT src

spring - Spring-发生错误时停止重定向

java - 如何在 build.gradle 中选择版本

java - Struts2 + Spring Security 2.06 : Valuestack is null when attempting to use @Secured on an Action method