Spring MVC returns JSON

Source: Internet
Author: User

The server side returns the text, the client obtains the text to convert the text to JSON, the server side transforms the object into the JSON text form, and needs to set the text the type to be text/plain,charset=utf-8

So add stringconverter and jsonconvert beans and servlet MVC annotation processing adapters in Application-context

<bean id="Stringconverter"

class="Org.springframework.http.converter.StringHttpMessageConverter">

<property name="Supportedmediatypes">

<list>

<value>text/plain; CharSet=utf-8</value>

</list>

</property>

</bean>

<!--used to convert an object to JSON--

<bean id="Jsonconverter"

class="Org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>

<bean

class="Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">

<property name="Messageconverters">

<list>

<ref bean="Stringconverter" />

<ref bean="Jsonconverter" />

</list>

</property>

</bean>

In the controller function to indicate that the return value is responsebody content

@RequestMapping ("/ajax2.do")

public @ResponseBody UserInfo ajax2 (String userId) {

System. out. println (userId);

UserInfo user = new UserInfo ();

if ("1001". Equals (UserId)) {

User.setuserid (1001);

User.setusername ("Goku");

}Else{

User.setuserid (1002);

User.setusername ("eight commandments");

}

return user;

}

Js Code

$ ("#but2"). Click (function() {

$.post ("Ajax2.do", {userid:$ ("#userId2"). Val ()},function(data) {

$ ("#info2"). html (data.userid+ "---" +data.username);

}, "JSON");

});

Spring MVC returns JSON

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.