在項目中需要寫一個接口,傳回json字元串,供别系統調用,傳回格式如下:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuETMykTM2QDOjlTY00iZzQjYtMjY4MTLwADOz0SN1YjZ4UWN08CXzYjMx8CX0ATMw8CX05WZth2YhRHdh9CXkF2bsBXdvwVbvNmLllXZ0lmLywGZvw1LcpDc0RHaiojIsJye.png)
具體怎麼實作呢,下面以代碼與注釋進行講解如何實作的,我這裡用兩種方式,一是用處理response,第二種方法用spring自帶的功能。
第一種實作方式:
首先要有個controller,當然我這裡寫的是一個很簡單的實作,隻是展現了實作原理,
@RequestMapping(value = "json/blog/{test}")
public String blog(@PathVariable(value = "test") String test,
HttpServletResponse response) {
List<User> userList = new ArrayList<User>();
User userOne = new User("jack","1001","60","25");
User userTwo = new User("jackson","1002","80","20");
userList.add(userOne);
userList.add(userTwo);
return ajaxJson(response, getJson(userList));
}
在上面這段代碼中用到了getJson和ajaxJson方法,這是兩個被封裝了的方法。getJson(Object)就是很簡單的将對象轉換為json串,第二個是對reponse做一定的處理,getJson代碼如下:
private static Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
.setDateFormat("yyyy-MM-dd HH:mm:ss").create();
/**
* 功能描述:根據Object輸出JSON字元串
*/
public String getJson(Object jsonObject) {
return gson.toJson(jsonObject);
}
ajaxJson方法的代碼如下:
public String ajaxJson(HttpServletResponse response,String jsonString) {
return ajax(response,jsonString, "text/html");
}
public String ajax(HttpServletResponse response, String content, String type) {
try {
response.setContentType(type + ";charset=UTF-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.getWriter().write(content);
response.getWriter().flush();
} catch (IOException e) {
log.error("IOException:", e);
}
return null;
}
// 此方法為添加緩存,varnich緩存
public void setCache(HttpServletResponse response, String cacheTime) {
long now = System.currentTimeMillis();
long cacheTimeLong = Long.parseLong(cacheTime);
response.setDateHeader("Expires", now + cacheTimeLong);
response.setDateHeader("Last-Modified", now - (now % cacheTimeLong));
response.setHeader("Cache-Control", "max-age=" + cacheTime+",s-maxage="+ cacheTime);
response.setHeader("Pragma", "Pragma");
}
第二種實作方式就很簡單了,controller修改如下:
@RequestMapping(value = "json/blog/{test}")
@ResponseBody
public List<User> blog(@PathVariable(value = "test") String test,
HttpServletResponse response) {
List<User> userList = new ArrayList<User>();
User userOne = new User("jack","1001","60","25");
User userTwo = new User("jackson","1002","80","20");
userList.add(userOne);
userList.add(userTwo);
return userList;
}
一般在異步擷取資料時使用,在使用@RequestMapping後,傳回值通常解析為跳轉路徑,加上@responsebody後傳回結果不會被解析為跳轉路徑,而是直接寫入HTTP response body中。比如異步擷取json資料,加上@responsebody後,會直接傳回json資料。看來spring夠強大啊,記錄下,不過如果用第二種方式的話,如何添加頁面緩存和處理callback還有待研究,請大神指點一二!!!