本篇文章将讲解三种不同值的获取方法。
1.从Web Form中获取值
如果看过此系列文章中的Restlet实战(七)-提交和处理Web Form 对此应该有一定的印象,简单把代码贴过来加深印象:
@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); }
除了上面这样的方式获取Web Form外,实际上Web Form是POST 请求送到服务器的实体,所以也可以从Request中获得,我们对上述类做一修改。
@Override public void init(Context context, Request request, Response response) { super.init(context, request, response); Form form = request.getEntityAsForm(); Customer customer = new Customer(); customer.setName(form.getFirstValue("name")); customer.setAddress(form.getFirstValue("address")); }
从方法调用顺序上讲,init方法调用在前,acceptRepresentation方法调用在后,有意思的是,如果这两个方法里面都有拦截取Form的代码,那么Restlet将抛出一个异常,内容如下:
java.lang.IllegalStateException: The Web form cannot be parsed as no fresh content is available. If this entity has been already read once, caching of the entity is required
意思是Form已经被分析过一次,如果想再次用,建议cache这个form,呵呵,有意思。
2. 从查询中获取值
对Restlet实战(七)-提交和处理Web Form 中的index.jsp做一个简单的修改:
<form name="form1" action="<%=request.getContextPath()%>/resources/customers?query=test" method="post"> Name:<input type="text" name="name"/><br> Address:<input type="text" name="address"/><br> <input type="button" value="Submit" onclick="doSubmit()"/> </form>
在/resources/customers后面加了?query=test,修改CustomersResource的init方法来获取查询值:
@Override public void init(Context context, Request request, Response response) { super.init(context, request, response); Form form = request.getResourceRef().getQueryAsForm(); for (Parameter parameter : form) { System.out.print("parameter " + parameter.getName()); System.out.println("/" + parameter.getValue()); } }
方法我们不作过多的处理,只是验证是否能获取到值。
3. 从Cookie中获取值
cookie能直接从request中获得,返回的是一个cookie的对象集合,同上,在init方法里面添加如下代码:
for (Cookie cookie : request.getCookies()) { System.out.println("name = " + cookie.getName()); System.out.println("value = " + cookie.getValue()); System.out.println("domain = " + cookie.getDomain()); System.out.println("path = " + cookie.getPath()); System.out.println("version = " + cookie.getVersion()); }