在 SpringMVC 中如何显式地获取文章数据?

有没有办法获得邮件数据本身?我知道 Spring 处理将帖子数据绑定到 Java 对象。但是,给定我要处理的两个字段,如何获得该数据呢?

例如,假设我的表单有两个字段:

 <input type="text" name="value1" id="value1"/>
<input type="text" name="value2" id="value2"/>

如何在控制器中检索这些值?

187732 次浏览

Spring MVC runs on top of the Servlet API. So, you can use HttpServletRequest#getParameter() for this:

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.

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.

If you are using Spring MVC annotations, you can add an annotated parameter to your method's parameters:

@RequestMapping(value = "/someUrl")
public String someMethod(@RequestParam("value1") String valueOne) {
//do stuff with valueOne variable here
}

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).

Of course, this presumes your POST payload is text data (as the OP stated was the case).

Example:

    @RequestMapping(value = "/your/url/here", method = RequestMethod.POST, consumes = "text/plain")
public ModelAndView someMethod(@RequestBody String postPayload) {
// ...
}

You can simply just pass the attribute you want without any annotations in your controller:

@RequestMapping(value = "/someUrl")
public String someMethod(String valueOne) {
//do stuff with valueOne variable here
}

Works with GET and POST