Syed Mhamudul Hasan
Syed Mhamudul Hasan

Reputation: 1349

Spring MVC request with null response in Json to Java object conversion

My ajax request in spring mvc

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

Model

@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;
}

and 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 is

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

and dispatcher servlets is

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

after sending ajax request in firebug it shows null result by post is done successfully by lands in ajax error .

enter image description here

I have pom.xml with <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>

But can not use it map in Spring MVC 4 json to java object. How to solve it??

Upvotes: 1

Views: 2339

Answers (1)

Raju Rudru
Raju Rudru

Reputation: 1132

Ok I have replicated your issue in my machine. To send the data from ajax call to spring mvc in the form of an object, you need to make few changes to the ajax call and you need to change the @ModelAttribute to @RequestBody. See below the updated code

    $(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);
        }
    }); 

});

The Spring Controller method

@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;
}

Since in the ajax call you are expecting a JSON response and you are returning a plain String from spring controller. It goes to error handler in ajax call. I have changed the response type of spring controller method to ResponseModel so that the response will be in JSON format and in the ajax call the control goes to success handler.

Upvotes: 1

Related Questions