1、示例说明

   版本:Restlet版本为2.1.0。

   相关:实例是使用Restlet自身的Application和Component组件。


2、创建Java Web工程,添加相关Jar。实例中工程名为RestletService

211714472.png

3、创建Model,示例为Student

public class Student {
    private Integer id;
    private String name;
    private Integer sex;
    private Integer age;
    public Student() {
    }
        /**setter/getter**/
}


4、创建BusinessObject类,示例虚拟了一个数据库和相应的一些操作

public class StudentBO {
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
    private static Map<Integer, Student> students = new HashMap<Integer, Student>();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
    // next Id
    private static int nextId = 5;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
    static {
        students.put(1, new Student(1, "Michael", 1, 18));
        students.put(2, new Student(2, "Anthony", 1, 22));
        students.put(3, new Student(3, "Isabella", 0, 19));
        students.put(4, new Student(4, "Aiden", 1, 20));
    }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
    public Student getStudent(Integer id) {
        return students.get(id);
    }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
    public List<Student> getStudentAll() {
        return new ArrayList<Student>(students.values());
    }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
    public Integer saveOrUpdateStudent(Student student) {
        if (student.getId() == null) {
            student.setId(nextId++);
        }
        students.put(student.getId(), student);
        return student.getId();
    }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
    public Integer removeStudent(Integer id) {
        students.remove(id);
        return id;
    }
}


5、创建对应的Resource类,具体看注释

   (1)、StudentResource类,主要针对单一查询,修改和删除操作

public class StudentResource extends ServerResource {
    private int id;
    private StudentBO studentService = new StudentBO();
                                                                                                                                                                                                                                                                                                                                                                                                      
    /**
     * 用来获取传递过来的studentId占位符的值
     */
    @Override
    protected void doInit() throws ResourceException {
        id = Integer.valueOf((String) getRequestAttributes().get("studentId"));
    }
                                                                                                                                                                                                                                                                                                                                                                                                      
    @Get("json")
    public Student getStudent(){
        return studentService.getStudent(id);
    }
                                                                                                                                                                                                                                                                                                                                                                                                      
    @Delete
    public Integer deleteStudent() {
        return studentService.removeStudent(id);
    }
                                                                                                                                                                                                                                                                                                                                                                                                         
    @Put("json")
    public Integer updateStudent(Student student){  
        student.setId(id);
        return studentService.saveOrUpdateStudent(student); 
    }
                                                                                                                                                                                                                                                                                                                                                                                                         
    /*
     * 第二种传入参数和返回值的方式
     * @Put
     * public Representation put(Representation entity) throws ResourceException {
     *    //entity这样一个对象将会把客户端传进来参数保存在其中,通过如下方式可以获取参数值
     *    Form form = new Form(entity);
     *    Student student = new Student();
     *    String name = form.getFirstValue("name");
     *    int sex = Integer.parseInt(form.getFirstValue("sex"));
     *    int age = Integer.parseInt(form.getFirstValue("age"));
     *    student.setName(name);
     *    student.setSex(sex);
     *    student.setAge(age);
     *    student.setId(id);
     *    studentService.saveOrUpdateStudent(student);
     *    //实例返回的是String类型的扩展,当然你也可以返回JsonRepresentation这样一个扩展
     *    return new StringRepresentation(student.toString()); //为了更好的说明返回整个对象
     *
     * }
     */
                                                                                                                                                                                                                                                                                                                                                                                                      
}


   (2)、StudentListResource类,主要针对多返回查询和新增操作

public class StudentListResource extends ServerResource {
    private StudentBO studentService = new StudentBO();
                                                                                                                                                                                                                                                                                                                                                                             
    @Get("json")
    public List<Student> get(Representation entity) {
        List<Student> studentList = studentService.getStudentAll();
        return studentList;
    }
                                                                                                                                                                                                                                                                                                                                                                             
    @Post("json")
    public Integer saveStudent(Student student) {
        return studentService.saveOrUpdateStudent(student);
    }
                                                                                                                                                                                                                                                                                                                                                                             
}


6、扩展org.restlet.Application类

