开门见山,三种方式解决。
有好有坏,你感觉不好的方式,了解即可。
下面测试的 SpringBoot version:2.3.1.RELEASE
问题引入
当你访问没有处理的 requestMapping 路径时,会出现“Whitelabel Error Page”
例如当你访问下面的:http://localhost:8080/ 或 http://localhost:8080/sJKnaIsf/skdjfi
方式1(了解):
给没有设置的路径添加 requestMaping 路径。
如果你访问 http://localhost:8080/ 时,不想让首页显示“Whitelabel Error Page”
》》》代码实现
1 | import org.springframework.web.bind.annotation.RestController; |
》》》测试访问
此时,你只是解决了首页,其他不存在的页面,同样不能解决。(了解即可)
具体想拦截所有 404 不存在的页面,可以参考下面“方式2”。
方式2(推荐):
给内嵌的容器添加错误页面。
》》》添加配置类
1 | import org.springframework.boot.web.server.ErrorPage; |
》》》添加 404 错误页面,路径“resources\static\404.html”
1 |
|
》》》测试(只要是不存在的页面,都等同于访问 http://localhost:8080/404.html)
方式3(了解):
基于拦截器实现:“可以通过的页面都放行,不可用识别的页面都拦截”
拦截器使用参考:SpringMVC 拦截器