java - 将 HTML 表单数据发送到 Spring REST Web 服务

标签 java spring web-services rest

我正在尝试将一个简单的字符串从 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/

相关文章:

java - 如何将多台机器的PATCH http请求同步到单台机器

java - 无法通过Java代码执行Unix命令

java - 使用 Spring Boot 进行集成测试

java - 过滤所有查询的数据

android - 从 Android 应用程序调用 Web 服务的最佳方式

java - 在一个 jcombobox 中进行选择启用不同的 jcombobox

java - Struts2 <filter> 和 <filter-mapping> 导致错误

java - 使用共享主键(双向) hibernate @OneToOne。依赖实体未保留在数据库中。

java - 通过 java webservice 提供数据库访问

java - WSO2 ESB 的用途是什么?