有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用springmvc和Thymeleaf添加静态文件

我的问题是如何添加静态文件,如CSS和图像文件,以便我可以使用它们。我正在使用SpringMVC和Thymeleaf。我看了很多关于这个主题的帖子,但是它们对我没有帮助,所以我问。根据这些帖子,我将CSS和图像文件放在resources/static/cssresources/static/images directory

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();
    }

}

然后在我的索引中。html文件中,我包含了以下行,以便可以包含样式文件(使用thymeleaf):

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

但是我一直得到一个错误,那就是stylesmd。css无法加载

我的问题是:

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

我知道在这个问题上已经有很多内容了,但这对我来说不起作用,所以我要问


共 (1) 个答案

  1. # 1 楼答案

    我就是这样做的。 只有一行就够了

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

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

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