一、相關說明java
version:文中示例使用的Spring版本爲3.0.3,Restlet版本爲2.1.0。node
entity:Studentweb
二、建立Java Web工程,添加相關Jar。文中示例工程名爲SpringRestlet。spring
說明:動態代理的cglib-nodep.jar不可缺乏。json
三、web.xml配置app
<servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/applicationContext.xml</param-value> </init-param> </servlet> <!--Spring ApplicationContext load --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring,avoid leaking memory --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <!-- restlet servlet --> <servlet> <servlet-name>restlet</servlet-name> <servlet-class>org.restlet.ext.spring.SpringServerServlet</servlet-class> <init-param> <param-name>org.restlet.application</param-name> <param-value>application</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>restlet</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
四、Model實體類代碼ide
@JsonSerialize(include = Inclusion.NON_NULL) publicclassStudent { privateInteger id; privateString name; privateInteger sex; privateInteger age; publicStudent() { } /**setter/getter**/ }
說明:@JsonSerialize
(include = Inclusion.NON_NULL)爲JackSon的註解,做用是返回JSON格式的實體時不返回該實體類值爲Null的Field,如: {"id" : 1,
"name" : null,
"sex" : 1,"age" : 20} 。
工具
五、Resource代碼
post
(1)、StudentResource:示例中主要針對單個實例的Retrieve、Update和Delete。測試
@Controller @Scope("prototype") publicclassStudentResource extendsServerResource{ privateInteger id; @Autowired privateStudentBO studentBO; publicvoidsetStudentBO(StudentBO studentBO) { this.studentBO = studentBO; } @Override protectedvoiddoInit() throwsResourceException { id = Integer.valueOf((String) getRequestAttributes().get("studentId")); } @Get("json") publicStudent findStudentById(){ Student s = this.studentBO.getStudent(id); returns; } @Delete("json") publicInteger deleteStudentById() { returnthis.studentBO.removeStudent(id); } @Put("json") publicInteger updateStudent(Student student) { student.setId(id); returnthis.studentBO.saveOrUpdateStudent(student); } }
(2)、StudentListResource:示例中主要針對單個實例的Create和多個實例的Retrieve。
@Controller @Scope("prototype") publicclassStudentListResource extendsServerResource { @Autowired privateStudentBO studentBO; @Post publicInteger saveStudent(Student student) { returnstudentBO.saveOrUpdateStudent(student); } @Get("json") publicList<Student> findStudentAll() { returnstudentBO.getStudentAll(); } publicvoidsetStudentBO(StudentBO studentBO) { this.studentBO = studentBO; } }
說明:接受Spring管理的Bean,@Scope("prototype")的annotation必需要有,不然會出現正確調用指定方法的問題,用xml配置Bean時也必需要Attribute:scope。
六、BusinessObject代碼
@Service @Scope("prototype") publicclassStudentBO { privatestaticMap<Integer, Student> students = newHashMap<Integer, Student>(); // next Id privatestaticintnextId = 5; static{ students.put(1, newStudent(1, "Michael", 1, 18)); students.put(2, newStudent(2, "Anthony", 1, 22)); students.put(3, newStudent(3, "Isabella", 0, 19)); students.put(4, newStudent(4, "Aiden", 1, 20)); } publicStudent getStudent(Integer id) { returnstudents.get(id); } publicList<Student> getStudentAll() { returnnewArrayList<Student>(students.values()); } publicInteger saveOrUpdateStudent(Student student) { if(student.getId() == null) { student.setId(nextId++); } students.put(student.getId(), student); returnstudent.getId(); } publicInteger removeStudent(Integer id) { students.remove(id); returnid; } }
七、Spring applictionContext.xml配置
<bean name="application"class="org.restlet.Application"> <property name="inboundRoot"> <bean class="org.restlet.ext.spring.SpringRouter"> <constructor-arg ref="application"/> <property name="p_w_uploads"> <map> <entry key="/student/{studentId}"> <bean class="org.restlet.ext.spring.SpringFinder"> <lookup-method name="create"bean="studentResource"/> </bean> </entry> <entry key="/student"> <bean class="org.restlet.ext.spring.SpringFinder"> <lookup-method name="create"bean="studentsResource"/> </bean> </entry> </map> </property> </bean> </property> </bean> <!-- spring annotation --> <context:component-scan base-package="com.xl.sr"/>
說明:該application在web.xml中引用
八、Client代碼
publicclassStudentClient { publicvoidstudent_get(){ try{ ClientResource client = newClientResource( "http://127.0.0.1:8080/SpringRestlet/student/1"); Representation representation = client.get(); System.out.println(representation.getText()); } catch(Exception e) { e.printStackTrace(); } } publicvoidstudent_delete() { try{ ClientResource client = newClientResource( "http://127.0.0.1:8080/SpringRestlet/student/1"); Representation representation = client.delete(); System.out.println(representation.getText()); } catch(Exception e) { e.printStackTrace(); } } publicvoidstudent_put(){ try{ ClientResource client = newClientResource( "http://127.0.0.1:8080/SpringRestlet/student/1"); Student student = newStudent("Test_Put", 1, 18); Representation representation = client.put( student, MediaType.APPLICATION_JAVA_OBJECT); System.out.println(representation.getText()); } catch(Exception e) { e.printStackTrace(); } } publicvoidstudent_post(){ try{ ClientResource client = newClientResource( "http://127.0.0.1:8080/SpringRestlet/student"); Student student = newStudent("Test_Post", 1, 18); Representation representation = client.post( student, MediaType.APPLICATION_JAVA_OBJECT); System.out.println(representation.getText()); } catch(Exception e) { e.printStackTrace(); } } publicvoidstudent_findAll(){ try{ ClientResource client = newClientResource( "http://127.0.0.1:8080/SpringRestlet/student"); Representation representation = client.get(); System.out.println(representation.getText()); } catch(Exception e) { e.printStackTrace(); } } publicstaticvoidmain(String[] args) { StudentClient client = newStudentClient(); client.student_get(); } }
九、補充
(1)、請求參數問題:客戶端發送形如/student/{studentId}的URI請求時,多是還須要攜帶其餘parameter的,參數攜帶形式可如/student/{studentId}?name=John&sex=23;Server端獲取參數時,針對在URI{}內的參數使用getRequest().getAttributes().get("studentId");方式獲取,針對附加參數能夠經過Form form = getRequest().getResourceRef().getQueryAsForm(); String name = form.getValues("name");方式獲取。
(2)、客戶端工具:測試Server端時,若是不想寫Client端code,能夠是WizTools.org的RestClient-ui.jar的小工具,Post和Put請求時的對象能夠以JSON格式添加到Http body中便可。
(3)、相關資源:文中工程以上傳至51cto下載中心,含代碼和Jar包。連接地址: http://down.51cto.com/data/847094