示例URL:

../search/?attr1=value1&attr2=value2&attr4=value4

我不知道attr1、att2和attr4的名称。

我希望能够做这样的事情(或类似的,不关心,只要我可以访问请求参数名称->值的映射:

@RequestMapping(value = "/search/{parameters}", method = RequestMethod.GET)
public void search(HttpServletRequest request, 
@PathVariable Map<String,String> allRequestParams, ModelMap model)
throws Exception {//TODO: implement}

我如何实现这与Spring MVC?


当前回答

@SuppressWarnings("unchecked")
Map<String,String[]> requestMapper=request.getParameterMap();
JsonObject jsonObject=new JsonObject();
for(String key:requestMapper.keySet()){
    jsonObject.addProperty(key, requestMapper.get(key)[0]);
}

所有参数将存储在jsonObject中。

其他回答

你可以简单地使用这个:

Map<String, String[]> parameters = request.getParameterMap();

应该没问题

在你的控制器方法中使用org.springframework.web.context.request.WebRequest作为参数,它提供了getParameterMap()方法,好处是你不用把你的应用程序绑定到Servlet API, WebRequest是JavaEE模式上下文对象的一个例子。

@SuppressWarnings("unchecked")
Map<String,String[]> requestMapper=request.getParameterMap();
JsonObject jsonObject=new JsonObject();
for(String key:requestMapper.keySet()){
    jsonObject.addProperty(key, requestMapper.get(key)[0]);
}

所有参数将存储在jsonObject中。

有两个接口

org.springframework.web.context.request.WebRequest org.springframework.web.context.request.NativeWebRequest

允许通用请求参数访问以及请求/会话属性访问,而不需要绑定到本机Servlet/Portlet API。

Ex.:

@RequestMapping(value = "/", method = GET)
public List<T> getAll(WebRequest webRequest){
    Map<String, String[]> params = webRequest.getParameterMap();
    //...
}

附注:有一些文档是关于可以用作控制器参数的参数的。

虽然其他答案是正确的,但它肯定不是直接使用HttpServletRequest对象的“Spring方式”。答案实际上很简单,如果您熟悉Spring MVC,您就会知道这一点。

@RequestMapping(value = {"/search/", "/search"}, method = RequestMethod.GET)
public String search(
@RequestParam Map<String,String> allRequestParams, ModelMap model) {
   return "viewName";
}