from the Spring documentation I took the following:
public @interface RequestParam
Annotation which indicates that a method parameter should be bound to a web request parameter. Supported for annotated handler methods in Servlet and Portlet environments.
...
If the method parameter is Map or MultiValueMap and a parameter name is not specified, then the map parameter is populated with all request parameter names and values.
Now I have created a controller for test purposes. It has a GET and a POST method and each uses a @RequestParam java.util.Map as only parameter. In the method body I am only trying to print the size of the map. When I send requests (GET/POST) only in the GET method the map contains any key/value pairs. I am using the Poster add-on in Firefox and I am sending three parameters.
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class TestController {
@RequestMapping(value="test/method", method = RequestMethod.GET)
@ResponseBody
public String testmethodGet(@RequestParam Map<String, String> params) {
System.out.println("GET: " + params.size()); // prints GET: 3
return "";
}
@RequestMapping(value="test/method", method = RequestMethod.POST)
@ResponseBody
public String testmethodPost(@RequestParam Map<String, String> params) {
System.out.println("POST: " + params.size()); // prints POST: 0
return "";
}
}
Would any of you guys know why @RequestParam Map would not work with a POST request or whether I need to change something to make it work?
Thanks.
Actually, it works on GET and POST method. It was solely my fault. The initially given code will work, when you actually pass parameters to the POST request.
Consider the following JS ( jQuery ) code as how to send a valid request:
$.ajax({
type: "POST",
url: "test/method",
data: { param1: param1, param2: param2, param3: param3 },
success: function(data) {
console.log("testPost successful!");
},
dataType: "html", // expected return value type
error: function(data, status, error) {
console.log("testPost with errors!");
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With