示例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?


当前回答

Edit

有人指出,存在一种纯Spring MVC机制(至少在3.0版本),通过这种机制可以获取这些数据。我不会在这里详细说明,因为这是另一个用户的答案。详情请看@AdamGent的回答,别忘了给它投票。

在Spring 3.2文档中,RequestMapping JavaDoc页面和RequestParam JavaDoc页面都提到了这种机制,但在此之前,它只在RequestMapping页面中提到。在2.5的文档中没有提到这种机制。

对于大多数开发人员来说,这可能是首选的方法,因为它删除了(至少这个)到servlet-api jar所定义的HttpServletRequest对象的绑定。

/编辑

你应该可以通过request.getQueryString()访问请求查询字符串。

除了getQueryString,查询参数还可以作为Map从request.getParameterMap()中检索。

其他回答

你可以简单地使用这个:

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

应该没问题

下面是一个在Map中获取requestParams的简单例子:

@RequestMapping(value="submitForm.html", method=RequestMethod.POST)
public ModelAndView submitForm(@RequestParam Map<String, String> reqParam) {
    String name  = reqParam.get("studentName");
    String email = reqParam.get("studentEmail");     
    ModelAndView model = new ModelAndView("AdmissionSuccess");
    model.addObject("msg", "Details submitted by you::Name: " + name
                                                + ", Email: " + email );
}

在这种情况下,它将绑定值:

带name的studentName studentEmail与email

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

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

我可能会迟到, 但据我所知,你要找的是这样的东西

for(String params : Collections.list(httpServletRequest.getParameterNames())) {
    // Whatever you want to do with your map
    // Key : params
    // Value : httpServletRequest.getParameter(params)                
}
@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中。