RESTLET开发实例(二)使用Component、Application的REST服务
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
上一篇文章,我們介紹了基于JAX-RS的REST服務(wù),本篇文章我們介紹不基于JAX-RS的模式。JAX-RS其實(shí)就是一個(gè)簡(jiǎn)單的Application服務(wù)。和我們接下來(lái)介紹的Application基本一致,唯一不同的地方就是,不使用JAX-RS自動(dòng)映射為xml。restlet的一些基本概念可以參考上篇文章?RESTLET開(kāi)發(fā)實(shí)例(一)基于JAX-RS的REST服務(wù)?的介紹,這里不再闡述。
一、基于ServerResource的REST,來(lái)實(shí)現(xiàn)JAX-RS中g(shù)et方法。
1、新建RestApplication Web工程。
然后把相應(yīng)的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對(duì)象。將應(yīng)用程序和資源類綁定在一起,代碼如下:
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個(gè)地方:
1)RestSimpleApplication直接擴(kuò)展了Application對(duì)象,而不是JAX-RS中的JaxRsApplication對(duì)象。
2)重載了createInboundRoot通過(guò)attach方法綁定資源類,并且制定了訪問(wèn)路徑。而JAX-RS中調(diào)用了this.add(new StudentApplication())來(lái)綁定資源類,并且不用指定訪問(wèn)路徑,因?yàn)槭窃谫Y源類中指定。
3、新建Student對(duì)象,代碼如下:和JAX-RS的區(qū)別就是少了@XmlRootElement(name="Student")標(biāo)注。
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類,該類擴(kuò)展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());
}
}
上面的代碼實(shí)現(xiàn)的功能和JAX-RS中的下面的代碼的功能一樣,都是根據(jù)ID來(lái)獲取對(duì)應(yīng)的student信息。
@GET
@Path("{id}/xml")
@Produces("application/xml")
public Student getStudentXml(@PathParam("id") int id) {
return ResourceHelper.findStudent(id);
}
非JAX-RS模式的,擴(kuò)展了ServerResource類,并且重載了doInit()方法用來(lái)獲取傳遞過(guò)來(lái)的studentId占位符的值。因?yàn)闆](méi)有傳遞method方法,默認(rèn)是調(diào)用@Get標(biāo)注的無(wú)參方法,最后返回StringRepresentation對(duì)象(你也可以返回xml或json的Representation對(duì)象)。
JAX-RS的也是類似,不過(guò)他的方法是帶參數(shù),并且返回一個(gè)Student對(duì)象(會(huì)根據(jù)@Produces("application/xml")自動(dòng)封裝xml數(shù)據(jù))。
5、完成了上面的主要類得創(chuàng)建和編寫(xiě),你就可以在tomcat中運(yùn)行了,啟動(dòng)tomcat后,訪問(wèn)http://localhost:8085/RestApplication/student/1,你將看到下面界面:
二、實(shí)現(xiàn)更新、刪除、添加(delete,put,post)及列表展示
1、上面的介紹,我們實(shí)現(xiàn)將JAX-RS中的get方法,用ServerResource方式的來(lái)實(shí)現(xiàn)。根據(jù)rest規(guī)范,對(duì)StudentResource,除了有g(shù)et方法外,還有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、測(cè)試更新和刪除:
1)通過(guò)頁(yè)面修改用戶資料
update.jsp頁(yè)面中加入:
<form action="/RestApplication/student/1?method=put" method="post">
用戶名:<input type="text" name="name"><br>
班級(jí):<input type="text" name="clsId"><br>
性別:<input type="text" name="sex"><br>
<input type="submit" value="提交">
</form>
提交后訪問(wèn),返回1表示修改成功。
訪問(wèn)http://localhost:8085/RestApplication/student/1就會(huì)看到名字已經(jīng)修改了。
2)通過(guò)客戶端刪除用戶資料。新建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();
}
}
這個(gè)時(shí)候訪問(wèn)?http://localhost:8085/RestApplication/student/1?,會(huì)提示錯(cuò)誤。因?yàn)檎也坏竭@個(gè)1的用戶。
3、添加一個(gè)student,及顯示全部student信息
1)StudentResource資源,按照restlet的規(guī)范,包含了get put delete方法。所以添加一個(gè)student及顯示全部student信息我們需要再加入一個(gè)資源類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的訪問(wèn)路徑才可以。
router.attach("/student", StudentsResource.class);
2)首先我們添加一個(gè)id為2的student對(duì)象,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();
}
}
訪問(wèn)http://localhost:8085/RestApplication/student?如下,返回了全部的student資料:
可以看到我們已經(jīng)成功添加了一個(gè)2的student。
三、使用Component綁定多個(gè)Application
我們已經(jīng)實(shí)現(xiàn)了一個(gè)student的application。里面包含了2個(gè)資源類(StudentResource和StudentsResource)。如果我們加入一個(gè)course的資源類,我們可以按照上面的方式直接建立CourseResource,然后在RestSimpleApplication中綁定下 router.attach("/course/{courseId}", CourseResource.class)。不過(guò)這樣處理會(huì)把業(yè)務(wù)邏輯混在一起,并不是很好的方法。因此我們建立一個(gè)RestCourseApplication,然后在這里綁定CourseResource類,來(lái)實(shí)現(xiàn)業(yè)務(wù)邏輯的分離。
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個(gè)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類,代碼如下,因?yàn)楸仨殘?zhí)行路徑,所以在訪問(wèn)的時(shí)候記得要帶上對(duì)應(yīng)的前綴。
public class RestComponent extends org.restlet.Component{
public RestComponent(){
getDefaultHost().attach("/a", new RestSimpleApplication());
getDefaultHost().attach("/b", new RestCourseApplication());
}
}
訪問(wèn):http://localhost:8085/RestApplication/a/student
訪問(wèn):http://localhost:8085/RestApplication/b/course/1
四、資源下載
RestApplication工程項(xiàng)目
轉(zhuǎn)載于:https://my.oschina.net/jiyayun/blog/146444
總結(jié)
以上是生活随笔為你收集整理的RESTLET开发实例(二)使用Component、Application的REST服务的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【C/C++】C语言复习笔记-17种小算
- 下一篇: windows 远程登录用户管理