我有一个端点"localhost:8080/users"和一个控制器,它应该将与"/users/**"模式匹配的任何要求重定向到"localhost:8080/users",并通过返回 index.html 文件显示登录页面,该文件是角度应用程序的入口点。我在目录中还有一个静态资源'..资源/静态/用户',其中包含构建的 Angular 应用程序。索引.html文件如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<base href="/users/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<app-root></app-root>
<script src="runtime-es2015.js" type="module"></script><script src="runtime-es5.js" nomodule defer></script><script src="polyfills-es5.js" nomodule defer></script><script src="polyfills-es2015.js" type="module"></script><script src="styles-es2015.js" type="module"></script><script src="styles-es5.js" nomodule defer></script><script src="vendor-es2015.js" type="module"></script><script src="vendor-es5.js" nomodule defer></script><script src="main-es2015.js" type="module"></script><script src="main-es5.js" nomodule defer></script></body>
</html>
问题是对静态 js 文件的任何请求都与我的控制器端点模式匹配并返回 index.html 文件。如何解决这样的问题?
使用ResourceResolver
解析静态资源。
从Spring 框架参考中的静态资源部分:
给定一个以
/resources
开头的请求,相对路径为 用于查找和提供相对于/public
下的静态资源 Web 应用程序根目录或类路径上的/static
下。@Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**") .addResourceLocations("/public", "classpath:/static/") .setCachePeriod(31556926); } }
而且,
WebJar 也通过
WebJarsResourceResolver
在org.webjars:webjars-locator-core
时自动注册 库存在于类路径中。