1, the first way is the product of the spring2 era, that is, each JSON view controller configuration of a jsoniew.
such as: <bean id= "Defaultjsonview" class= "Org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
or <bean id= "Defaultjsonview" class= "Org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
Also use Jackson's jar package.
2. The second uses the JSON tool to serialize objects into JSON, a common tool jackson,fastjson,gson.
Take advantage of HttpServletResponse, then get Response.getoutputstream () or Response.getwriter ()
Direct output.
Example:
[Java]View Plaincopyprint?
- Public class Jsonutil
- {
- private static Gson gson=new Gson ();
- /**
- * @MethodName: ToJson
- * @Description: Convert object to JSON string, this method can meet most requirements
- * @param src
- *: The object that will be converted
- * @return: Converted JSON string
- */
- public static String ToJson (Object src) {
- if (src = = null) {
- return Gson.tojson (jsonnull.instance);
- }
- return Gson.tojson (SRC);
- }
- }
3, the third use of Spring MVC3 annotation @responsebody
For example:
[Java]View Plaincopyprint?
- @ResponseBody
- @RequestMapping ("/list")
- Public list<string> List (Modelmap modelmap) {
- String hql = "Select C from clothing C";
- page<clothing> page = new page<clothing> ();
- Page.setpagesize (6);
- page = clothingserviceimpl.queryforpagebyhql (page, HQL);
- return Page.getresult ();
- }
You can then return the JSON using the spring MVC default configuration, but you'll need Jackson's jar package.
Note: When using <mvc:annotation-driven/> in Springmvc-servlet.xml, If it is 3.1 before the default injection annotationmethodhandleradapter,3.1 after the default injection requestmappinghandleradapter just add the above mentioned jar package!
If it is manual injection requestmappinghandleradapter can be set
The configuration is as follows:
[HTML]View Plaincopyprint?
- <Bean class="Org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"
- p:ignoredefaultmodelonredirect="true" >
- <property name="Messageconverters">
- <list>
- <Bean class="Org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
- </list>
- </Property>
- </Bean>
Add a Package
Jackson-mapper-asl-*.jar
Jackson-core-asl-*.jar
It can be seen that the use of more and more simple, programmers more and more silly, do not know is good, or bad things ...
Springmvc three ways to return JSON data