Spring中的MVC请求,在Json中使用null响应进行Java对象转换

时间:2016-03-21 05:59:37

标签: java ajax spring spring-mvc

我在春天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请求后,显示null结果通过post在ajax错误中成功完成。

enter image description here

我有<jackson.version>2.6.3</jackson.version>

的pom.xml
<!-- 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对象。如何解决?

1 个答案:

答案 0 :(得分: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 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控制器返回一个普通的String。它转到ajax调用中的错误处理程序。我已将spring控制器方法的响应类型更改为ResponseModel,以便响应将采用JSON格式,并且在ajax调用中控件转到成功处理程序。