之前开发网页,无论是之前的php还是后来的jsp,数据的传输主要都是在服务器上,与客户端的数据传输都是:客户端通过get/post方法发送请求,服务器端对数据进行处理,最终返回html文本。就客户端来说,即使是post方法,也只是传输的是键值对,服务器返回的是html文本,其他复杂结构的数据的交互都只是发生在服务器端。然而现在来搞app后端,部分处理逻辑转移到app端,服务器方面更多是像mvc中的m,而且也多了复杂结构的数据的传输,这是便是json大显身手的时候了。由于json在与类的相互转换的优越性,和根据http传输的便捷性,于是它便成了app端与服务器传输数据的主要格式。
//组装日期传递到前台
JSONArray companyJson = new JSONArray();
PrintWriter out = null;
//设置响应头
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setContentType("text/json;charset=utf-8");
//获取输出
out = response.getWriter();
for(TelephoneSchedule a : companyJsons )
{
JSONObject json = new JSONObject();
json.put("id", a.getBeginPeriod());
json.put("name", a.getEndPeriod());
companyJson.add(json);
}
//传递业务类型到数据库
model.addAttribute("date",companyJsons);
out.println(companyJson);
out.flush();
out.close();
以上是服务器往app发送json数据的例子,然后spring mvc已经较好帮我们做好了这方面的过程,我们只需:
在方法名前面增加@ResponseBody注解。如果Spring发现
- 项目lib库中含有相应的json包(例如Jackson)
- Spring启用了
mvc:annotation-driven
MVC注解配置 - 返回的方法使用了@ResponseBody注解
Spring 会自动进行JSON的转换。
JSONController.java如下所示:
package com.mkyong.common.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mkyong.common.model.Shop;
@Controller
@RequestMapping("/kfc/brands")
public class JSONController {
@RequestMapping(value="{name}", method = RequestMethod.GET)
public @ResponseBody Shop getShopInJSON(@PathVariable String name) {
Shop shop = new Shop();
shop.setName(name);
shop.setStaffName(new String[]{"mkyong1", "mkyong2"});
return shop;
}
}