Java 如何在 Spring MVC 中显式获取发布数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2494774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to explicitly obtain post data in Spring MVC?
提问by
Is there a way to obtain the post data itself? I know spring handles binding post data to java objects. But, given two fields that I want to process, how can I obtain that data?
有没有办法获取post数据本身?我知道 spring 处理将 post 数据绑定到 java 对象。但是,鉴于我要处理的两个字段,我如何获取该数据?
For example, suppose my form had two fields:
例如,假设我的表单有两个字段:
<input type="text" name="value1" id="value1"/>
<input type="text" name="value2" id="value2"/>
How would I go about retrieving those values in my controller?
我将如何在我的控制器中检索这些值?
采纳答案by Jacob Mattison
If you are using one of the built-in controller instances, then one of the parameters to your controller method will be the Request object. You can call request.getParameter("value1")
to get the POST (or PUT) data value.
如果您使用内置控制器实例之一,则控制器方法的参数之一将是 Request 对象。您可以调用request.getParameter("value1")
以获取 POST(或 PUT)数据值。
If you are using Spring MVC annotations, you can add an annotated parameter to your method's parameters:
如果您使用的是 Spring MVC 注释,则可以在方法的参数中添加一个带注释的参数:
@RequestMapping(value = "/someUrl")
public String someMethod(@RequestParam("value1") String valueOne) {
//do stuff with valueOne variable here
}
回答by BalusC
Spring MVC runs on top of the Servlet API. So, you can use HttpServletRequest#getParameter()
for this:
Spring MVC 运行在 Servlet API 之上。因此,您可以HttpServletRequest#getParameter()
为此使用:
String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");
The HttpServletRequest
should already be available to you inside Spring MVC as one of the method arguments of the handleRequest()
method.
在HttpServletRequest
Spring MVC的内部应该已经提供给您的方法参数的一个handleRequest()
方法。
回答by simon
Another answer to the OP's exact question is to set the consumes
content type to "text/plain"
and then declare a @RequestBody String
input parameter. This will pass the text of the POST data in as the declared String
variable (postPayload
in the following example).
OP 确切问题的另一个答案是将consumes
内容类型设置为"text/plain"
然后声明一个@RequestBody String
输入参数。这会将 POST 数据的文本作为声明的String
变量传入(postPayload
在以下示例中)。
Of course, this presumes your POST payload is text data (as the OP stated was the case).
当然,这假设您的 POST 有效负载是文本数据(正如 OP 所述)。
Example:
例子:
@RequestMapping(value = "/your/url/here", method = RequestMethod.POST, consumes = "text/plain")
public ModelAndView someMethod(@RequestBody String postPayload) {
// ...
}