在Spring Boot中加載CSS的方法有多種,以下是一些常見的做法:
1、在HTML頁面中直接引入CSS文件,在HTML的<head>
標(biāo)簽中,使用<link>
標(biāo)簽引入CSS文件,
<link rel="stylesheet" href="path/to/your/css/file.css">
2、使用Spring的Resource
類加載CSS文件,在Java代碼中,可以使用Resource
類加載CSS文件,并將其內(nèi)容轉(zhuǎn)換為String
類型,然后將其作為HTML頁面的樣式表。
import org.springframework.core.io.ClassPathResource; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Base64; public String loadCssFile(String fileName) { try { ClassPathResource resource = new ClassPathResource(fileName); InputStream inputStream = resource.getInputStream(); byte[] fileContent = new byte[(int) resource.contentLength()]; inputStream.read(fileContent); return Base64.getEncoder().encodeToString(fileContent); } catch (Exception e) { e.printStackTrace(); return null; } }
3、使用@Value
注解加載CSS文件,在Spring Boot中,可以使用@Value
注解將CSS文件的內(nèi)容注入到Java代碼中,
import org.springframework.core.io.ClassPathResource; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Base64; @Value(resourceBundlePath = "path/to/your/css/file.css", encoding = "UTF-8") public String cssContent;
4、使用Thymeleaf
模板引擎加載CSS文件,在Thymeleaf模板中,可以使用th:include
標(biāo)簽引入CSS文件,
<head> <title>Page Title</title> <link rel="stylesheet" th:include="path/to/your/css/file.css"></link> </head>
是幾種常見的加載CSS文件的方法,你可以根據(jù)自己的需求選擇適合的方法。