上一篇文章,我们介绍了基于JAX-RS的REST服务,本篇文章我们介绍不基于JAX-RS的模式。JAX-RS其实就是一个简单的 Application服务。和我们接下来介绍的Application基本一致,唯一不同的地方就是,不使用JAX-RS自动映射为xml。 restlet的一些基本概念可以参考上篇文章 RESTLET开发实例(一)基于JAX-RS的REST服务 的介绍,这里不再阐述。

一、基于ServerResource的REST,来实现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的区别就是少了@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());

}

}

上面的代码实现的功能和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、完成了上面的主要类得创建和编写,你就可以在tomcat中运行了,启动tomcat后,访问http://localhost:8085/RestApplication/student/1,你将看到下面界面:

二、实现更新、删除、添加(delete,put,post)及列表展示

1、上面的介绍,我们实现将JAX-RS中的get方法,用ServerResource方式的来实现。根据rest规范,对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类,加入如下代码,执行成功返回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的规范,包含了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类中加入下面代码,执行成功后返回新添加的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

我们已经实现了一个student的application。里面包含了2个资源类(StudentResource和 StudentsResource)。如果我们加入一个course的资源类,我们可以按照上面的方式直接建立CourseResource,然后在 RestSimpleApplication中绑定下 router.attach("/course/{courseId}", CourseResource.class)。不过这样处理会把业务逻辑混在一起,并不是很好的方法。因此我们建立一个 RestCourseApplication,然后在这里绑定CourseResource类,来实现业务逻辑的分离。

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);

}

}

现在我们有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类,代码如下,因为必须执行路径,所以在访问的时候记得要带上对应的前缀。

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工程项目

[转贴]JAVA:RESTLET开发实例(二)使用Component、Application的REST服务的更多相关文章

  1. [转贴]JAVA :RESTLET开发实例(一)基于JAX-RS的REST服务

    RESTLET介绍 Restlet项目为“建立REST概念与Java类之间的映射”提供了一个轻量级而全面的框架.它可用于实现任何种类的REST式系统,而不仅仅是REST式Web服务. Restlet项 ...

  2. [转贴]JAVA:RESTLET开发实例(三)基于spring的REST服务

    前面两篇文章,我们介绍了基于JAX-RS的REST服务以及Application的Rest服务.这里将介绍restlet如何整合spring框架进行开发.Spring 是一个开源框架,是为了解决企业应 ...

  3. RESTLET开发实例(一)基于JAX-RS的REST服务

    RESTLET介绍 Restlet项目为“建立REST概念与Java类之间的映射”提供了一个轻量级而全面的框架.它可用于实现任何种类的REST式系统,而不仅仅是REST式Web服务. Restlet项 ...

  4. RESTLET开发实例(三)基于spring的REST服务

    http://www.lifeba.org/arch/restlet_spring_3.html 前面两篇文章,我们介绍了基于JAX-RS的REST服务以及Application的Rest服务.这里将 ...

  5. NDK 开发实例二(添加 Eigen库)

    上一篇,我已经阐述了如何创建一个简单的NDK实例: NDK 开发实例一(Android.mk环境配置下) 在上一篇的基础上,我们来添加Eigen库,然后做一个简单实例. Eigen是一个高层次的C + ...

  6. RESTLET开发实例

    1 前提 由于近期工作的需要,要把RESTLET应用到项目中,于是在网上参考了一些资料的基础上,实践了一个关于RESTLET接口的小例子. Restlet的思想是:HTTP客户端与HTTP服务器之间的 ...

  7. 【温故知新】Java web 开发(二)Servlet 和 简单JSP

    系列一介绍了新建一个 web 项目的基本步骤,系列二就准备介绍下基本的 jsp 和  servlet 使用. (关于jsp的编译指令.动作指令.内置对象不在本文讨论范围之内) 1. 首先,在 pom. ...

  8. java web开发入门二(struts)基于eclispe

    JavaBean JavaBean,  咖啡豆. JavaBean是一种开发规范,可以说是一种技术. JavaBean就是一个普通的java类.只有符合以下规定才能称之为javabean: 1)必须提 ...

  9. Spring Boot 使用IntelliJ IDEA创建一个web开发实例(二)

    1. 创建一个Controller类 package com.example.demo; import org.springframework.web.bind.annotation.RequestM ...

随机推荐

  1. 万网免费主机wordpress快速建站教程-wordpress下载及安装

    进入wordpress官网(http://cn.wordpress.org)下载最新的wordpress安装程序,下载完成后解压到任意电脑目录. 解压完毕后,使用FTP管理工具上传安装文件至主机htd ...

  2. ASP.NET Identity 用户注册相关设定

    此部分可以在 Web项目中的App_Start目录下的 IdentityConfig.cs 文件进行设置. 1.配置密码的验证逻辑 manager.PasswordValidator = new Pa ...

  3. maven是什么?(转自oracle官网)

    Maven 是一个项目管理和构建自动化工具.但是对于我们程序员来说,我们最关心的是它的项目构建功能.所以这里我们介绍的就是怎样用 maven 来满足我们项目的日常需要.Maven 使用惯例优于配置的原 ...

  4. mysql merge表介绍

    在Mysql数据库中,Mysql Merge表有点类似于视图.下面就让我们来一起了解一下Mysql Merge表都有哪些优点,希望对您能有所帮助. Mysql Merge表的优点: A: 分离静态的和 ...

  5. C#&JQuery非缓存式无刷新临时存储数据之仿购物车功能

    感谢广大博问博友的帮助和共同研究讨论,终于实现了一个无缓存无刷新仿购物车的小功能: 一.实现效果简述: 有一种列表,是由双层Repeater嵌套,第一层用来显示类别,第二层用来显示类别下的商品数据, ...

  6. 自动生成get,set方法

    引发的问题: Action中有一个属性名字叫private boolean isHideNumber 用struts2的<s:if test ="isHideNumber"& ...

  7. linux/windows系统oracle数据库简单冷备同步

    linux/windows系统oracle数据库简单冷备同步 我们有一个财务系统比较看重财务数据的安全性,同时我们拥有两套系统,一个生产环境(linux),一个应急备份环境(windows).备份环境 ...

  8. 获取键盘输入或者USB扫描枪数据

    /// <summary> /// 获取键盘输入或者USB扫描枪数据 可以是没有焦点 应为使用的是全局钩子 /// USB扫描枪 是模拟键盘按下 /// 这里主要处理扫描枪的值,手动输入的 ...

  9. SDL实现按钮

    是的,按钮控件很常见,几乎在每一个Windows窗体内都能找到它的身影.SDL作为一套“一套开放源代码的跨平台多媒体开发库”,自然可以实现按钮.而按钮实现的重点,就是SDL的鼠标响应事件. SDL的鼠 ...

  10. datagrid合并行列--并不能影响序号列内容...(formatter的锅.)

    datagrid合并行列 //datagrid组件. $('#id_dailylist_dg').datagrid({ //url:'datagrid_data.json', columns:[[ { ...