開發(fā)實例一基于JAXRS的REST服務(wù)_第1頁
開發(fā)實例一基于JAXRS的REST服務(wù)_第2頁
開發(fā)實例一基于JAXRS的REST服務(wù)_第3頁
開發(fā)實例一基于JAXRS的REST服務(wù)_第4頁
開發(fā)實例一基于JAXRS的REST服務(wù)_第5頁
已閱讀5頁,還剩15頁未讀 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

1、RESTLET開發(fā)實例(一)基于JAX-RS的REST服務(wù)RESTLET介紹Restlet項目為“建立REST概念與Java類之間的映射”提供了一個輕量級而全面的框架。它可用于實現(xiàn)任何種類的REST式系統(tǒng),而不僅僅是REST式Web服務(wù)。Restlet項目受到Servlet API、JSP(Java Server Pages)、HttpURLConnection及Struts等Web開發(fā)技術(shù)的影響。該項目的主要目標是:在提供同等功能的同時,盡量遵守Roy Fielding博士論文中所闡述的REST的目標。它的另一個主要目標是:提出一個既適于客戶端應(yīng)用又適于服務(wù)端的應(yīng)用的、統(tǒng)一的Web視圖。Re

2、stlet的思想是:HTTP客戶端與HTTP服務(wù)器之間的差別,對架構(gòu)來說無所謂。一個軟件應(yīng)可以既充當Web客戶端又充當Web服務(wù)器,而無須采用兩套完全不同的APIs。準備工作1、Restlet提供了多個版本:Java SE、Java EE、android、Google AppEngine、Google Web Toolkit、Android。這里我們下載jee版本。restlet-jee-.zip 下載地址:2、restlet-jee-.zip解壓到硬盤,這里以%RESTLET_HOME%表示為解壓的文件目錄。一、基于JAX-RS的REST服務(wù)JAX-RS (JSR-311) 是一種 Java

3、 API,可使 Java Restful 服務(wù)的開發(fā)變得迅速而輕松。這個 API 提供了一種基于注釋的模型來描述分布式資源。注釋被用來提供資源的位置、資源的表示和可移植的(pluggable)數(shù)據(jù)綁定架構(gòu)。在本文中,學習如何使用 JAX-RS 在 Java EE 環(huán)境內(nèi)實現(xiàn) RESTful 服務(wù)架構(gòu)的潛能。1、新建java web project RestService工程2、%RESTLET_HOME%lib 復(fù)制到 RestServiceWebRootWEB-INFlib 下,并加入工程引用。為了測試方便可以將全部的lib包加入進去。實際上面,你可以根據(jù)實際需要只復(fù)制相應(yīng)的包進去即可。下面

4、的圖片是我加入的相關(guān)的jar包:這個是必須的,如果是用于JAX-RS發(fā)布rest的話,還需要這幾個包:3、創(chuàng)建Student實體類,用于返回數(shù)據(jù)。Student使用JAXB綁定技術(shù),自動解析為xml返回給客戶端或瀏覽器。JAXB是一套自動映射XML和Java實例的開發(fā)接口和工具。JAXB使XML更加方便的編譯一個XML SCHEMA到一個或若干個JAVA CLASS。可以從使用JAXB 進行數(shù)據(jù)綁定  獲得詳細介紹。XmlRootElement(name=”Student”)public class Student   private int id; p

5、rivate String name; private int sex; private int clsId; private int age;  public int getId()   return id;  public void setId(int id)   this.id = id;  public String getName()   return name;  public void setName(Strin

6、g name)    = name;  public int getSex()   return sex;  public void setSex(int sex)   this.sex = sex;  public int getClsId()   return clsId;  public void setClsId(int clsId)   this.clsId = clsId; &

7、#160;public int getAge()   return age;  public void setAge(int age)   this.age = age; 4、Restlet架構(gòu)主要是Application和Resource的概念。程序上可以定義多個Resource,一個Application可以管理多個Resource。創(chuàng)建應(yīng)用類:StudentApplication 繼承了抽象類:,并重載getClasses()方法。代碼如下:Set<Class<?>> rrcs = new Ha

8、shSet<Class<?>>();rrcs.add(StudentResource.class);綁定了StudentResource。有多個資源可以在這里綁定。你可以有Course等其他更多資源,相應(yīng)的可以定義為:CourseResource及Course,然后加入rrcs.add(CourseResource.class)。創(chuàng)建資源類:StudentResource管理Student實體類Path(“student”)public class StudentResource       GET  

