首页 > 解决方案 > 提供静态内容的 Springboot 服务器问题

问题描述

我正在使用 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得到服务,但它没有发生。它返回错误说there is no error default error page。它在其他静态 Web 服务器中运行良好。默认情况下,spring boot 不在index.html任何子文件夹下提供服务。

标签: springspring-boot

解决方案


这里已经回答。它不是 Spring Boot 到 index.html 的映射,它是 servlet 引擎(它是一个欢迎页面)。只有一个欢迎页面(根据规范),目录浏览不是容器的功能。

您可以手动添加视图控制器映射以使其工作:

@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/内部(不向客户端发送重定向)到子目录index.html中的。emp

以及您收到的错误消息there is no default error page,因为您正在尝试访问localhost:8080/emp/尚未配置的内容。所以 spring-boot 将检查是否配置了任何错误页面。由于您还没有配置错误页面,因此您会收到上述错误。


推荐阅读