This basically sounds to me like you're asking "what is a RequestParam
and why should I use it?"
The RequestParam allows you to bind the method parameter argument to the web request parameter. Without any other attributes, your example tells Spring that a name
and age
parameter are required and Spring will know to associate those two parameters against the incoming request. You can optionally set required
to false
to, well, make the argument optional:
public String PrintInfo(@RequestParam("name", required = false) String name,
@RequestParam("age") int age) {
As an extremely useful feature, you can also provide a defaultValue
in case you receive an empty value from the request. So you can do:
public String PrintInfo(@RequestParam("name", defaultValue="John Doe") String name,
@RequestParam("age") int age) {
...and you'll never deal with a null name.
Finally, using it also does some magic type conversions, like for example automatically using an Integer
type. In your example, you could have used:
public String PrintInfo(@RequestParam("name") String name,
@RequestParam("age") Integer age) {
...and Spring would have boxed it automatically without you doing any extra work.
There's nothing inherently wrong with leaving off the RequestParam
annotation, but you're essentially saying no to Spring enabling these features as you have in your second case.
Aside:
@RequestMapping(value="/print")
can be more simply written as @RequestMapping("/print")