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

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

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

2、stlet的思想是:HTTP客戶端與HTTP服務器之間的差別,對架構來說無所謂。一個軟件應可以既充當Web客戶端又充當Web服務器,而無須采用兩套完全不同的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服務JAX-RS (JSR-311) 是一種 Java

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

4、的圖片是我加入的相關的jar包:這個是必須的,如果是用于JAX-RS發布rest的話,還需要這幾個包:3、創建Student實體類,用于返回數據。Student使用JAXB綁定技術,自動解析為xml返回給客戶端或瀏覽器。JAXB是一套自動映射XML和Java實例的開發接口和工具。JAXB使XML更加方便的編譯一個XML SCHEMA到一個或若干個JAVA CLASS。可以從使用JAXB 進行數據綁定  獲得詳細介紹。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架構主要是Application和Resource的概念。程序上可以定義多個Resource,一個Application可以管理多個Resource。創建應用類:StudentApplication 繼承了抽象類:,并重載getClasses()方法。代碼如下:Set<Class<?>> rrcs = new Ha

8、shSet<Class<?>>();rrcs.add(StudentResource.class);綁定了StudentResource。有多個資源可以在這里綁定。你可以有Course等其他更多資源,相應的可以定義為:CourseResource及Course,然后加入rrcs.add(CourseResource.class)。創建資源類: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”)執行了uri路徑,student路徑進來的都會調用StudentResource來處理。

10、GET 說明了http的方法是get方法。Path(“id/xml”) 每個方法前都有對應path,用來申明對應uri路徑。Produces(“application/xml”) 指定返回的數據格式為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”)  指定返回的數據格式為json。5、定義了相應的Resource和Application后,還要創建運行環境。RESTlet 架構為了更好的支持 JAX-RS 規范,定了 JaxRsApplication 類來初始化基于 JAX-RS 的 Web Service 運行環境。創建運行類:RestJaxRsApplication  繼承了類:。構造方法代碼如下:public RestJaxRsApplication(Context context) &

12、#160;super(context); this.add(new StudentApplication();將StudentApplication加入了運行環境中,如果有多個Application可以在此綁定。二、發布和部署restlet服務1、將Restlet服務部署到 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服務當做單獨的Java 程序進行部署創建類 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(); 該類中創建一個新的 Http Server,添加監聽端口8085。將RestJaxRsApplication加入到 Http Server 中。運行該代碼,下圖說明你啟動成功。三、測試Restlet服務1、瀏覽器模式訪問xml數據http:/localhost:8085/Re

16、stService/student/1/xml訪問json數據http:/localhost:8085/RestService/student/1/json  提示下載數據,下載后打開數據內容為“name”:”Steven”,”id”:1,”age”:0,”sex”:1,”clsId”:201001如果是獨立部署的話,直接訪問:http:/localhost:8085/student/1/xml即可。2、Restlet自帶了客戶端測試代碼,目前提供了jee、webkit、android等版本,調用rest服務,非常方便。新建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測試代碼分別輸出:四、實現對Res

20、t服務的PUT,POST,DELETE方法。到現在我們已經完成一個基本的Rest搭建,并且實現了GET方法。REST定義了4個基本方法:可以參見REST架構概述。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方法調用,如果是用restlet客戶端調用的話,調用client.post(form.getWebRepresentation()方法,如果是網頁上面操作的話,就是一個標準的post方法。Representation entity:Restlet中全部的接受和返回對象都Representation類的子類。將entity 封裝為Form對象,就可以通過Form取得post過來的數據。相應的客戶端調用代

23、碼:public static void testPost() ClientResource client = new ClientResource(url+”student/add”);try  Form form = new Form(); form.add(“name”, “lifeba”); 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();將需要傳遞的參數封裝為Form對象,然后通過post(form.getWebRepresentation()來調用服務端post方法,返回時添加成功的Student的id。添加成功后,訪問:http:/localhost:8085/RestService/student/2/xml  如下圖:除了上面的通過restlet提供的客戶端調用外,你也可以直接通過網頁的post數據過

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數據:2、PUT方法PUT方法用來更新一個Student對象,和上面的POST方法類似。需要注意的地方,如果是通過restlet客戶端接口來調用的話,必須使用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客戶端調用代碼,對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(); 執行后訪問http:/localhost:8085/RestService/student/1/xml:那么我們如何從網頁中直接調用put接口呢?form只有get和post方法,并沒有put和delete的對應方法。Restlet為我們提供了method指定操作

31、的支持。要在form中執行同樣的操作,只需加入method=put即可,可以通過url直接拼接,或者post中加入隱藏input。這里如果直接拼接URL來實現,代碼如下:<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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論