SpringMVC4.0 and later versions return json format data, springmvc4.0json

Source: Internet
Author: User

SpringMVC4.0 and later versions return json format data, springmvc4.0json

I did not write well for my first blog post, but I hope it will help you. I hope you can make a lot of mistakes. I have been troubled by this problem for two days, and these two days I can't sleep. I have been thinking about this problem. Not much nonsense.

1. Create a web project and add SpringMVC jar. Here I demonstrate using spring-framework-4.2.3.RELEASE. Shows the jar package:

2. Configure web. xml as follows:

<? Xml version = "1.0" encoding = "UTF-8"?>
<Web-app version = "2.5"
Xmlns = "http://java.sun.com/xml/ns/javaee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee
Http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd>

<Servlet>
<Servlet-name> SpringMVC </servlet-name>
<Servlet-class> org. springframework. web. servlet. DispatcherServlet </servlet-class>
<Init-param>
<Param-name> contextConfigLocation </param-name>
<Param-value> classpath: applicationContext. xml </param-value>
</Init-param>
</Servlet>

<Servlet-mapping>
<Servlet-name> SpringMVC </servlet-name>
<Url-pattern>/</url-pattern>
</Servlet-mapping>

</Web-app>

3. Configure applicationContext. xml

<? Xml version = "1.0" encoding = "UTF-8"?>
<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-4.1.xsd
Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd ">
<Context: component-scan base-package = "cn. xugang..."> </context: component-scan>
<Mvc: annotation-driven content-negotiation-manager = "contentNegotiationManagerFactoryBean"/>
<Mvc: default-servlet-handler/>
<Bean class = "org. springframework. web. accept. ContentNegotiationManagerFactoryBean" id = "contentNegotiationManagerFactoryBean">
<Property name = "favorPathExtension" value = "false"/>
<Property name = "favorParameter" value = "false"/>
<Property name = "ignoreAcceptHeader" value = "false"/>
<Property name = "mediaTypes">
<Map>
<Entry key = "xml" value = "application/xml"/>
<Entry key = "json" value = "application/json"/>
<Entry key = "xls" value = "application/vnd. ms-excel"/>
</Map>
</Property>
</Bean>
<Bean class = "org. springframework. http. converter. json. MappingJackson2HttpMessageConverter" id = "mappingJacksonHttpMessageConverter">
<Property name = "supportedMediaTypes">
<List>
<Value> text/html; charset = UTF-8 </value>
</List>
</Property>
</Bean>
<Bean id = "annotationMethodHandlerAdapter" class = "org. springframework. web. servlet. mvc. annotation. AnnotationMethodHandlerAdapter">
<Property name = "messageConverters">
<List>
<Ref bean = "mappingJacksonHttpMessageConverter"/>
</List>
</Property>
</Bean>


<Bean class = "org. springframework. web. servlet. view. InternalResourceViewResolver">
<Property name = "prefix" value = "/WEB-INF/jsp/"> </property>
<Property name = "suffix" value = ". jsp"> </property>
</Bean>
</Beans>

4. Configure to create a controller and use the @ Responsebody annotation to specify the returned content.

Package cn. xugang. cotroller;

Import org. springframework. stereotype. Controller;
Import org. springframework. web. bind. annotation. RequestMapping;
Import org. springframework. web. bind. annotation. RequestMethod;
Import org. springframework. web. bind. annotation. ResponseBody;

Import cn. xugang. entity. User;

@ Controller
@ RequestMapping ("/user ")
Public class UserCotroller {
@ RequestMapping (value = "/hello.html", method = RequestMethod. GET)
Public @ ResponseBody User hello (){
User user = new User ();
User. setAge (19 );
User. setName ("test ");
Return user;
}
@ RequestMapping (value = "/test.html ")
Public String test (){
System. out. println ("hello world ");
Return "hello ";
}
}
5. Send an asynchronous request. Because I used Etx. js, I directly used ext. js to send an asynchronous request.

Ext. onReady (function (){
Ext. define ('user ',{
Extend: 'ext. data. model ',
Fields: ['name', 'age'],
});
Var store = Ext. create ('ext. data. store ',{
Model: 'user ',
Proxy :{
Type: 'ajax ',
Url: '/SpringMVC4/user/hello.html ',
Reader :{
Type: 'json ',

}
}

});

Store. load ({
Callback: function (records, operation, success ){
If (success ){
Var msg = [];
Store. each (function (user ){
Msg. push (user. get ('name') + "" + user. get ('age '));

});
Ext. MessageBox. alert ("prompt", msg. join ("<br> "));
}
}


});
Var msg = [];
Store. each (function (user ){
Msg. push (person. get ('name') + "" + user. get ('age '));

});
Ext. MessageBox. alert ('hprompt ', msg. join ("<br> "));

});

6. Result demonstration

7. summary: At last, SpringMVC4.0 and later versions successfully return json in this way. If the returned value is below 4.0, it is also a pitfall because of different json parsing methods, I collected a lot of information on the Internet, read it in the fog, and it was completely unusable. Finally, I carefully summarized the content described in this article. The following jar packages can be used for less than 4.0.

Configure the following code in applicationContext. xml:

<? Xml version = "1.0" encoding = "UTF-8"?>
<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-4.1.xsd
Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd ">
<Context: component-scan base-package = "cn. xugang..."> </context: component-scan>
<Mvc: annotation-driven/>
<Mvc: default-servlet-handler/>
<Bean class = "org. springframework. http. converter. json. MappingJacksonHttpMessageConverter" id = "mappingJacksonHttpMessageConverter">
<Property name = "supportedMediaTypes">
<List>
<Value> application/json; charset = UTF-8 </value>
</List>
</Property>
</Bean>
<Bean class = "org. springframework. web. servlet. view. InternalResourceViewResolver">
<Property name = "prefix" value = "/WEB-INF/jsp/"> </property>
<Property name = "suffix" value = ". jsp"> </property>
</Bean>
</Beans>

Finally, I hope the post will be useful to you. For the first time I wrote it, it is not very good in many places. Please forgive me. If you have any questions about the above, you can leave a message. If it is reproduced, indicate the source. Thank you!

 

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.