SpringMVC中@ResponseBody的相關注意點
阿新 • • 發佈:2019-01-05
博主習慣性用SpringMVC的@ResponseBody註解返回JSON字串,原先採用的方法是GSON將物件轉換成json字串。(需要引入gson-2.x.x.jar的jar包)
如上程式碼所示,Controller的返回值就為String型別。@ResponseBody @RequestMapping(value = "/cpuUsage.do", produces = "text/html;charset=UTF-8") public String getCpuUsage(@RequestParam(value = "name", required = true) String clusterName) { logger.info("/charts/cluster/cpuUsage.do?name=" + clusterName); String ans = null; try { ans = clusterChartsService.getCpuUsage(clusterName); logger.info(ans); } catch (InstantiationException | IllegalAccessException | RuntimeFaultFaultMsg | DatatypeConfigurationException | NullPointerException | ConnectException | XMLStreamException e) { logger.error(e.getMessage()); } return ans; }
在getCpuUsage()方法中:
採用Gson將物件轉換成JSON字串,然後返回給前端呼叫。public String getCpuUsage(String clusterName) throws RuntimeFaultFaultMsg, DatatypeConfigurationException, InstantiationException, IllegalAccessException, ConnectException, XMLStreamException { double value = MoniterWsInterface.getClusterCpuUsageByClusterName(clusterName); Charts charts = new Charts(value, new Date()); String ans = Gson.class.newInstance().toJson(charts); return ans; }
但是有些讀者可能瞭解到Spring的@ResponseBody可以自動將物件轉換為JSON物件然後返回給前端,這裡專案中需要加入兩個jar包:jackson-core-asl-1.9.x.jar和jackson-mapper-asl-1.9.x.jar。然後在springMVC的配置檔案中加入:
<mvc:annotation-driven />
這句即可,也可以顯示的標註,即在springMVC的配置檔案中加入:
這樣就可以採用@ResponseBody註解自動將物件(包括普通物件,List物件,Map物件等)轉換為JSON.<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <ref bean="mappingJacksonHttpMessageConverter" /> </property> </bean> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean>
@RequestMapping("/test.do")
@ResponseBody
public List<String> test(){
List<String> list = new ArrayList<String>();
list.add("zzh1");
list.add("zzh1");
list.add("zzh2");
list.add("字串");
return list;
}
如上程式碼可以看到直接返回一個List的物件,這裡springMVC的@ResponseBody標籤會自動採用jackson講物件轉換為JSON。
這裡有個小坑。在@ResponseBody註解上面還有一個@RequestMapping註解,有時候需要顯示的標註一些資訊,如:
@RequestMapping(value = "/test.do", produces = "application/json;charset=UTF-8")
如果這裡的produces=“text/html,charset=UTF-8”就會報錯:HTTP406的錯誤。所以這裡要特別的小心。
好了@ResponseBody的相關知識先說到這裡,以後繼續補充。