gpt4 book ai didi

java - 如何使用 Spring MVC 和 Thymeleaf 添加静态文件

转载 作者:太空宇宙 更新时间:2023-11-04 09:52:01 25 4
gpt4 key购买 nike

我的问题是如何添加 CSS 和图像文件等静态文件以便我可以使用它们。我正在使用 Spring MVC 和 Thymeleaf。我查看了有关此主题的各种帖子,但它们对我没有帮助,所以我在问。根据这些帖子,我将我的 CSS 和图像文件放在 resources/static/cssresources/static/images 目录中。

demo

templates 下(webapp/WEB-INF/templates 下)是我所有的 HTML 文件的存放地,那些要使用 CSS 和图像文件的。

我有以下 LoginApplicationConfig 文件。我包含的最底层的两个方法使我的 HTML 文件可以使用样式和图像文件:

@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 无法加载的错误。

我的问题:

  1. 我的样式和图像文件的位置是否正确。也就是说,我应该专门将它们放在什么文件夹中。我尝试了各种位置,例如 webappWEB-INF 目录下,但没有用。
  2. 是否需要LoginApplicationConfig中最下面的两个方法?此外,我对在 addResourceHandler(...) 方法中包含什么以及在 addResourceLocations(...) 方法中包含什么感到有点困惑。
  3. 我对样式表(使用 thymeleaf)的引用是否正确?

我知道很多内容已经存在于这个问题上,但这对我不起作用,所以这就是我问的原因。

最佳答案

我就是这样实现的。一根线就够了。

registry.addResourceHandler("/static/**").addResourceLocations("/static/");

<head>
<link rel="stylesheet" type="text/css" href="/static/css/your.css" th:href="@{/static/css/your.css}"/>
</head>

如果一直失败,请尝试将“templates”文件夹作为子文件夹移动到资源文件夹中。

关于java - 如何使用 Spring MVC 和 Thymeleaf 添加静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39024767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com