Map as @RequestParam in Spring MVC

2019-09-05 18:02发布

问题:

I'm new to spring and I'm trying to add a @RequestParam of type Map<String, String> to my controller like this:

@RequestMapping(method = RequestMethod.GET)
public Model search(@RequestParam(value = "searchTerm", required = false) final String searchTerm,
        @RequestParam(value = "filters", required = false) Map<String, String> filters,
        final Model model) {

And in the URL it looks like this:

localhost/search?searchTerm=factory&filters[name]=factory1&filters[name]=factory2

But every time, filters is null, no matter what I do.

Can this be done? Thank you very much for your time!

回答1:

Using Map with @RequestParam for multiple params If the method parameter is Map or MultiValueMap then the map is populated with all query string names and values. Following will be mapped with /employees/234/messages?sendBy=mgr&date=20160210

@RequestMapping("{id}/messages")
public String handleEmployeeMessagesRequest (@PathVariable("id") String employeeId,
                                        @RequestParam Map<String, String> queryMap,
                                        Model model) {
    model.addAttribute("msg", "employee request by id and query map : "+
              employeeId+", "+queryMap.toString());
    return "my-page";
}

Where employeeId = "234" and queryMap = {sendBy=mgr, date=20160210}



标签: spring-mvc