public class StudentApplication extends Application {
                                                                                                                                                                                                                                                                                                                                                                    
    /**
     * 重写createInboundRoot通过attach方法绑定资源类,并且制定了访问路径
     */
    @Override
    public Restlet createInboundRoot() {
        Router router = new Router(getContext());
        router.attach("/student/{studentId}", StudentResource.class);
        router.attach("/student", StudentListResource.class);
        return router;
    }
                                                                                                                                                                                                                                                                                                                                                                    
}


7、配置web.xml

<context-param>
    <param-name>org.restlet.application</param-name>
    <!-- 自定义org.restlet.Application扩展类  -->
    <param-value>com.rc.rl.StudentApplication</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>


8、Test客户端

/**
 *客户端使用了Junit4
 */
public class StudentClient {
                                                                                                                                                                                                                                                                                                                            
    @Test
    public void student_findById() {
        try {
            ClientResource client = new ClientResource(
                    "http://localhost:8080/RestletService/student/1");
            Representation representation = client.get();
            System.out.println(representation.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
                                                                                                                                                                                                                                                                                                                            
    public void student_delete() {
        try {
            ClientResource client = new ClientResource(
                    "http://localhost:8080/RestletService/student/1");
            Representation representation = client.delete();
            System.out.println(representation.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
                                                                                                                                                                                                                                                                                                                            
    @Test
    public void student_put() {
        try {
            Student student = new Student("Test_Put", 0, 23);
            ClientResource client = new ClientResource(
                    "http://localhost:8080/RestletService/student/2");
            Representation representation = client.put(student, MediaType.APPLICATION_JAVA_OBJECT);
            System.out.println(representation.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
                                                                                                                                                                                                                                                                                                                            
    /**
     * StudentResource中第二种传入参数和返回值的方式的客户端调用方式
     */
    @Test
    public void student_put_other() {
        try {
            Form queryForm = new Form();
            queryForm.add("name", "steven4");
            queryForm.add("sex", "2");
            queryForm.add("age", "300");
            ClientResource client = new ClientResource(
                    "http://localhost:8080/RestletService/student/2");
            Representation representation = client.put(queryForm.getWebRepresentation());
            System.out.println(representation.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
                                                                                                                                                                                                                                                                                                                            
    @Test
    public void student_post() {
        try {
            Student student = new Student("Test_Put", 0, 23);
            ClientResource client = new ClientResource(
                    "http://localhost:8080/RestletService/student");
            Representation representation = client.post(student, MediaType.APPLICATION_JAVA_OBJECT);
            System.out.println(representation.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
                                                                                                                                                                                                                                                                                                                            
    @Test
    public void student_getAll() {
        try {
            ClientResource client = new ClientResource(
                    "http://localhost:8080/RestletService/student");
            Representation representation = client.get();
            System.out.println(representation.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
                                                                                                                                                                                                                                                                                                                            
}


说明:以上的org.restlet.Application的使用示例。


9、org.restlet.Component的使用

   在上面的实例中,如果需要加入Teacher等更多资源时,或许为了业务逻辑的分离,就不能再把TeacherResource也在StudentApplication中进行绑定。


   解决办法是如同上面所示建立Teacher相关的Resource和针对Teacher的org.restlet.Application扩展,然后扩展org.restlet.Component如下:

public class RestSimpleComponent extends Component {
                                                                                                                               
    public RestSimpleComponent() {
        getDefaultHost().attach("/stu",new StudentApplication());
        getDefaultHost().attach("/tea",new TeacherApplication());
    }
                                                                                                                               
}


   再修改web.xml中<context-param/>如下:

<context-param>
    <!-- <param-name>org.restlet.application</param-name>
    <param-value>com.rc.rl.RestSimpleApplication</param-value> -->
    <param-name>org.restlet.component</param-name>
    <param-value>com.rc.rl.RestSimpleComponent</param-value>
</context-param>


   注意:通过如上配置之后,访问的URI需要加上Component中添加的路径,如之前的 http://localhost:8080/RestletService/student/1将变更http://localhost:8080/RestletService/stu/student/1