[java] How to explicitly obtain post data in Spring MVC?

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?

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?

This question is related to java spring-mvc

The answer is


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.


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