本节演示如何使用Restlet通过提交Web Form来创建一个Customer。
首先创建一个customer.jsp作为测试form提交文件
- <html>
- <head>
- <script>
- function doSubmit(){
- document.forms[0].submit();
- }
- </script>
- </head>
- <body>
- <form name="form1" action="<%=request.getContextPath()%>/resources/customers" method="post">
- Name:<input type="text" name="name"/><br>
- Address:<input type="text" name="address"/><br>
- <input type="button" value="Submit" onclick="doSubmit()"/>
- </form>
- </body>
- </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对应的方法来充当创建的方法,加入的代码如下:
- @Override
- public boolean allowPost() {
- return true;
- }
- @Override
- public void acceptRepresentation(Representation entity) throws ResourceException {
- Form form = new Form(entity);
- Customer customer = new Customer();
- customer.setName(form.getFirstValue("name"));
- customer.setAddress(form.getFirstValue("address"));
- customer.setRemarks("This is an example which receives request with put method and save data");
- customerDAO.saveCustomer(customer);
- }
再次测试,yes, It is ok.
BTW:说到Form只支持get和post两种方法,对于支持Rest的另外的一个framework-Cetia4来说,由于采用自定义的form标签cetia:form,所以,除了get和post参数外,还可以指定具体的方法名,如:
- <cetia:form method="insertCustomer" action="tasks">
如果是这种情况,当Cetia4解析tag以后,会认为当前提交的form的method是post,只不过类里面具体的方法是insertCustomer。