Gurdev Parmar
Gurdev Parmar

Reputation: 1

Spring MVC - How to get Controller level RequestMapping parameter inside Controller

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?

Upvotes: 0

Views: 3123

Answers (1)

Will Keeling
Will Keeling

Reputation: 23054

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 {

Upvotes: 6

Related Questions