Restlet实战(七)-提交和处理Web Form

本节演示如何使用Restlet通过提交Web Form来创建一个Customer。

 

首先创建一个customer.jsp作为测试form提交文件

Java代码   收藏代码
  1. <html>  
  2. <head>  
  3.   
  4. <script>  
  5.     function doSubmit(){  
  6.         document.forms[0].submit();  
  7.     }  
  8. </script>  
  9.   
  10. </head>  
  11.   
  12. <body>  
  13.   
  14. <form name="form1" action="<%=request.getContextPath()%>/resources/customers" method="post">  
  15.     Name:<input type="text" name="name"/><br>  
  16.     Address:<input type="text" name="address"/><br>  
  17.     <input type="button" value="Submit" onclick="doSubmit()"/>  
  18. </form>  
  19. </body>  
  20. </html>  

 

上篇文章提到,如果要创建一个Customer,URL应该是:/customers,对应的资源是CustomersResources。

 

CustomersResources已经有处理接收Form提交的代码,故不需要做任何修改,见上篇文章。

 

下面就测试这个功能,启动Web server,运行customer.jsp,在显示的页面上填写上Name和Address两栏,然后提交当前的form,一个错误的页面出现了,错误信息如下:




 
 这个错误出现是显而易见的,因为form的定义里面我们指定method="post",所以,CustomersResource里面的对应Post的方法应该被调用,而我们的程序里面没有这个方法,那么是否应该指定method="put"呢?因为put对应的是修改,post对应的创建的概念。但显然是不行的,因为form里面的method只支持"get"和"post"两种形式,所以,如果是从Form提交的请求,无论是修改还是创建,都只会访问Post对应的acceptRepresentation方法。。

 

如果form的定义本身不支持,那么我们只能在CustomersResource里面定义与Post对应的方法来充当创建的方法,加入的代码如下:

 

 

Java代码   收藏代码
  1. @Override  
  2. public boolean allowPost() {  
  3.     return true;  
  4. }  
  5.   
  6. @Override  
  7.    public void acceptRepresentation(Representation entity) throws ResourceException {  
  8.     Form form = new Form(entity);  
  9.     Customer customer = new Customer();  
  10.     customer.setName(form.getFirstValue("name"));  
  11.     customer.setAddress(form.getFirstValue("address"));  
  12.     customer.setRemarks("This is an example which receives request with put method and save data");  
  13.       
  14.     customerDAO.saveCustomer(customer);  
  15. }  

 

再次测试,yes, It is ok.

 

 

BTW:说到Form只支持get和post两种方法,对于支持Rest的另外的一个framework-Cetia4来说,由于采用自定义的form标签cetia:form,所以,除了get和post参数外,还可以指定具体的方法名,如:

 

Java代码   收藏代码
  1. <cetia:form method="insertCustomer" action="tasks">  

 

 如果是这种情况,当Cetia4解析tag以后,会认为当前提交的form的method是post,只不过类里面具体的方法是insertCustomer。

猜你喜欢

转载自chenjianfei2016.iteye.com/blog/2355185