Spring MVC is a follow-up product of SpringFrameWork and has been integrated into Spring Web Flow. The Spring framework provides full-featured MVC modules for building web applications. Using Spring's pluggable MVC architecture, when using Spring for WEB development, you can choose to use Spring's SpringMVC framework or integrate other MVC development frameworks, such as Struts1, Struts2, etc.
1. The first method is a product of the spring2 era, that is, each json view controller is configured with a Jsoniew.
For example:
or
You also need to use Jackson’s jar package.
2. The second type uses JSON tools to serialize objects into json. Common tools include Jackson, fastjson, and gson.
Use HttpServletResponse, and then get response.getOutputStream() or response.getWriter()
Output directly.
Example:
public class JsonUtil { private static Gson gson=new Gson(); /** * @MethodName : toJson * @Description : 将对象转为JSON串,此方法能够满足大部分需求 * @param src * :将要被转化的对象 * @return :转化后的JSON串 */ public static String toJson(Object src) { if (src == null) { return gson.toJson(JsonNull.INSTANCE); } return gson.toJson(src); } }
3. The third way to use spring mvc3 annotation @ResponseBody
For example:
@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(); }
Then use the default configuration of spring mvc to return json, but you need the jackson jar package.
Note: When
If you manually inject RequestMappingHandlerAdapter, you can set it like this
The configuration is as follows:
<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 package
jackson-mapper-asl-*.jar
jackson-core-asl-*.jar
It can be seen that the usage methods are getting simpler and simpler, and programmers are getting stupider and stupider. I don’t know whether this is a good thing or a bad thing...
The above content is the three ways that SpringMVC returns json data shared by the editor. I hope you like it.