Spring RESTful服务接收和返回JSON最佳实践
返回JSON
1) 用Maven构建web项目:
构建过程参考limingnihao的blog(写得相当的详细!!!):使用Eclipse构建Maven的SpringMVC项目
注解@ResponseBody可以将结果(一个包含字符串和JavaBean的Map),转换成JSON。由于Spring是采用对JSON进行了封装的jackson来生成JSON和返回给客户端,所以这里需要添加jackson的相关包。项目的pom.xml配置如下:
@RequestMapping("/jsonfeed") public @ResponseBody Object getJSON(Model model) { List<TournamentContent> tournamentList = new ArrayList<TournamentContent>(); tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "World Cup", "www.fifa.com/worldcup/")); tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "U-20 World Cup", "www.fifa.com/u20worldcup/")); tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "U-17 World Cup", "www.fifa.com/u17worldcup/")); tournamentList.add(TournamentContent.generateContent("中超", new Date(), "中超", "www.fifa.com/confederationscup/")); model.addAttribute("items", tournamentList); model.addAttribute("status", 0); return model; }
5)将运行项目,在浏览器中输入http://[host]:[port]/[appname]/jsonfeed.json,例如楼主的实例中输入如下:http://localhost:7070/rest-spring/jsonfeed/,得到结果为:
//FINAL package com.watson.rest.json; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.watson.rest.feeds.TournamentContent; import java.util.ArrayList; import java.util.Date; import java.util.List; @Controller public class FeedController { @RequestMapping("/jsonfeed") public String getJSON(Model model) { List<TournamentContent> tournamentList = new ArrayList<TournamentContent>(); tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "World Cup", "www.fifa.com/worldcup/")); tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "U-20 World Cup", "www.fifa.com/u20worldcup/")); tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "U-17 World Cup", "www.fifa.com/u17worldcup/")); tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "Confederations Cup", "www.fifa.com/confederationscup/")); model.addAttribute("items", tournamentList); model.addAttribute("status", 0); return "jsontournamenttemplate"; } }
这里的TournamentContent是自定义的POJO类:
public class TournamentContent { private static int idCounter = 0; private String author; private Date publicationDate; private String name; private String link; private int id; public static TournamentContent generateContent(String author, Date date, String name, String link) { TournamentContent content = new TournamentContent(); content.author = author; content.publicationDate = date; content.name = name; content.link = link; content.id = idCounter++; return content; } //省略getter、setter }
5)将运行项目,在浏览器中输入http://[host]:[port]/[appname]/jsonfeed.json,例如楼主的实例中输入如下:http://localhost:7070/rest-spring/jsonfeed.json,得到结果为:
@RequestMapping(value="/add",method=RequestMethod.POST) @ResponseBody public Object addUser(@RequestBody User user) { System.out.println(user.getName() + " " + user.getAge()); return new HashMap<String, String>().put("success", "true"); }
这里的POJO如下:
public class User { private String name; private String age; //getter setter }
2)而在前台,我们可以用 jQuery 来处理 JSON。从这里,我得到了一个 jQuery 的插件,可以将一个表单的数据返回成JSON对象:
- $.fn.serializeObject = function(){
- var o = {};
- var a = this.serializeArray();
- $.each(a, function(){
- if (o[this.name]) {
- if (!o[this.name].push) {
- o[this.name] = [o[this.name]];
- }
- o[this.name].push(this.value || '');
- }
- else {
- o[this.name] = this.value || '';
- }
- });
- return o;
- };
以下是使用 jQuery 接收、发送 JSON 的代码:
- $(document).ready(function(){
- jQuery.ajax({
- type: 'GET',
- contentType: 'application/json',
- url: 'jsonfeed.do',
- dataType: 'json',
- success: function(data){
- if (data && data.status == "0") {
- $.each(data.data, function(i, item){
- $('#info').append("姓名:" + item.name +",年龄:" +item.age);
- });
- }
- },
- error: function(){
- alert("error")
- }
- });
- $("#submit").click(function(){
- var jsonuserinfo = $.toJSON($('#form').serializeObject());
- jQuery.ajax({
- type: 'POST',
- contentType: 'application/json',
- url: 'add.do',
- data: jsonuserinfo,
- dataType: 'json',
- success: function(data){
- alert("新增成功!");
- },
- error: function(){
- alert("error")
- }
- });
- });
- });
但是似乎用Spring这套东西真是个麻烦的事情,相对Jersey对RESTful的实现来看,确实有很多不简洁的地方。
参考:
官方文档:http://static.springsource.org/spring/docs/3.0.0.M3/spring-framework-reference/html/ch18.html
badqiu的BOLG: 《spring REST中的内容协商(同一资源,多种展现:xml,json,html)》
liuweifeng的BOLG :http://blog.liuweifeng.net/archives/407
Gary Mark等的书籍:《Spring Recipes》2ed