我正在使用 Spring Boot 来提供静态内容。我的所有静态内容都位于 src/main/resources/static
下。
我有如下简单的文件夹结构。我没有上下文路径。
static/index.html (Default index page)
static/emp/index.html
通过访问localhost:8080
按预期返回index.html
。
但是,如果访问localhost:8080/emp
,我期望提供emp/index.html
,但它没有发生。它返回错误,指出没有错误默认错误页面
。它在其他静态 Web 服务器中运行良好。默认情况下,Spring Boot 不会在任何子文件夹下提供 index.html
服务。
最佳答案
已经回答here 。 它不是 Spring Boot 映射到 index.html,而是 servlet 引擎(这是一个欢迎页面)。只有一个欢迎页面(根据规范),并且目录浏览不是容器的一项功能。
您可以手动添加 View Controller 映射来使其工作:
@Configuration
public class CustomWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/emp").setViewName("redirect:/emp/"); //delete these two lines if looping with directory as below
registry.addViewController("/emp/").setViewName("forward:/emp/index.html"); //delete these two lines if looping with directory as below
String[] directories = listDirectories("/");
for (String subDir : directories){
registry.addViewController(subDir).setViewName("redirect:/" + subDir + "/");
registry.addViewController(subDir).setViewName("forward:/" + subDir + "/index.html");
}
super.addViewControllers(registry);
}
}
/**
* Resources mapping
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("classpath:/assets/css/"); //my css are in src/resources/assets/css that's why given like this.
registry.addResourceHandler("/emp/**").addResourceLocations("classpath:/emp/");
registry.addResourceHandler("/images/**").addResourceLocations("classpath:/assets/images/");
registry.addResourceHandler("/js/**").addResourceLocations("classpath:/assets/js/");
}
/***
This should list subdirectories under the root directory you provide.
//Not tested
***/
private String[] listDirectories(String root){
File file = new File(root);
String[] directories = file.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
}
如果请求 /emp
(不带尾部斜杠),第一个映射会导致 Spring MVC 向客户端发送重定向。如果您在 /emp/index.html
中有相对链接,则这是必要的。第二个映射将任何对 /emp/
的请求内部转发(不向客户端发送重定向)到 emp
子目录中的 index.html
.
并且您收到错误消息没有默认错误页面
,因为您正在尝试访问尚未配置的localhost:8080/emp/
。因此 spring-boot 将检查是否配置了任何错误页面。由于您还没有配置错误页面,因此您会收到上述错误。
关于Spring Boot 服务器提供静态内容的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53878909/