2015-09-27 70 views
2

我有一个html form,我需要提交到restlet。似乎很简单,但形式总是回到空白。发表html to restlet

这是形式:

<form action="/myrestlet" method="post"> 
    <input type="text" size=50 value=5/> 
    <input type="text" size=50 value=C:\Temp/> 
    (and a few other input type texts) 
</form> 

restlet

@Post 
public Representation post(Representation representation) { 
    Form form = getRequest().getResourceRef().getQueryAsForm(); 
    System.out.println("form " + form); 
    System.out.println("form size " + form.size()); 
} 

我也试图让表单是这样的:

Form form = new Form(representation); 

但它总是作为[]与大小0.

我错过了什么?

编辑:下面是我使用的解决方法:

String query = getRequest().getEntity().getText(); 

这样将form所有的值。我必须解析它们,这很烦人,但是它完成了这项工作。

+0

请求参数丢失。 –

+0

@RomanC可以详细说明一下吗? – Eddy

+0

不,我不熟悉上面的代码,我只是看到HTML代码中的一些拼写错误。 –

回答

2

以下是从Restlet服务器资源中提交的HTML表单(内容类型为 application/x-www-form-urlencoded)中获取值的正确方法。事实上这是你所做的。

​​

在你的情况下,HTML表单实际上并未发送,因为您的形式并没有定义任何属性name。我用你的HTML代码,发送的数据是空的。您可以使用Chrome开发人员工具(Chrome)或Firebug(Firefox)进行检查。

POST /myrestlet HTTP/1.2 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
Accept-Encoding: gzip, deflate 
Accept-Language: fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3 
Connection: keep-alive 
Host: localhost:8182 
Referer: http://localhost:8182/static/test.html 
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0 
Content-Length: 0 
Content-Type: application/x-www-form-urlencoded 

你应该使用类似的东西为你的HTML表单:

<form action="/test" method="post"> 
    <input type="text" name="val1" size="50" value="5"/> 
    <input type="text" name="val2" size="50" value="C:\Temp"/> 
    (and a few other input type texts) 
    <input type="submit" value="send"> 
</form> 

在这种情况下,请求将是:

POST /myrestlet HTTP/1.2 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
Accept-Encoding: gzip, deflate 
Accept-Language: fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3 
Connection: keep-alive 
Host: localhost:8182 
Referer: http://localhost:8182/static/test.html 
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0 
Content-Length: 23 
Content-Type: application/x-www-form-urlencoded 

val1=5&val2=C%3A%5CTemp 

希望它可以帮助你, 蒂埃里

+0

谢谢,它现在正在工作。为了澄清,我需要为输入字段命名,而不是表单本身。 – Eddy

2

这里实现这个有点简单,它直接声明Form作为参数t他的Java方法:

public class MyServerResource extends ServerResource { 
    @Post 
    public Representation handleForm(Form form) { 

     // The form contains input with names "user" and "password" 
     String user = form.getFirstValue("user"); 
     String password = form.getFirstValue("password"); 

    (...) 
    } 
}