我有spring引导项目,我不能包含css文件。 这是我的项目的结构:我不能将css文件包含到我的Spring BOOT中
main
-java
-DemoApplication.java
-Initializer.java
-WebAppConfig.java
-resources
-static
-css
-test.css
-templates
-start.html
-WEB-INF
-web.xml
起点班春启动的:用于初始化CONFIGS
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
WebApplicationInitializer类:
public class Initializer implements WebApplicationInitializer {
private static final String DISPATCHER_SERVLET_NAME = "dispatcher";
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebAppConfig.class);
servletContext.addListener(new ContextLoaderListener(ctx));
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet(DISPATCHER_SERVLET_NAME,
new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
CONFIGS文件,其中地方资源映射:
@Configuration
@EnableWebMvc
@ComponentScan("com.example")
public class WebAppConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/static/");
}
}
这是我的网页:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handling Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="../static/css/test.css" th:href="@{/css/test.css}" media="screen"/>
</head>
<body>
<h1>Result</h1>
<[email protected] id="message" type=""-->
<p th:text="${message}" ></p>
</body>
</html>
是CSS
.h1{
font-size: 11px;
background-color: red;
}
和web.xml
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
</web-app>
当我联系我看到我的网页,但CSS有没有
你配置的东西,春天开机时会为您配置,包括资源处理这很可能是问题所在。默认情况下,Spring Boot会自动使src/main/resources/static中的任何东西可用,并为您配置一个DispatcherServlet。尝试删除您的'web.xml',以及'Initializer'和'WebAppConfig'类。 –
我同意@AndyWilkinson,你应该保持简单,保持春天的工作做的工作。无论如何,这里的问题与maven的概念有关。 src/main/resources,不会在你的最终jar/war中创建。 Maven会将它添加到目标类路径中。如果你解压缩生成的jar/war,你将会在顶层看到它,而不是在资源文件夹中。 Maven info:https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html –