0

I am pretty new in Spring MVC and I have the following doubt.

In a controller, I have a method annotated in this way:

@Controller
@RequestMapping(value = "/users")
public class UserController {

    @RequestMapping(params = "register")
    public String createForm(Model model) {
        model.addAttribute("user", new Customer());
        return "user/register";
    } 

}

So this method handle HTTP Request toward the URL /users?register where register is a parameter (because the entire class handle request toward /users resource).

Is it the same thing if, instead using the params = "register" I use the following syntaxt:

@Controller
public class UserController {

    @RequestMapping("/users/{register}")
    public String createForm(Model model) {
        model.addAttribute("user", new Customer());
        return "user/register";
    } 

}

I have deleted the mapping at class level and I use @RequestMapping("/users/{register}").

Is it the same meaning of the first example?

Aniket Kulkarni
  • 12,825
  • 9
  • 67
  • 90
AndreaNobili
  • 40,955
  • 107
  • 324
  • 596

1 Answers1

6

NO, they are completely different constructs:

Code 1

@Controller
@RequestMapping(value = "/users")
public class UserController {

    @RequestMapping(params = "register")
    public String createForm(Model model) {
        model.addAttribute("user", new Customer());
        return "user/register";
    } 

}

In this case, createForm method will be called when a HTTP request is made at URL /users?register. Quoting from Spring Javadoc, it means this method will be called whatever the value of the register HTTP parameter; it just has to be present.

"myParam" style expressions are also supported, with such parameters having to be present in the request (allowed to have any value).

Code 2

@Controller
public class UserController {

    @RequestMapping("/users/{register}")
    public String createForm(Model model) {
        model.addAttribute("user", new Customer());
        return "user/register";
    } 

}

In this case, @RequestMapping is declaring register as a PathVariable. The method createForm will be called if a HTTP request is made at URL /users/something, whatever the something. And you can actually retrieve this something like this:

@RequestMapping("/users/{register}")
public String createForm(@PathVariable("register") String register, Model model) {
    // here "register" will have value "something".
    model.addAttribute("user", new Customer());
    return "user/register";
} 
Tunaki
  • 132,869
  • 46
  • 340
  • 423