How to explicitly obtain post data in Spring MVC?

JavaSpring Mvc

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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
}

Solution 2 - Java

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) {    
		// ...    
	}

Solution 3 - Java

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.

Solution 4 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser130532View Question on Stackoverflow
Solution 1 - JavaJacob MattisonView Answer on Stackoverflow
Solution 2 - JavasimonView Answer on Stackoverflow
Solution 3 - JavaBalusCView Answer on Stackoverflow
Solution 4 - JavaSuisseView Answer on Stackoverflow