Preface
After learning spring mvc, I found that spring mvc is more convenient than struts2 to return json data, just use @ResponseBody
@ResponseBody
Used when the returned data is not a page with an html tag, but data in some other format (such as json, xml, etc.);
If we do not configure json processing in springMvc, we usually obtain data in the Controller layer and convert the data into a json string, such as calling fastjson for conversion, as follows
@RequestMapping("/getCategoryTree") @ResponseBody public String getmCategoryTree() { String data = JSON.toJSONString(categoryService.getCategoryList()); return data; }In this way, when we have a lot of json data that needs to be returned, we have to write a conversion in each method and then return. The following configuration in the xml configuration file of springmvc can eliminate the conversion operations in the future code
The configuration is as follows
<bean id="jsonConverter"class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean> <bean> <property name="messageConverters"> <list> <ref bean="jsonConverter" /> </list> </property> </bean>
Note: This configuration also needs to be imported in the pom.xml file
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.4</version> </dependency>
Now let’s take a look at the code in the Controller layer.
@RequestMapping("/getCategoryTree") @ResponseBody public List<Category> getCategoryTree() { return categoryService.getCategoryList(); }At this time, there is no such step of json conversion, but note that the return result at this time is no longer String type, but must be kept consistent with the return type in the service layer.
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.