最简单方式:
配置404页面
1 2 3 4
| @Bean public ErrorPageRegistrar errorPageRegistrar(){ return registry -> registry.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/index.html")); }
|
问题:
- 所有404都回定向到html 报错一些不存在的js,jpg文件,都返回index.html里面内容了
- html页面状态码是404 看起来很不和谐
分析问题
springMVC 请求请求顺序
- Controller
- static-resources 有/**兜底
解决一:(推荐)
我们可以在Controller里面配置一个区别于接口的 路径 返回index.html文件
例如
1
| @RequestMapping("/html/**");
|
感觉对路径侵入有点大必须html开头
换种匹配规则 所有 路径不带.
的
1
| @RequestMapping("/**/{path:[^.]+}");
|
升级写法,写一个HandlerMapping放在Controller
后面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Component public class VueSinglePage extends AbstractUrlHandlerMapping { public VueSinglePage() { HttpRequestHandler httpRequestHandler = (request, response) -> { response.setContentType(MediaType.TEXT_HTML_VALUE); FileCopyUtils.copy(Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResourceAsStream("static/index.html")), response.getOutputStream()); }; registerHandler("/**/{path:[^.]+}", httpRequestHandler); registerHandler("/", httpRequestHandler); }
@Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE - 1; } }
|
解决二
static-resources 把/**兜底 关掉
写一个全匹配的HandlerMapping插入在12后面
1
| spring.resources.add-mappings=false
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| @Bean HandlerMapping vueHandlerMapping() { return new VueHandlerMapping(); }
class VueHandlerMapping implements HandlerMapping, Ordered { @Override public HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception { return new HandlerExecutionChain(new HttpRequestHandler() { @Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(MediaType.TEXT_HTML_VALUE); FileCopyUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("public/dist/index.html"), response.getOutputStream()); } }); }
@Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE; } }
|