9、;   Path(“id/xml”)     Produces(“application/xml”)     public Student getStudentXml(PathParam(“id”) int id)    return ResourceHelper.getDefaultStudent();     其中:Path(“student”)執(zhí)行了uri路徑,student路徑進來的都會調(diào)用StudentResource來處理。

10、GET 說明了http的方法是get方法。Path(“id/xml”) 每個方法前都有對應(yīng)path,用來申明對應(yīng)uri路徑。Produces(“application/xml”) 指定返回的數(shù)據(jù)格式為xml。PathParam(“id”) int id  接受傳遞進來的id值,其中id為 id定義的占位符要一致。和上面類似,我們可以定義返回json格式方法,如下GETPath(“id/json”)Produces(“application/json”)public Student getStudentJson(PathParam(“id”) int id)   return

11、 ResourceHelper.findStudent(id);其中:Produces(“application/json”)  指定返回的數(shù)據(jù)格式為json。5、定義了相應(yīng)的Resource和Application后,還要創(chuàng)建運行環(huán)境。RESTlet 架構(gòu)為了更好的支持 JAX-RS 規(guī)范,定了 JaxRsApplication 類來初始化基于 JAX-RS 的 Web Service 運行環(huán)境。創(chuàng)建運行類:RestJaxRsApplication  繼承了類:。構(gòu)造方法代碼如下:public RestJaxRsApplication(Context context) &

12、#160;super(context); this.add(new StudentApplication();將StudentApplication加入了運行環(huán)境中,如果有多個Application可以在此綁定。二、發(fā)布和部署restlet服務(wù)1、將Restlet服務(wù)部署到 Tomcat容器中web.xml加入如下代碼:<context-param> <param-name>org.restlet.application</param-name> <param-value>ws.app.RestJaxRsApplic

13、ation</param-value></context-param><servlet> <servlet-name>RestletServlet</servlet-name> <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class></servlet><servlet-mapping> <servlet-name>RestletServlet</servlet

