json is a common passing format, a key-value-based format. And the data size will be relatively small, making it easy to pass. Therefore, json is often used in development.
First, let’s take a look at the format of json:
{key1: value1, key2: value2}Each build corresponds to a value, and each key-value pair is connected by commas. And there is no comma after the last key-value pair, and the whole need to be enclosed in braces.
Generally, when a normal servlet returns json, it will look like the following:
response.setContentType("text/JSON;charset=utf-8");response.getWriter().print(gson.toJson(page));response.getWriter().flush();response.getWriter().close();return null;This is relatively troublesome and difficult to encapsulate. When the new version of spring returns json, you can return it directly through @ResponseBody. This is done very well. The general code is as follows:
@Controller@RequestMapping("/json")public class JsonController { @RequestMapping(value="{provinceId}",method = RequestMethod.GET) @ResponseBody public String pagination(@PathVariable String provinceId){ return getJsonData(provinceId); }}The access method is as follows: http://localhost:8080/spring3/action/json/1. One thing to note is that when accessing the spring mvc controller, a /action is added in the middle. That is because if the mapping path of the DispatcherServlet is directly used /*, the corresponding jsp will be blocked, so a prefix must be added to distinguish jsp from controller.
If there is Chinese in the json above, garbled code will appear, so modify the spring-servlet.xml configuration file and modify the messageConverters of AnnotationMethodHandlerAdapter, because it uses the iso8895-1 encoding by default, the code is as follows:
<bean> <property name="webBindingInitializer"> <bean /> </property> <property name="messageConverters"> <list> <bean> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean>
After these steps, the processing of json is quite convenient.