【问题标题】:Spring Boot Context Path Static Files Not Found未找到 Spring Boot 上下文路径静态文件
【发布时间】:2020-01-20 13:17:51
【问题描述】:

我的应用程序无法找到我的静态文件时遇到问题。然而,这仅在一定程度上发生。从下面的代码片段中可以看出,css、图像、js 等适用于某些文件,而不适用于其他文件。不确定我在这里缺少什么。

我的堆栈:Spring Boot,Thymeleaf

我的 application.yml 文件的一部分:

server:
  port: 8090
  servlet:
    context-path: /myapp

我的应用公共资源目录结构:

/resources
   /public
      /css
      /images
      /js

我的应用程序模板结构以及样式和图像的作用:

/resources
  /templates/index.html (works)
  /templates/admin/index.html (works)
  /templates/admin/user/admin/showuser.html (does not work)

来自 /resources/admin/fragments/header.html 的代码(用作其他文件的头文件)

<!DOCTYPE html>
<html>
<head>
    <link href="css/mycss.css" rel="stylesheet">

来自 /resources/templates/index.html 的代码(有效)(不包括 header.html 片段)

<link href="css/mycss.css" rel="stylesheet">

来自 /resources/templates/admin/index.html 的代码(有效)(包括 header.html 作为使用 Thymeleaf 的片段)

<!--/*/ <th:block th:include="/admin/fragments/header"></th:block> /*/-->

来自 /resources/templates/admin/user/admin/showuser.html 的代码(不起作用)(包括 header.html 作为使用 Thymeleaf 的片段)

<!--/*/ <th:block th:include="/admin/fragments/header"></th:block> /*/-->

不知道如何解决这个问题。 谢谢!

【问题讨论】:

    标签: spring-boot thymeleaf static-content contextpath


    【解决方案1】:

    当您的网址以斜杠/ 开头时,它们会尝试解析当前目录。例如:

    Page: /templates/index.html
    Css:  css/mycss.css
    
    The browser tries to locate /templates/css/mycss.css
    

    如果不适用的情况:

    Page: /templates/admin/user/admin/showuser.html
    Css:  css/mycss.css
    
    The browser tries to locate /templates/admin/user/admin/css/mycss.css
    

    如果您想确保您的 css 在任何地方都能正常工作,您需要确保链接始终指向正确的位置。我猜这样的事情会起作用:

    <link th:href="@{/css/mycss.css}" rel="stylesheet">
    

    (使用 Thymeleaf 添加上下文,并使路径成为绝对路径。)

    【讨论】:

    • 您对 Thymeleaf 解决方案绝对 100% 正确。将它添加到我的所有链接后,一切都很好。谢谢。
    猜你喜欢
    • 2016-12-11
    • 2018-10-01
    • 2018-05-17
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2015-08-21
    相关资源
    最近更新 更多