Thymeleaf无法加载资源

EI-*_*-01 3 html thymeleaf

您好我正在尝试使用thymeleaf呈现我的html页面,但无法加载.js文件.我正在使用spring-boot,我的文件结构src/main/resources/templates包含了我所有的html文件.我的css文件位于src/main/resources/static/css/.我的.js文件位于src/main/resources/js/.

现在我尝试渲染我的guest.html文件,但它没有加载资源,因为我尝试检查chrome上的元素,它显示以下错误消息:

http://localhost:8080/js/bootstrap-formhelpers.min.js Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:8080/js/bootstrap.min.js Failed to load resource: the server responded with a status of 404 (Not Found)
Run Code Online (Sandbox Code Playgroud)

以下是我的guest.html文件中无法找到资源的问题:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js" th:src="@{https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js}" ></script>
<script src="../js/bootstrap.min.js" th:src="@{js/bootstrap.min.js}"></script>
<script src="../js/bootstrap-formhelpers.min.js" th:src="@{js/bootstrap-formhelpers.min.js}"></script>
Run Code Online (Sandbox Code Playgroud)

Tom*_*lst 5

src/main/resources默认情况下,Spring Boot不提供静态内容.它提供以下类路径位置的内容:

  • classpath:/META-INF/resources
  • classpath:/static
  • classpath:/resources
  • classpath:/public

因此,src/main/resources/static/css服务,但不是src/main/resources/js/.

js目录移动到src/main/resources/static目录以使其服务.另一个选择是添加资源处理程序:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/js/**")
            .addResourceLocations("classpath:/js/");
}
Run Code Online (Sandbox Code Playgroud)

您也可以覆盖该spring.resources.staticLocations属性.

有关使用Spring Boot提供静态内容的更多信息,请参阅Spring Boot Documentation:Static Content.