Spring MVC 如何在我的控制器方法中获取 GET HTTP 请求的参数值?

在这个阶段,我正在学习 Spring MVC 示例(可以从 STS dasboard 下载) ,关于 Request Mapping示例,我有一些简单的问题:

1)在我的 home.jsp页面上有这样一个链接:

        <li>
<a id="byParameter" class="textLink" href="<c:url value="/mapping/parameter?foo=bar" />">By path, method, and presence of parameter</a>
</li>

通过这个链接可以看到,我正在执行一个 HTTP GET 请求,其中有一个包含值“ bar”的“ foo”参数。

此 HTTP 请求由控制器类 MappingController 的以下方法处理:

@RequestMapping(value="/mapping/parameter", method=RequestMethod.GET, params="foo")
public @ResponseBody String byParameter() {
return "Mapped by path + method + presence of query parameter! (MappingController)";
}

此方法管理具有名为“ foo”的参数的 HTTP 请求(仅 GET类型)

如何获取这个参数的值(“ bar”)并将其放入 by Parameter 方法的代码中的变量中?

283549 次浏览

As explained in the documentation, by using an @RequestParam annotation:

public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
+ foo;
}

You could also use a URI template. If you structured your request into a restful URL Spring could parse the provided value from the url.

HTML

<li>
<a id="byParameter"
class="textLink" href="<c:url value="/mapping/parameter/bar />">By path, method,and
presence of parameter</a>
</li>

Controller

@RequestMapping(value="/mapping/parameter/{foo}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String foo) {
//Perform logic with foo
return "Mapped by path + method + presence of query parameter! (MappingController)";
}

Spring URI Template Documentation