【发布时间】:2015-11-13 03:17:08
【问题描述】:
Thymeleaf 模板定位放置在 Web 应用程序根目录中的静态文件(包括下面的 CSS 文件)的问题。我已经通过 addResourceHandlers() 方法添加了相关的映射(/resource)(参见下面的配置类)。
也许这与最近切换到 gradle(以前是 Maven)有关。我可能忽略了 build.gradle 文件中的某些内容?
<link rel="stylesheet" th:href="@{'/resources/stylesheets/test.css'}" type="text/css" media="screen" />
浏览器控制台输出(页面加载时)
Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:8080/resources/stylesheets/test.css".
百里香
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:tiles="http://www.thymeleaf.org">
<head>
<!--Stylesheets -->
<link rel="stylesheet" th:href="@{'/resources/stylesheets/test.css'}" type="text/css" media="screen" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
</head>
...
</html>
.war 目录结构
- root/
--stylesheets/
--- test.css
--images/
--META-INF/
--WEB-INF/
--...
配置类
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/")
.setCachePeriod(31556926);
}
...
}
Gradle 构建文件
buildscript {
repositories {
mavenLocal()
jcenter()
}
dependencies {
classpath 'com.bmuschko:gradle-tomcat-plugin:2.2.2'
}
}
plugins {
id "com.bmuschko.tomcat" version "2.2.2"
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'war'
apply plugin: 'com.bmuschko.tomcat-base'
version = '1.0'
group = 'com.project'
sourceCompatibility = 1.8
targetCompatibility = 1.8
war {
baseName = '/'
archiveName = "${project.name}.war"
}
war.doLast {
ant.unzip(src: war.archivePath, dest: "$buildDir/$project.name")
}
sourceSets {
main {
java{
srcDir 'src/main/java'
}
resources {
srcDir 'src/main/resources'
}
}
test {
java {
srcDir 'src/test/java'
}
resources {
srcDir 'src/test/resources'
}
}
}
dependencies {
modules {
module("javassist:javassist") {
replacedBy("org.javassist:javassist")
}
}
tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
"org.apache.tomcat.embed:tomcat-embed-logging-juli:${tomcatVersion}"
tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}") {
exclude group: "org.eclipse.jdt.core.compiler", module: "ecj"
}
....
}
repositories {
jcenter()
mavenCentral()
mavenLocal()
}
task wrapper(type: Wrapper) {
gradleVersion = '2.6'
}
jar {
manifest {
attributes 'Implementation-Title': 'App',
'Implementation-Version': version
}
}
test {
systemProperties 'property': 'value'
testLogging {
// Show that tests are run in the command-line output
events 'started', 'passed'
exceptionFormat "full"
showStandardStreams = true
showCauses = true
showExceptions = true
}
}
【问题讨论】:
-
我记得,
.addResourceLocations("/")会尝试在类路径根目录中查找资源,例如在src/main/resources而不是war文件根目录? -
"/" 确实指向部署根目录。
标签: spring spring-mvc gradle spring-boot