SpringMVC RequestMapping GET参数

如何使RequestMapping在URL中处理GET参数? 例如,我有这个url

http://localhost:8080/userGrid?_search=false&nd=1351972571018&rows=10&page=1&sidx=id&sord=desc 

(来自jqGrid)

我的RequestMapping应该如何? 我想要使​​用HttpReqest获取参数

试过这个:

 @RequestMapping("/userGrid") public @ResponseBody GridModel getUsersForGrid(HttpServletRequest request) 

但它不起作用。

在你的方法参数中使用@RequestParam ,所以Spring可以绑定它们,也可以使用@ RequestMapping.params数组来缩小Spring将要使用的方法。 示例代码:

 @RequestMapping("/userGrid", params = {"_search", "nd", "rows", "page", "sidx", "sort"}) public @ResponseBody GridModel getUsersForGrid( @RequestParam(value = "_search") String search, @RequestParam(value = "nd") int nd, @RequestParam(value = "rows") int rows, @RequestParam(value = "page") int page, @RequestParam(value = "sidx") int sidx, @RequestParam(value = "sort") Sort sort) { // Stuff here } 

这样,如果所有参数都存在,Spring将只执行这个方法,从而避免了空值检查和相关的事情。

你可以像这样添加@RequestMapping

 @RequestMapping("/userGrid") public @ResponseBody GridModel getUsersForGrid( @RequestParam("_search") String search, @RequestParam String nd, @RequestParam int rows, @RequestParam int page, @RequestParam String sidx) @RequestParam String sord) { 

这将从请求中获取所有参数。 仅用于debugging目的:

 @RequestMapping (value = "/promote", method = {RequestMethod.POST, RequestMethod.GET}) public ModelAndView renderPromotePage (HttpServletRequest request) { Map<String, String[]> parameters = request.getParameterMap(); for(String key : parameters.keySet()) { System.out.println(key); String[] vals = parameters.get(key); for(String val : vals) System.out.println(" -> " + val); } ModelAndView mv = new ModelAndView(); mv.setViewName("test"); return mv; } 

如果你愿意改变你的URI,你也可以使用PathVariable

 @RequestMapping(value="/mapping/foo/{foo}/{bar}", method=RequestMethod.GET) public String process(@PathVariable String foo,@PathVariable String bar) { //Perform logic with foo and bar } 

注意:第一个foo是path的一部分,第二个是PathVariable

你应该在@RequestMapping写一种模板:

 http://localhost:8080/userGrid?_search=${search}&nd=${nd}&rows=${rows}&page=${page}&sidx=${sidx}&sord=${sord} 

现在定义您的业务方法如下:

 @RequestMapping("/userGrid?_search=${search}&nd=${nd}&rows=${rows}&page=${page}&sidx=${sidx}&sord=${sord}") public @ResponseBody GridModel getUsersForGrid( @RequestParam(value = "search") String search, @RequestParam(value = "nd") int nd, @RequestParam(value = "rows") int rows, @RequestParam(value = "page") int page, @RequestParam(value = "sidx") int sidx, @RequestParam(value = "sort") Sort sort) { ............... } 

所以,框架将${foo}映射到适当的@RequestParam

由于sorting可能是asc或desc我将它定义为一个枚举:

 public enum Sort { asc, desc } 

Spring很好地处理枚举。

这在我的情况下工作:

 @RequestMapping(value = "/savedata", params = {"textArea", "localKey", "localFile"}) @ResponseBody public void saveData(@RequestParam(value = "textArea") String textArea, @RequestParam(value = "localKey") String localKey, @RequestParam(value = "localFile") String localFile) { }