我正在尝试将一个简单的字符串从 HTML 表单发送到基于 spring 的 REST Web 服务,但即使经过多次尝试,我也无法将数据发送到我的 web 服务,每次我收到“The request sent by the客户端语法不正确”(400) 错误。有人可以查看代码片段并让我知道我错过了什么吗?
<form action="http://localhost:8080/SpringRest/rest/store/prolist" method="GET">
<p>
Products : <input type="text" name="listofproducts" id = "listofproducts"/>
</p>
<input type="submit" value="Get the Lowest Price" />
</form>
Controller 中的代码:
@RequestMapping(value = "http://localhost:8080/SpringRest/rest/store/prolist/{listofproducts}", method = RequestMethod.GET)
public @ResponseBody String getListOfProducts(@PathVariable String listofproducts) {
return listofproducts;
}
最佳答案
当使用 GET 发送表单数据时,您必须将其作为请求参数而不是路径变量接收,因为表单数据以以下格式作为请求参数发送到服务器
http://host_port_and_url?name1=value1&name2=value2&more_params
所以这样做
@RequestMapping(value = "http://localhost:8080/SpringRest/rest/store/prolist", method = RequestMethod.GET)
public @ResponseBody String getListOfProducts(@RequestParam(value = "listofproducts") String listofproducts) {
return listofproducts;
}
您可以查看this出
Notes on GET:
Appends form-data into the URL in name/value pairs The length of a URL is limited (about 3000 characters) Never use GET to send sensitive data! (will be visible in the URL) Useful for form submissions where a user want to bookmark the result GET is better for non-secure data, like query strings in Google
而且您也不需要与主机、端口等进行绝对 URI 映射。只需使用 Controller 映射即可。假设 store
是 Controller 上下文路径,这就足够了
@RequestMapping(value = "store/prolist", method = RequestMethod.GET)
关于java - 将 HTML 表单数据发送到 Spring REST Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29640084/