Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @RequestParam Map<String, String> does not work in POST method

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.

like image 758
abedurftig Avatar asked Dec 27 '22 03:12

abedurftig


1 Answers

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!");
    }
});
like image 100
abedurftig Avatar answered Jan 14 '23 07:01

abedurftig