[英]Spring Boot 2.6 and Angular in static Resources
我的問題與已經提出並回答但不是 100% 最新的問題非常相似。
我們使用 Chris Gaskill 的解決方案有一段時間了,它非常適合我們,因為我們想重定向包含多個路徑段(即/foo/bar
)的請求
從 Spring Boot 2.4 開始,Boot 使用PathPatternParser
而不是AntPathMatcher
,其中前者不再支持模式開頭的**
( 請參閱文檔)。
是否有其他解決方案來獲得相同的行為? 您使用什么將所有與其他任何內容都不匹配的請求重定向到index.html
應用程序的 index.html?
這是轉發請求的 controller 的代碼。
@Controller
class SpaRoutingController {
@GetMapping("/**/{path:[^\\.]*}", headers = "X-Requested-With!=XMLHttpRequest")
fun forward(): String? {
return "forward:/"
}
}
我寧願使用 go 解決方案來配置WebMvcConfigurer
。 請參閱下面的代碼。
Maven 配置
Maven 配置指示frontend-maven-plugin
構建 angular 並將構建內容復制到target/static
目錄中,以便在最終 WAR 和 JAR 構建中可用。 然后我另外配置一個WebMvcConfigurer
來在JAR / WAR的static目錄中查找資源,如果找到-將其發送給客戶端,否則重定向到index.html。
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>${maven-clean-plugin.version}</version>
<configuration>
<filesets>
<fileset>
<directory>src/main/webapp</directory>
<includes>
<include>*.js</include>
<include>*.txt</include>
<include>*.html</include>
<include>*.css</include>
<include>*.map</include>
<include>*.json</include>
<include>*.ico</include>
<followSymlinks>false</followSymlinks>
</includes>
</fileset>
<fileset>
<directory>src/main/webapp/assets</directory>
<includes>
<include>**</include>
<followSymlinks>false</followSymlinks>
</includes>
</fileset>
</filesets>
</configuration>
<executions>
<execution>
<id>auto-clean</id>
<phase>initialize</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<phase>process-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/classes/static</outputDirectory>
<includeEmptyDirs>true</includeEmptyDirs>
<resources>
<resource>
<directory>${basedir}/src/main/${angular.project.name}/dist/${angular.project.name}</directory>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>1.8.0</version>
<configuration>
<workingDirectory>src/main/${angular.project.name}</workingDirectory>
</configuration>
<executions>
<execution>
<id>install node and npm</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
<phase>generate-resources</phase>
<configuration>
<nodeVersion>v14.16.1</nodeVersion>
</configuration>
</execution>
<execution>
<id>npm build angular</id>
<goals>
<goal>npm</goal>
</goals>
<phase>generate-resources</phase>
<configuration>
<arguments>run build:prod</arguments>
</configuration>
</execution>
</executions>
</plugin>
MVC 配置
在這里,您嘗試查找 static 目錄中是否存在資源,如果不存在,則將其重定向到 index.html。
您可能需要根據您的要求更改源位置。
@Configuration
public class ApplicationWebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/")
.resourceChain(true)
.addResolver(new PathResourceResolver() {
@Override
protected Resource getResource(String resourcePath, Resource location)
throws IOException {
Resource requestedResource = location.createRelative(resourcePath);
if (requestedResource.exists() && requestedResource.isReadable()) {
return requestedResource;
}
return new ClassPathResource("/static/index.html");
}
});
}
}
PathPatternParser 等同於之前的 AntPathMatcher /**
將是:
@GetMapping("/{*path}")
根據 spring 文檔:
/resources/{*path} — 匹配 /resources/ 和 /resources 下的所有文件,並在名為“path”的變量中捕獲它們的相對路徑; /resources/image.png 將匹配“path”→“/image.png”,/resources/css/spring.css 將匹配“path”→“/css/spring.css”
編輯 - 與循環有關:
在您的情況下,為了避免由於使用forward:/
如果您只關心加載 angular 頁面而導致的循環,只需將forward
替換為 index.html 的實際內容
如果出於某種原因你需要轉發以便在返回響應之前展平 uri 你可以通過各種方式解決它你可以forward:/index.html
@GetMapping("/index.html") 應該優先於通配符或使用@PathVariable
來區分行為並避免永恆的前向循環
@Controller
class SpaRoutingController {
@GetMapping("/{*path}")
fun forward(@PathVariable(value="path", required=false) path: String): String? {
if ("/".equals(path)) { // may need to handle additional cases
return ""; // or your index.html
}
return "forward:/";
}
}
您是否嘗試過在 Angular 端實現重定向? 在我的應用程序中,我已經解決了這個問題:
const routes: Routes = [
{path: '', redirectTo: '/myProjects', pathMatch: 'full'},
//...
{path: '**', redirectTo: ''}
}
@NgModule({
imports: [
RouterModule.forRoot(routes, {useHash: true})
],
exports: [
RouterModule
],
declarations: []
})
export class MyRoutingModule {
}
在使用Angular時,您不能談論諸如index.html
類的頁面。 你有什么路線!
所以當你重定向時,你應該做的是路由而不是頁面。
ModelAndView forward() {
return new ModelAndView("redirect:/");
}
PS:如果/
是你的默認路由。
您是否嘗試過使用 Servlet 過濾器來處理 Spring Boot 未處理的端點? Baeldung的這篇文章解釋了一個解決方案,您可以檢查您的用例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.