私は春のブートプロジェクトビットを持っています。私はCSSファイルを含めることができません。春ブーツの私のSpring BOOTにCSSファイルを含めることができません
main
-java
-DemoApplication.java
-Initializer.java
-WebAppConfig.java
-resources
-static
-css
-test.css
-templates
-start.html
-WEB-INF
-web.xml
スタート・ポイント・クラス:初期コンフィグため
@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);
}
}
コンフィグファイルの場所のリソースマッピング:
それは私のプロジェクトの構造であり、@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が
@EnableWebMvc注釈を削除する必要があります。デフォルトでは、Springブートは 'src/main/resources/static'にあるものを自動的に利用可能にし、あなたのために' DispatcherServlet'を設定します。 'web.xml'と' Initializer'と 'WebAppConfig'クラスを削除してみてください。 –
私は@AndyWilkinsonに同意します。あなたはそれを簡単に保つべきです。とにかく、ここでの問題は、Mavenの概念に関連しています。 src/main/resourcesは、最終的なjar/warには作成されません。 Mavenはそれをターゲットクラスパスに追加します。生成されたjar/warを解凍すると、トップレベルに表示され、リソースフォルダには表示されません。 Maven情報:https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html –