Restlet - 使用Restlet自身元件Application/Component的開發例項

襲冷發表於2014-03-31
一、示例說明
    版本:Restlet版本為2.1.0。
    相關:例項是使用Restlet自身的Application和Component元件。

二、建立Java Web工程,新增相關Jar。例項中工程名為RestletService

    


三、建立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 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;
	}
}

五、建立對應的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);
	}
}
六、擴充套件org.restlet.Application類

public class StudentApplication extends Application {
	/**
	 * 重寫createInboundRoot通過attach方法繫結資源類,並且制定了訪問路徑
	 */
	@Override
	public Restlet createInboundRoot() {
		Router router = newRouter(getContext());
		router.attach("/student/{studentId}", StudentResource.class);
		router.attach("/student", StudentListResource.class);
		return router;
	}
}
七、配置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>
八、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的使用示例。

九、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


 

相關文章