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?

4

1 回答 1

6

不,它们是完全不同的构造:

代码 1

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

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

}

在这种情况下,createForm将在 URL 发出 HTTP 请求时调用方法/users?register。引用Spring Javadocregister ,这意味着无论HTTP 参数的值如何,都会调用此方法;它必须存在。

还支持“myParam”样式表达式,此类参数必须存在于请求中(允许具有任何值)。

代码 2

@Controller
public class UserController {

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

}

在这种情况下,@RequestMapping声明registerPathVariable. createForm如果在 URL 发出 HTTP 请求,则将调用该方法/users/something,无论something. 您实际上可以something像这样检索它:

@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";
} 
于 2015-08-30T16:26:12.087 回答