spring - 提供静态内容的 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
任何子文件夹下提供服务。
解决方案
这里已经回答了。它不是 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 将检查是否配置了任何错误页面。由于您还没有配置错误页面,因此您会收到上述错误。
推荐阅读
- c++ - C++ 数据存储
- javascript - 在 Node 中使用 mySQL 导致 Async/Await 出现问题
- node.js - 如何使用节点从网站上抓取数据
- node.js - SyntaxError: Unexpected reserved word => prettier/third-party.js
- arrays - Dataweave:将正则表达式模式匹配到数组的每个元素
- vue.js - Vue-Router - 将数据从一个路由组件传递到另一个
- javascript - 为什么第二个 Javascript 函数返回 NaN?
- python - Itertools 加速美丽汤中的嵌套循环
- java - “load()”处的 cassandra-connector 问题
- r - ggplot:将具有给定宽度的边框添加到 geom_point()