Spring引导更改静态路径模式不自动为index.html服务



我有一个spring-boot项目,在resources/static/文件夹中也包含了前端代码。我已经将上下文路径设置为/ibo-modules,将端口设置为9080。现在,当我尝试点击http://localhost:9080/ibo-modules/时,spring-boot将自动从中加载index.html文件。现在我想更改加载静态文件的url模式。为此,我尝试了两种方法:

  1. 设置spring.mvc.static路径模式=/ui/**
  2. 创建了自定义webMvcConfigurer,如下所示
public class CustomWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/ui/**").addResourceLocations("classpath:/static/");
}
}

在这两种情况下,每当我点击http://localhost:9080/ibo-modules/ui/时,它都不会加载。我得到404错误。我必须显式地输入http://localhost:9080/ibo-modules/ui/index.html才能加载静态页面。但在我的项目中,这并不是有意的。有人能帮我解决这个问题吗?

与使用WebMvcConfigurer.addResourceHandlers方法一样,您也可以使用特殊的forward:前缀覆盖WebMvcConfigurer.addViewControllers方法,如下所示:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/ui/") //<--Configure automated controller for /ui/
.setViewName("forward:/ui/index.html"); //<-- forward to index.html
}

相关内容

最新更新