Search code examples
springspring-mvcrequest-mapping

Spring MVC RequestMapping PathVariable in the first place


I would like to set for each user's own profile link.
Like this:

   @RequestMapping(value = "/{userlogin}", method = RequestMethod.GET)
    public String page(@PathVariable("userlogin") String userlogin, ModelMap model) {
        System.out.println(userlogin);
        return "user";
    }

But static pages get this expression too..
Like this:

@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() {
    System.out.println("hello mapping");
    return "hello";
}

That is when I request GET request "hello" that calls both controllers.
I would like to do that, user controller calls only if other methods not called.

Console, when I calls localhost:8080/123:

123

Console, when I calls localhost:8080/hello:

hello 
hello mapping

or

hello mapping
hello 

I want to get only

hello mapping

when calls localhost:8080/hello

Who knows how it can be implemented?


Solution

  • Spring MVC can use URI Template Patterns with Regular Expressions. Provided :

    • userlogin only contain digits
    • others URL immediately under root contains at least one non digit character

    you can use that in your @RequestMapping :

    @RequestMapping(value = "/{userlogin:\\d+}", method = RequestMethod.GET)
    public String page(@PathVariable("userlogin") String userlogin, ModelMap model) {
        //...
    }
    

    If the separation between userlogin and other URL is different from what I imagined, it can be easy to adapt.