Spring Controller RequestMapping 统一访问路径的前缀

文章目录

    使用场景

    例如,我想写一个 emoji 表情查询功能。相关的页面链接:

    • emoji 首页 /emoji
    • 标签分类 /emoji/tag/tag-slug
    • 具体标签详情 /emoji/emoji-slug

    特征就是都以 emoji 作为网址路径前缀。

    写个简单测试 Controller

    返回字符串看看效果。

    @RestController
    @RequestMapping("/emoji")
    public class EmojiController {
        @GetMapping("")
        public String index() {
            return "hello index";
        }
    
        @GetMapping("/tag/{slug}")
        public String tag(@PathVariable("slug") String slug) {
            return "hello tag " + slug;
        }
    }
    

    测试结果:

    http://localhost:9090/emoji/tag/smile
    hello tag smile
    

    果然可以。

    首页不想缀上斜杠

    例如访问

    http://localhost:9090/emoji

    报错:

    Whitelabel Error Page
    This application has no explicit mapping for /error, so you are seeing this as a fallback.
    Fri Dec 18 17:00:55 CST 2020
    There was an unexpected error (type=Not Found, status=404).
    No message available
    

    而加上后缀斜杠就正常:

    http://localhost:9090/emoji/
    hello index
    

    解决方法:

    @GetMapping("/")
    

    替换为:

    @GetMapping("")
    

    这样的好处是,同时支持了加斜杠后缀和不加的情况。

    参考

    • https://www.oreilly.com/library/view/spring-cookbook/9781783985807/ch03s06.html

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式