Static Resources Using Spring and Thymeleaf

I am trying to access my static resources in my HTML using the following code:

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

But it just works when I put it @{static/css/main.css}. I know that when you set the resource folder, you do not need to set the static folder every time you call the static file.

My folder structure:

/webapp
=== /static
==========/css
==========/js
=== /WEB-INF
==========/views

Configuring Spring mvc configurations:

....
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Bean
    public ViewResolver viewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }

    private TemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver());
        return engine;
    }

    private ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".html");
        resolver.setCacheable(false); // On production , turn TRUE
        resolver.setTemplateMode(TemplateMode.HTML);
        return resolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

I am using Spring 4 and Thymeleaf 3 beta. Each css-js-image file that I use, I need to write "static" in the path. This code, which is encoded, does not work, so as not to write the full path. Why?

+4
source share
1 answer
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
                             ^^^^^^^^                           ^^^^^^^
                             ----------- These two are different ------       

spring mvc, /static/ /static . , static/css/main.css, .

, , .

, /static/** /static. static @{static/css/main.css} /static/** , :

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

:

...addResourceLocations("/static/")

, :

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

, , content/css/main.css.

: css/main.css , :

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

/static/ src/main/resources.

+2

Source: https://habr.com/ru/post/1629807/


All Articles