14、-name> <url-pattern>/*</url-pattern></servlet-mapping>啟動tomcat沒報錯的話,說明你配置正常。2、將Restlet服務(wù)當做單獨的Java 程序進行部署創(chuàng)建類 RestJaxRsServer,代碼如下:public static void main(String args) throws  Exception  Component component = new Component(); component.getServers().add(Protocol

15、.HTTP, 8085);         component.getDefaultHost().attach(new RestJaxRsApplication(null); component.start(); 該類中創(chuàng)建一個新的 Http Server,添加監(jiān)聽端口8085。將RestJaxRsApplication加入到 Http Server 中。運行該代碼,下圖說明你啟動成功。三、測試Restlet服務(wù)1、瀏覽器模式訪問xml數(shù)據(jù)http:/localhost:8085/Re

16、stService/student/1/xml訪問json數(shù)據(jù)http:/localhost:8085/RestService/student/1/json  提示下載數(shù)據(jù),下載后打開數(shù)據(jù)內(nèi)容為“name”:”Steven”,”id”:1,”age”:0,”sex”:1,”clsId”:201001如果是獨立部署的話,直接訪問:http:/localhost:8085/student/1/xml即可。2、Restlet自帶了客戶端測試代碼,目前提供了jee、webkit、android等版本,調(diào)用rest服務(wù),非常方便。新建Client類,代碼如下:/public static St

17、ring url=”http:/localhost:8085/“; public static String url=”http:/localhost:8085/RestService/“;public static void testXml()  ClientResource client = new ClientResource(url+”student/1/xml”); try   System.out.println(client.get().getText();  catch (ResourceException e) &#

18、160; / TODO Auto-generated catch block  e.printStackTrace();  catch (IOException e)   / TODO Auto-generated catch block  e.printStackTrace(); public static void testJson()  ClientResource client = new ClientResource(url+”student/1/json”); try &#

19、160; System.out.println(client.get().getText();  catch (ResourceException e)   / TODO Auto-generated catch block  e.printStackTrace();  catch (IOException e)   / TODO Auto-generated catch block  e.printStackTrace(); 通過junit測試代碼分別輸出:四、實現(xiàn)對Res

20、t服務(wù)的PUT,POST,DELETE方法。到現(xiàn)在我們已經(jīng)完成一個基本的Rest搭建,并且實現(xiàn)了GET方法。REST定義了4個基本方法:可以參見REST架構(gòu)概述。1、POST方法在StudentResource中加入該方法,用于添加一個Student:POSTPath(“add”)public String addStudent(Representation entity)   Form form = new Form(entity);  String name = form.getFirstValue(“name”);  int clsId = Integer.

21、parseInt(form.getFirstValue(“clsId”);  int sex = Integer.parseInt(form.getFirstValue(“sex”);  Student student = new Student();  student.setClsId(clsId);  student.setName(name);  student.setSex(sex);  ResourceHelper.maxId+;  int id =  ResourceHelper.maxId; 

22、; student.setId(id);  return String.valueOf(ResourceHelper.addStudent(student);POST 說明這是個post方法調(diào)用,如果是用restlet客戶端調(diào)用的話,調(diào)用client.post(form.getWebRepresentation()方法,如果是網(wǎng)頁上面操作的話,就是一個標準的post方法。Representation entity:Restlet中全部的接受和返回對象都Representation類的子類。將entity 封裝為Form對象,就可以通過Form取得post過來的數(shù)據(jù)。相應(yīng)的客戶端調(diào)用代

23、碼:public static void testPost() ClientResource client = new ClientResource(url+”student/add”);try  Form form = new Form(); form.add(“name”, “l(fā)ifeba”); form.add(“clsId”,”201001); form.add(“sex”,”0); String id = client.post(form.getWebRepresentation().getText(); System.ou

24、t.println(id);  catch (Exception e)  / TODO Auto-generated catch block e.printStackTrace();將需要傳遞的參數(shù)封裝為Form對象,然后通過post(form.getWebRepresentation()來調(diào)用服務(wù)端post方法,返回時添加成功的Student的id。添加成功后,訪問:http:/localhost:8085/RestService/student/2/xml  如下圖:除了上面的通過restlet提供的客戶端調(diào)用外,你也可以直接通過網(wǎng)頁的post數(shù)據(jù)過

25、來。新建java web project RestServiceForm工程,添加add.jsp。<form action=”/RestService/student/add” method=”post”>     用戶名:<input type=”text” name=”name”><br>     班級:<input type=”text” name=”clsId”><br>     性別:<input t

26、ype=”text” name=”sex”><br>     <input type=”submit” value=”提交”></form>提交成功后:測試新添加的student數(shù)據(jù):2、PUT方法PUT方法用來更新一個Student對象,和上面的POST方法類似。需要注意的地方,如果是通過restlet客戶端接口來調(diào)用的話,必須使用client.put(form.getWebRepresentation()方法。主要代碼如下:PUTPath(“update”)public String updateStuden

27、t(Representation entity)   Form form = new Form(entity);  int id = Integer.parseInt(form.getFirstValue(“id”);  Student student = ResourceHelper.findStudent(id);   String name = form.getFirstValue(“name”);  int clsId = Integer.parseInt(form.getFirstValue(“clsId”); 

28、int sex = Integer.parseInt(form.getFirstValue(“sex”);   student.setClsId(clsId);  student.setName(name);  student.setSex(sex);   return String.valueOf(ResourceHelper.updateStudent(student);Restlet客戶端調(diào)用代碼,對id為1的student進行編輯。public static void testUpdate()  ClientReso

29、urce client = new ClientResource(url+”student/update”); try   Form form = new Form();  form.add(“name”, “steven2);  form.add(“clsId”,”201002);  form.add(“sex”,”0);  form.add(“id”,”1);  String id = client.put(form.getWebRepresentation()

30、.getText();  System.out.println(id);    catch (Exception e)   / TODO Auto-generated catch block  e.printStackTrace(); 執(zhí)行后訪問http:/localhost:8085/RestService/student/1/xml:那么我們?nèi)绾螐木W(wǎng)頁中直接調(diào)用put接口呢?form只有g(shù)et和post方法,并沒有put和delete的對應(yīng)方法。Restlet為我們提供了method指定操作

31、的支持。要在form中執(zhí)行同樣的操作,只需加入method=put即可,可以通過url直接拼接,或者post中加入隱藏input。這里如果直接拼接URL來實現(xiàn),代碼如下:<form action=”/RestService/student/update?method=put” method=”post”> 用戶ID:<input type=”text” name=”id” ><br> 用戶名:<input type=”text” name=”name”><br> 班級:<input type=”text” name=”clsId”><br> 性別:<input type=”text” name=”sex”><br> <input typ

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論