Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have 2 spring controller mappings:

@Controller
public class ContentController {

    @RequestMapping(value = "**/{content}.html")
    public String content(@PathVariable String content, Model model, HttpServletRequest request) {
    }
}

@Controller
public class HomeController {

    @RequestMapping(value = "**/home")
    public String home(HttpServletRequest request, Model model) {
    }
}

The following url matches both mappings: /home.html

However, I want to ensure that the 'content' mapping ALWAYS has priority over the 'home' mapping. Is there a way I can specify that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
227 views
Welcome To Ask or Share your Answers For Others

1 Answer

I had very similar problem recently where I had to two kind of ambiguous URLs:

  • One was accepting a year, say /2012, /2013 etc. I created it using mapping with regular expression like this: @RequestMapping("/{year:(?:19|20)\d{2}}")
  • Another one was accepting a content identifier (aka slug). I created it using mapping like @RequestMapping("/{slug}").

It was important that the "year" controller method was taking precedence over the "slug" one. Unfortunately (for me) Spring was always using the "slug" controller method.

As Spring MVC prefers more specific mappings, I had to make my "slug" pattern less specific. Based on Path Pattern Comparison documentation, I added wild card to the slug mapping: @RequestMapping("/{slug}**")

My controllers look like that and now listByYear is called when a year (/2012, /1998 etc) is in URL.

@Controller
public class ContentController
{
    @RequestMapping(value = "/{slug}**")
    public String content(@PathVariable("slug") final String slug)
    {
        return "content";
    }
}

and

@Controller
public class IndexController
{
    @RequestMapping("/{year:(?:19|20)\d{2}}")
    public String listByYear()
    {
        return "list";
    }
}

This is not exactly how to set up a priority (which in my opinion would be an amazing feature) but give some sort of "nice" workaround and might be handy in the future.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...