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

发布时间: 2020-12-25 13:59:30 作者: 大象笔记

使用场景

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

特征就是都以 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("")

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

参考

我是一名山东烟台的开发者,联系作者