RESTLET开发实例(二)使用Component、Application的REST服务
2019獨角獸企業(yè)重金招聘Python工程師標準>>>
上一篇文章,我們介紹了基于JAX-RS的REST服務,本篇文章我們介紹不基于JAX-RS的模式。JAX-RS其實就是一個簡單的Application服務。和我們接下來介紹的Application基本一致,唯一不同的地方就是,不使用JAX-RS自動映射為xml。restlet的一些基本概念可以參考上篇文章?RESTLET開發(fā)實例(一)基于JAX-RS的REST服務?的介紹,這里不再闡述。
一、基于ServerResource的REST,來實現(xiàn)JAX-RS中get方法。
1、新建RestApplication Web工程。
然后把相應的restlet的lib下的全部jar加入工程引用中,然后在web.xml,加入如下配置:
<context-param>
<param-name>org.restlet.application</param-name>
<param-value>org.lifeba.ws.app.RestSimpleApplication</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-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
上面的配置和基于JAX-RS的配置一樣的。
2、新建RestSimpleApplication對象。將應用程序和資源類綁定在一起,代碼如下:
public class RestSimpleApplication extends org.restlet.Application{
@Override
public Restlet createInboundRoot() {
Router router = new Router(getContext());
router.attach("/student/{studentId}", StudentResource.class);
return router;
}
}
和JAX-RS不同主要有2個地方:
1)RestSimpleApplication直接擴展了Application對象,而不是JAX-RS中的JaxRsApplication對象。
2)重載了createInboundRoot通過attach方法綁定資源類,并且制定了訪問路徑。而JAX-RS中調用了this.add(new StudentApplication())來綁定資源類,并且不用指定訪問路徑,因為是在資源類中指定。
3、新建Student對象,代碼如下:和JAX-RS的區(qū)別就是少了@XmlRootElement(name="Student")標注。
public class Student {
private int id;
private 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(String name) {
this.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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Id:"+this.id+"\r\nName:"+this.name+"\r\nClass:"+
this.clsId+"\r\nSex:"+this.sex+"\r\nAge:"+this.age;
}
}
4、新建StudentResource類,該類擴展ServerResource類。代碼如下:
public class StudentResource extends ServerResource{
private int id;
@Override
protected void doInit() throws ResourceException {
id = Integer.valueOf((String) getRequestAttributes().get("studentId"));
}
@Get
public Representation get(Representation entity) {
Student student = ResourceHelper.findStudent(id);
return new StringRepresentation(student.toString());
}
}
上面的代碼實現(xiàn)的功能和JAX-RS中的下面的代碼的功能一樣,都是根據ID來獲取對應的student信息。
@GET
@Path("{id}/xml")
@Produces("application/xml")
public Student getStudentXml(@PathParam("id") int id) {
return ResourceHelper.findStudent(id);
}
非JAX-RS模式的,擴展了ServerResource類,并且重載了doInit()方法用來獲取傳遞過來的studentId占位符的值。因為沒有傳遞method方法,默認是調用@Get標注的無參方法,最后返回StringRepresentation對象(你也可以返回xml或json的Representation對象)。
JAX-RS的也是類似,不過他的方法是帶參數,并且返回一個Student對象(會根據@Produces("application/xml")自動封裝xml數據)。
5、完成了上面的主要類得創(chuàng)建和編寫,你就可以在tomcat中運行了,啟動tomcat后,訪問http://localhost:8085/RestApplication/student/1,你將看到下面界面:
二、實現(xiàn)更新、刪除、添加(delete,put,post)及列表展示
1、上面的介紹,我們實現(xiàn)將JAX-RS中的get方法,用ServerResource方式的來實現(xiàn)。根據rest規(guī)范,對StudentResource,除了有get方法外,還有delete及put方法。
@Delete
public Representation delete() {
int status = ResourceHelper.deleteStudent(id);
return new StringRepresentation(String.valueOf(status));
}
@Put
public Representation put(Representation entity)
throws ResourceException {
Form form = new Form(entity);
Student student = ResourceHelper.findStudent(id);
String name = form.getFirstValue("name");
int clsId = Integer.parseInt(form.getFirstValue("clsId"));
int sex = Integer.parseInt(form.getFirstValue("sex"));
student.setClsId(clsId);
student.setName(name);
student.setSex(sex);
return new StringRepresentation(String.valueOf(ResourceHelper.updateStudent(student)));
}
2、測試更新和刪除:
1)通過頁面修改用戶資料
update.jsp頁面中加入:
<form action="/RestApplication/student/1?method=put" method="post">
用戶名:<input type="text" name="name"><br>
班級:<input type="text" name="clsId"><br>
性別:<input type="text" name="sex"><br>
<input type="submit" value="提交">
</form>
提交后訪問,返回1表示修改成功。
訪問http://localhost:8085/RestApplication/student/1就會看到名字已經修改了。
2)通過客戶端刪除用戶資料。新建Client類,加入如下代碼,執(zhí)行成功返回1.
public void student_delete(){
try {
ClientResource client = new ClientResource("http://localhost:8085/RestApplication/student/1");
Representation representation =client.delete();
System.out.println(representation.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
這個時候訪問?http://localhost:8085/RestApplication/student/1?,會提示錯誤。因為找不到這個1的用戶。
3、添加一個student,及顯示全部student信息
1)StudentResource資源,按照restlet的規(guī)范,包含了get put delete方法。所以添加一個student及顯示全部student信息我們需要再加入一個資源類StudentsResource,代碼如下:
@Get
public Representation get(Representation entity) {
StringBuilder sb = new StringBuilder();
Iterator it = ResourceHelper.students.keySet().iterator();
while(it.hasNext()){
sb.append(ResourceHelper.students.get(it.next()).toString()+"\r\n\r\n");
}
return new StringRepresentation(sb.toString());
}
@Post
public Representation post(Representation entity)
throws ResourceException {
Form form = new Form(entity);
String name = form.getFirstValue("name");
int clsId = Integer.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;
student.setId(id);
return new StringRepresentation(String.valueOf(ResourceHelper.addStudent(student)));
}
添加了上面代碼后,我們還要在RestSimpleApplication添加下面代碼,指定下資源類StudentsResource的訪問路徑才可以。
router.attach("/student", StudentsResource.class);
2)首先我們添加一個id為2的student對象,client類中加入下面代碼,執(zhí)行成功后返回新添加的studentid:2。
public void student_post(){
try {
Form queryForm = new Form();
queryForm.add("name","steven3");
queryForm.add("clsId","201002");
queryForm.add("sex","2");
queryForm.add("age","12");
ClientResource client = new ClientResource("http://localhost:8085/RestApplication/student");
Representation representation =client.post(queryForm.getWebRepresentation());
System.out.println(representation.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
訪問http://localhost:8085/RestApplication/student?如下,返回了全部的student資料:
可以看到我們已經成功添加了一個2的student。
三、使用Component綁定多個Application
我們已經實現(xiàn)了一個student的application。里面包含了2個資源類(StudentResource和StudentsResource)。如果我們加入一個course的資源類,我們可以按照上面的方式直接建立CourseResource,然后在RestSimpleApplication中綁定下 router.attach("/course/{courseId}", CourseResource.class)。不過這樣處理會把業(yè)務邏輯混在一起,并不是很好的方法。因此我們建立一個RestCourseApplication,然后在這里綁定CourseResource類,來實現(xiàn)業(yè)務邏輯的分離。
RestCourseApplication代碼如下:
public class RestCourseApplication extends org.restlet.Application{
@Override
public Restlet createInboundRoot() {
Router router = new Router(getContext());
router.attach("/course/{courseId}", CourseResource.class);
return router;
}
}
CourseResource代碼如下:
public class CourseResource extends ServerResource{
private int id;
@Override
protected void doInit() throws ResourceException {
id = Integer.valueOf((String) getRequestAttributes().get("courseId"));
}
@Get
public Representation get(Representation entity) {
return new StringRepresentation("course id:"+id);
}
}
現(xiàn)在我們有2個Application了,web.xml中就不能使用org.restlet.application了,必須使用org.restlet.component。
<context-param>
<param-name>org.restlet.application</param-name>
<param-value>org.lifeba.ws.app.RestSimpleApplication</param-value>
</context-param>
把上面的代碼改為:
<init-param>
<param-name>org.restlet.component</param-name>
<param-value>component</param-value>
</init-param>
新建RestComponent類,代碼如下,因為必須執(zhí)行路徑,所以在訪問的時候記得要帶上對應的前綴。
public class RestComponent extends org.restlet.Component{
public RestComponent(){
getDefaultHost().attach("/a", new RestSimpleApplication());
getDefaultHost().attach("/b", new RestCourseApplication());
}
}
訪問:http://localhost:8085/RestApplication/a/student
訪問:http://localhost:8085/RestApplication/b/course/1
四、資源下載
RestApplication工程項目
轉載于:https://my.oschina.net/jiyayun/blog/146444
總結
以上是生活随笔為你收集整理的RESTLET开发实例(二)使用Component、Application的REST服务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【C/C++】C语言复习笔记-17种小算
- 下一篇: windows 远程登录用户管理