Spring MVC How to accept the value of the GET HTTP Request parameter in my controller method?

During this period, I am studying the Spring MVC showcase example (downloadable from STS dasboard), and I have a simple question about Request Mapping examples:

1) On my home.jsp page, I have this link:

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

As you can see from this link, I am making an HTTP GET request with the parameter "foo" containing the value: "bar".

This HTTP request is processed by the following method of the MappingController controller class:

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

This method manages the HTTP request ( GET type only), which has a parameter named "foo"

How can I take the value ("bar") of this parameter and put it in a variable inside the code of my Parameter method?

+62
java spring parameters request
Nov 18 '12 at 17:34
source share
2 answers

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

 public @ResponseBody String byParameter(@RequestParam("foo") String foo) { return "Mapped by path + method + presence of query parameter! (MappingController) - foo = " + foo; } 
+145
Nov 18 '12 at 17:40
source

You can also use the URI pattern. If you structured your request in a calm Spring URL, you can 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

+33
Nov 19 '12 at 10:10
source



All Articles