Spring Boot CSS 剥离 [英] Spring Boot CSS stripped

查看:24
本文介绍了Spring Boot CSS 剥离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件夹结构

ProjectName
 src/main/java
 src/main/resources
    static
       css
         styles.css
         main.css
       js
       ...
    templates

我所有的 html 文件都在文件夹 templates

All my html files are in the folder templates

我的 HTML 文件头

My HTML file head

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
...
<link rel="stylesheet" href="../static/css/main.css" />
<link rel="stylesheet" href="../static/css/styles.css" />

我的任何 Java 类中都没有 EnableWebMvc

I do not have EnableWebMvc in any of my Java classes

当我将它作为 jar 运行时,页面运行良好,但所有 CSS 都被剥离了.它只是显示为纯文本.我在不同的浏览器中尝试过,结果相同.我做错了什么?

When I run this as a jar, the page comes up fine, but all the CSS is stripped. It just shows up as plain text. I've tried this in different browsers with the same result. What am I doing wrong?

推荐答案

如果您检查浏览器控制台(例如在 Chrome 中),我猜您会看到 HTTP 404 Not found for your CSS files.问题在于您的 CSS 的 URL 路径.

If you check your browser console (e.g. in Chrome), my guess you will see HTTP 404 Not found for your CSS files. The problem is with your URL path to CSS.

主要的一点是文件(.html、.css)在 JAR 文件(或源代码)中的存储方式和 HTTP 服务器如何提供服务是不同的.据我所知,您正在使用 thymeleafs,因此(我再次猜测),您的 HTML 模板文件可以用于不同类型的 URL(例如 //book/23 等),因此我不建议使用相对 URL 来处理 CSS 文件(就像您所做的那样).

The main point is that there is a difference how files (.html, .css) are stored in your JAR file (or in your source code) and how they are served by HTTP server. As far as I see you are using thymeleafs and therefore (my guess again), your HTML template files can be served for different kind of URLs (like /, /book/23 etc.) and therefore I don't recommend to address CSS files with relative URLs (as you did).

由于 CSS 文件存储在 static 目录中,因此它们应该由 Spring Boot 自动为 /** 模式提供服务,即.如果您不使用任何上下文路径,则您的 CSS 应具有以下 URL:/css/main.css.

As CSS files are stored in static directory, they should be automatically served by spring boot for /** pattern, ie. if you don't use any context path, your CSS should have following URL: /css/main.css.

如果你想非常正确并准备好你的 web 应用程序可以在不同的上下文"中,你应该使用类似 <link rel="stylesheet" th:href="@{/css/main.css}">

If you want to be very correct and be prepared that your web application can be in different "context", you should use something like <link rel="stylesheet" th:href="@{/css/main.css}">

这篇关于Spring Boot CSS 剥离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