0

I want to send a json with values from the form tag to a Spring MVC controller.

The forms on submit method executes the following code

var jsonStr = JSON.stringify($("#form1").serializeArray());  
    $.ajax({
        url :  "/DMS/webcontroller/startupload",
        type : "POST",
       // traditional : true,
        contentType : "application/json; charset=utf-8",
        processData:false,
        //dataType : "json",
        data : jsonStr,
        success : function (response) {
            alert('success ' + response);
        },
        error : function (response) {
            alert('error ' + response);
        },
    });

I have added the following to my spring configuration xml

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jsonMessageConverter"/>
            </list>
        </property>
    </bean>

    <!-- Configure bean to convert JSON to POJO and vice versa -->
    <bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
     <property name="prefixJson" value="false"/>
        <property name="supportedMediaTypes" value="application/json"/>
    </bean>   

My controller signature is as follows

@RequestMapping(value="/startupload", method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
        public @ResponseBody ReturnData startUpload(@RequestBody UploadStartVO startVO)
        {...

When I run this on tomcat 7 with firefox 31, I am getting the 415 response.If I check the request using tools I see that Content-Type has been added to the Request body. Also the Request data is query formatted like this:

supplierId=1111&unregSupplier=unregSupplier&customerName=customerName&externalEntity=externalentity&application=scms&logicalGroup=demand&user=u1&password=u1&appUser=appu1&documentType=email&documentDescription=documentDescription&contactPerson=contactPerson&contactNumber=contactNumber&documentGroupName=demand&documentPurpose=documentpurpose&uploaderIP=uploaderIp&uploaderName=scmsname&uploaderCompletePath=somepath%2Fsomepath&uploadDateTime=20%2F12%2F2014

and not like this:

[{"name":"supplierId","value":"1111"},{"name":"unregSupplier","value":"unregSupplier"},{"name":"customerName","value":"customerName"},{"name":"externalEntity","value":"externalentity"},{"name":"application","value":"scms"},{"name":"logicalGroup","value":"demand"},{"name":"user","value":"u1"},{"name":"password","value":"u1"},{"name":"appUser","value":"appu1"},{"name":"documentType","value":"email"},{"name":"documentDescription","value":"documentDescription"},{"name":"contactPerson","value":"contactPerson"},{"name":"contactNumber","value":"contactNumber"},{"name":"documentGroupName","value":"demand"},{"name":"documentPurpose","value":"documentpurpose"},{"name":"uploaderIP","value":"uploaderIp"},{"name":"uploaderName","value":"scmsname"},{"name":"uploaderCompletePath","value":"somepath/somepath"},{"name":"uploadDateTime","value":"20/12/2014"}]

Request Body shows :

Content-Type: application/x-www-form-urlencoded
Content-Length: 457

Request header shows

Host: localhost:8082
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:8082/DMS/
Cookie: JSESSIONID=C64F21EEECFC5BDF515C3DE22F51626A
Connection: keep-alive

If I edit this request and put the json(this is what is seen in the jsonStr var during debugging) in the request Body change the Content-Type in Body and add the Content-Type in the header I am getting a 400 Bad Request!!

Please help me with this!

EDIT:: So main problem is that $.ajax() is not creating proper request. Data is not json and contenttype is not application/json.

EDIT:: forgot to paste the pom.xml dependancy

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

EDIT::: I tried the code with removing the Converted objects UploadStartVO and ReturnData and replacing with String object. The call was successful, the ajax() method still returned the exception but the form tag had the action attribute which goes properly to my controller method. Can anyone point out why the ajax call doesnt work?? Firefox 31

3
  • pls try with my answer, if it helps you Commented Sep 5, 2014 at 6:59
  • which version of spring you are using? Commented Sep 8, 2014 at 5:08
  • 4.0.2.RELEASE.jackson 2.3.3 Commented Sep 8, 2014 at 5:10

4 Answers 4

1

It seems I was sending data in the wrong format to the controller. I tried changing everything one by one. The controller header headers = {"Content-type=application/json"} was unrequired.

The consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE in the controller was not needed.

I downgraded from 2.3.3 to 1.9.1 the jackson version. That had no effect.

The data I sent initially was

 JSON.stringify({'key': 'John', 'application': 'SCMS'})

After changing it to

JSON.stringify({key: 'John', application: 'SCMS'})

The Request is not converted to the POJO properly.

Hope this saves someone some time!

Sign up to request clarification or add additional context in comments.

Comments

0

In Spring MVC , to output JSON data,you have to add Jackson library in the project classpath.

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.9</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.9</version>
</dependency>

2 Comments

have added the dependency but hadnt pasted the pom.. version is 2.3.3
@kavita try removing consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE, @RequestBody is sufficient
0

Try using below

Just try some below points if still not works.

1.) Try commenting/uncommenting combination of contentType and dataType.

2.) Also try using 'data : JSON.stringify(jsonStr),'.

3.) Also try to alert your data.

var jsonStr = $("#form1").serialize();  
    $.ajax({
        url :  "/DMS/webcontroller/startupload",
        type : "POST",
        contentType : "application/json",
        data : JSON.stringify(jsonStr),
        success : function (response) {
            alert('success ' + response);
        },
        error : function (response) {
            alert('error ' + response);
        },
    });

2 Comments

done all three! alert is what i see in the debugging. stringify in the value for data is still giving the error. I have also added the contenttype header in edit request.
Befor the request...Yes it does. I have pasted it in my q
0

Try with changing the code consumes=MediaType.APPLICATION_JSON_VALUE with consumes="application/json" Do the same for produces if it gives errors to the response too. Eventually if it doesn't works try removing on the clientside code, in the header declaration the charset encoding, leaving just the application/json declaration.

Hope this helps.

Cheers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.