Restlet - 基于JAX-RS的Restlet开发实例

来源:互联网 发布:香薰加湿器怎么用 知乎 编辑:程序博客网 时间:2024/04/29 07:02
一、示例说明
    版本:Restlet版本为2.1.0。
    另外:这个应该是才开始接触级别的示例,刚学者可以作为借鉴看看,大神请深藏您的功与名。

二、关于Restlet
    1、官网:http://restlet.org/
    2、原则:为所有“事物”即资源定义ID;将所有事物链接在一起;使用标准方法,即CRUD;资源多重表述;无状态通信。具体描述谷歌搜索。

三、创建Java Web工程,添加相关Jar。文中示例工程名为JAXRSRestlet

    

四、创建Model,示例为Student

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

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

public class StudentBO {private static Map<Integer, Student> students = new HashMap<Integer, Student>();// next Idprivate 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;}}
六、创建对应的Resource类,具体看注释

//student路径进来的都会调用StudentResource来处理@Path("student")public class StudentResource {StudentBO studentBO = new StudentBO();// 说明了http的方法是get方法@GET// 每个方法前都有对应path,用来申明对应uri路径@Path("{id}/xml")// 指定返回的数据格式为xml@Produces("application/xml")// 接受传递进来的id值,其中id为Path中的{id},注意定义的占位符与@PathParam要一致public Student getStudentXml(@PathParam("id") int id) {return studentBO.getStudent(id);}@GET@Path("{id}/json")@Produces("application/json")public Student getStudentJson(@PathParam("id") int id) {return studentBO.getStudent(id);}@POST@Path("post")public String addStudent(Representation entity) {Form form = new Form(entity);String name = form.getFirstValue("name");int sex = Integer.parseInt(form.getFirstValue("sex"));int age = Integer.parseInt(form.getFirstValue("age"));Student student = new Student();student.setName(name);student.setSex(sex);student.setAge(age);int i = studentBO.saveOrUpdateStudent(student);return i + "";}@PUT@Path("put")public String updateStudent(Representation entity) {Form form = new Form(entity);int id = Integer.parseInt(form.getFirstValue("id"));String name = form.getFirstValue("name");int sex = Integer.parseInt(form.getFirstValue("sex"));int age = Integer.parseInt(form.getFirstValue("age"));Student student = new Student();student.setId(id);student.setName(name);student.setSex(sex);student.setAge(age);int i = studentBO.saveOrUpdateStudent(student);return i + "";}}
七、扩展javax.ws.rs.core.Application类

public class StudentApplication extends Application {@Overridepublic Set<Class<?>> getClasses() {Set<Class<?>> rrcs = new HashSet<Class<?>>();// 绑定StudentResource。有多个资源可以在这里绑定。rrcs.add(StudentResource.class);return rrcs;}}
八、扩展org.restlet.ext.jaxrs.JaxRsApplication类

public class RestJaxRsApplication extends JaxRsApplication {public RestJaxRsApplication(Context context) {super(context);// 将StudentApplication加入了运行环境中,如果有多个Application可以在此绑定this.add(new StudentApplication());}}
九、web.xml配置

<context-param><param-name>org.restlet.application</param-name><param-value>app.RestJaxRsApplication</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>
十、Client端测试

/** * 示例使用了Junit,不用可以写Main方法 */public class Client {public static String url = "http://127.0.0.1:8080/JAXRSRestlet/";@Testpublic void testGetXml() {ClientResource client = new ClientResource(url + "student/1/xml");try {System.out.println(client.get().getText());} catch (ResourceException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}@Testpublic void testGetJson() {ClientResource client = new ClientResource(url + "student/1/json");try {System.out.println(client.get().getText());} catch (ResourceException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}@Testpublic void testPost() {ClientResource client = new ClientResource(url + "student/post");try {Form form = new Form();form.add("name", "testPost");form.add("age", "0");form.add("sex", "39");String id = client.post(form.getWebRepresentation()).getText();System.out.println(id);} catch (Exception e) {e.printStackTrace();}}@Testpublic void testPut() {ClientResource client = new ClientResource(url + "student/put");try {Form form = new Form();form.add("id", "1");form.add("name", "testPut");form.add("age", "22");form.add("sex", "0");String id = client.put(form.getWebRepresentation()).getText();System.out.println(id);} catch (Exception e) {e.printStackTrace();}}@Testpublic void testDelete() {ClientResource client = new ClientResource(url + "student/1");try {System.out.println(client.delete().getText());} catch (ResourceException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}
十一、输出结果
   (1)、testGetXml():
        <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
        <Student><age>18</age><id>1</id><name>Michael</name><sex>1</sex></Student>
   (2)、testGetJson:
        {"id":1,"sex":1,"age":18,"name":"Michael"}
   (3)、testPut():1
      再调用testGetJson()传入{id}=1时:{"id":1,"sex":0,"age":22,"name":"testPut"}
   (4)、testPost():5
      再调用testGetJson()传入{id}=5时:{"id":5,"sex":39,"age":0,"name":"testPost"}
 
 
 

0 0