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

拥有回忆 提交于 2019-12-05 12:26:42

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

Spring does not know how to convert a String received as a request param to a map.

String-based values extracted from the request including request parameters, path variables, request headers, and cookie values may need to be converted to the target type of the method parameter or field (e.g., binding a request parameter to a field in an @ModelAttribute parameter) they're bound to. If the target type is not String, Spring automatically converts to the appropriate type. All simple types such as int, long, Date, etc. are supported. You can further customize the conversion process through a WebDataBinder (see the section called “Customizing WebDataBinder initialization”) or by registering Formatters with the FormattingConversionService (see Section 7.6, “Spring 3 Field Formatting”).

Spring does provide support for maps via the HttpServletReqeust which could be used to obtain the map via getParameterMap().

   @RequestMapping(value="test/method", method = RequestMethod.POST)
    @ResponseBody
    public String testmethodPost(HttpServletRequest request) {

        System.out.println("POST: " + request.getParameterMap().size()); // prints POST: 0
        return "";

    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!