How to explicitly get post data in Spring MVC?

Is there any way to get message data? I know spring handles post data binding with java objects. But, given the two fields that I want to process, how can I get this data?

For example, suppose my form had two fields:

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

How can I get these values ​​in my controller?

+50
java spring-mvc
Mar 22 '10 at 18:32
source share
3 answers

If you use one of the built-in controller instances, then one of the parameters of your controller method will be the Request object. You can call request.getParameter("value1") to get the value of the Post data.

If you use Spring MVC annotations, you can add an annotated parameter to your method parameters:

 @RequestMapping(value = "/someUrl") public String someMethod(@RequestParam("value1") String valueOne) { //do stuff with valueOne variable here } 
+94
Mar 22 '10 at 18:37
source share

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"); 

HttpServletRequest should already be available to you inside Spring MVC as one of the arguments to the handleRequest() method method.

+23
Mar 22 '10 at 18:36
source share

Another answer to the exact OP question is to set the content type of consumes to "text/plain" and then declare the input parameter @RequestBody String . This will pass the text of the POST data in the declared variable String ( postPayload in the following example).

Of course, this assumes that your POST payload is text data (as specified in the OP).

Example:

  @RequestMapping(value = "/your/url/here", method = RequestMethod.POST, consumes = "text/plain") public ModelAndView someMethod(@RequestBody String postPayload) { // ... } 
+21
Jul 30 '14 at 17:24
source share



All Articles