私の質問は、CSSやイメージファイルなどの静的ファイルを追加して使用する方法です。私はSpring MVCとThymeleafを使用しています。私はこの主題のさまざまな記事を見ましたが、彼らは私を助けなかったので、私は尋ねています。これらの記事のとおり、私はCSSと画像ファイルをresources/static/css
とresources/static/images directory
に入れました。すべての私のHTMLファイルが格納されている場所templates
の下Spring MVCとThymeleafを使って静的ファイルを追加する方法
(webapp/WEB-INF/templates
下)は、CSSや画像ファイルを使用したいもの。
私は以下のファイルを持っています:LoginApplicationConfig
私は私のHTMLファイルは、スタイルやイメージファイルを使用することができるように含ま非常に下の2つの方法:私はスタイルファイルを含めることができるように
@EnableWebMvc
@Configuration
@ComponentScan({ "com.myapp.spring.*" })
@Import(value = { LoginSecurityConfig.class })
public class LoginApplicationConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware{
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
@Bean
public TemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(true);
engine.setTemplateResolver(templateResolver());
return engine;
}
private ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/templates/");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/static/css").setCachePeriod(31556926);
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/static/images").setCachePeriod(31556926);
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
はその後、私のindex.htmlファイルで、私はthymeleafを使用して(次の行を含めます):
<link rel="stylesheet" th:href="@{css/stylesmd.css}" type="text/css">
しかし、私はstylesmd.cssが読み込まれなかったというエラーを受けています。
私の質問:
- は正しい私のスタイルや画像ファイルの配置です。つまり、具体的にどのフォルダに入れるべきですか?
webapp
とWEB-INF
ディレクトリのようなさまざまな場所を試しましたが、うまくいきませんでした。 LoginApplicationConfig
の下の2つの方法は必要ですか?さらに、addResourceHandler(...)
メソッドに何を含めるべきか、addResourceLocations(...)
メソッドで何を含めるべきかについて少し混乱しました。- スタイルシート(thymeleafを使用)への参照は正しいですか?
この質問には多くのコンテンツが既に存在していますが、それはうまく機能しませんでしたので、私は尋ねています。