转载请标明原文地址:http://blog.csdn.net/jiangsq12345/archive/2011/03/02/6219186.aspx
之前写过一遍关于GAE+JDO搭建商业网站的帖子,而这篇帖子的目的是在原有的源代码基础上稍加改动,让该商业网站支持网络web RESTful服务,本文使用 一个开源项目 Jersey (Jersey is the open source, production quality, JAX-RS (JSR 311) Reference Implementation for building RESTful Web services. )
GAE支持对Jersey的开发,但是新手用起来比较困难,想把个人的经验跟大家分享一下,好让大家少走些弯路
PS: 也可以将Jersey运用到Android等系统开发软件,道理应该差不多,都是google的产品
表象化状态转变 (英文:Representational State Transfer ,简称REST )是Roy Fielding 博士在2000年他的博士论文中提出来的一种软件架构 风格。
目前在三种主流的Web服务 实现方案中,因为REST模式的Web服务 与复杂的SOAP 和XML-RPC 对比来讲明显的更加简洁,越来越多的web服务开始采用REST风格设计和实现。
web服务是基于C/S的模式,所以要分别开发客户端,服务器端。Jersey已经包括所有需要的函数库
假如你的服务器已经搭建好,现在只是想再在此基础上开发Web服务,那是一件比较轻松的事情,因为服务器端的原代码基本上不用改动,我们要做的仅仅是在服务器端加入几个资料URL类,然后开发一个客户端
下面列一下开发过程中容易出错的一些地方
此例告诉网络服务器我们的网络服务URL都在 /resources/ 这个目录后
此类前必须要有 @XmlRootElement 标签
Normal 0 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE MicrosoftInternetExplorer4
附一个URL资源类供参考:
@Path("Cart") /*本资源的URL, ".../resources/Carte" */ public class CartResource extends Cart{ /** * connection * @param ac * @return * @throws IOException */ @Path("Connexion") @PUT @Produces(MediaType.TEXT_PLAIN) /*返回的数据类型*/ @Consumes(MediaType.APPLICATION_XML) /*本函数接受的数据类型*/ public String connect(AccountClient ac) throws IOException { String reponse; if(ac == null) return "false"; PersistenceManager pm = PMF.get().getPersistenceManager(); // verify if this account has exist yet Query query = pm.newQuery(AccountClient.class); query.setFilter("COMPTE == COMPTEParam && CODE == CODEParam"); query.declareParameters("String COMPTEParam,String CODEParam "); List<AccountClient> accounts = (List<AccountClient>) query.execute(ac.getCompte(),ac.getCode());; System.out.println("Accounts size="+accounts.size()); if(accounts.size()== 1){ reponse = "true"; }else reponse = "false"; System.out.println("[Connexion] mail="+ac.getCompte()+"/t reponse="+reponse); return reponse; }
附客户端:
/** * To connecter with his account * @param mail * @param code * @return */ public static boolean connexion(String mail, String code){ WebResource r= client.resource("http://"+addr+":"+port+"/resources/Cart/Connexion"); AccountClient ac = new AccountClient(mail, code); // call the function of server to create an account ClientResponse response = r .accept(MediaType.TEXT_PLAIN) .put(ClientResponse.class, ac); String resultat = response.getEntity(String.class); if(resultat.equals("true")) return true; else return false; }
希望对大家有些帮助
参考链接:
Jersey官网: http://jersey.java.net/
维基百科: http://zh.wikipedia.org/wiki/REST