我有一个 html 表单
,我需要提交给 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
的所有值。我必须解析它们,这很烦人,但它完成了工作。
最佳答案
这是从提交的 HTML 表单中获取值的正确方法(内容类型为
application/x-www-form-urlencoded
) 在 ReSTLet 服务器资源中。事实上,这就是您所做的。
public class MyServerResource extends ServerResource {
@Post
public Representation handleForm(Representation entity) {
Form form = new Form(entity);
// The form contains input with names "user" and "password"
String user = form.getFirstValue("user");
String password = form.getFirstValue("password");
(...)
}
}
在您的情况下,实际上并未发送 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
希望对你有帮助, 蒂埃里
关于java - 将 html 表单发布到 reSTLet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32807254/