Spring MVC - How to get Controller level RequestMa

2019-09-04 09:30发布

For example, if I had a Spring MVC Controller like this:

@Controller
@RequestMapping("/{nickname}")
public class LoginController {
    //...controller code
}

I want a handle to the nickname inside my controller code. How can I do that?

标签: spring-mvc
1条回答
趁早两清
2楼-- · 2019-09-04 09:55

You can use the path variable {nickname} at the controller level, and then use the @PathVariable annotation at the method parameter level.

@Controller
@RequestMapping("/{nickname}")
public class LoginController {
    //...controller code

    @RequestMapping
    public String login(@PathVariable String nickname) {
        // Do something with nickname
    }
}

It may be more sensible to have part of the path fixed to identify the controller specifically - otherwise any request which doesn't get a more exact match may end up being sent to the LoginController which you may not want. For example:

@Controller
@RequestMapping("/login/{nickname}")
public class LoginController {
查看更多
登录 后发表回答