thymeleaf 3 spring 5 load css

2019-08-23 12:45发布

I'm trying to configure Spring5 and Thymeleaf3 togheter.

I'm working on Eclipse, I build with clean install and run the app with springboot:run.

I've setup a controller and a couple of template and css but it seems that thymeleaf cannot find the css, in the browser it shows the template (es. 'panda.html') without loading the css but if I open manually the .html the browser load also the .css . What i need to add to my code?

this is the mapping

@Controller
public class MyController {

@Autowired
UtentiRepository utentiRepository;  

@GetMapping("/gab")
public String panda(Model model) {

return "panda";
}

and this is the template resolver

@Bean
public SpringResourceTemplateResolver templatecssResolver() {
    SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
    templateResolver.setApplicationContext(applicationContext);
    templateResolver.setPrefix("classpath:/static/css/");
    templateResolver.setSuffix(".css");
    return templateResolver;
}

@Bean
public SpringResourceTemplateResolver templateResolver() {
    SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
    templateResolver.setApplicationContext(applicationContext);
    templateResolver.setPrefix("classpath:/templates/");
    templateResolver.setSuffix(".html");
    return templateResolver;
}

@Bean
public SpringTemplateEngine templateEngine() {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.addTemplateResolver(templatecssResolver());
    templateEngine.setTemplateResolver(templateResolver());
    templateEngine.setEnableSpringELCompiler(true);
    return templateEngine;
}

@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
    ThymeleafViewResolver resolver = new ThymeleafViewResolver();
    resolver.setTemplateEngine(templateEngine());
    registry.viewResolver(resolver);
}

1条回答
相关推荐>>
2楼-- · 2019-08-23 13:18

You've to override the addResourceHandlers(..) method of the you calls that implements the WebMvcConfigurerAdapter not as a bean (SpringResourceTemplateResolver )

SO just add the overiding method

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

in your template use

<link href="<c:url value="/css/style.css" />" rel="stylesheet">

or using themleaf

<link th:href="@{/css/style.css}" />" rel="stylesheet">
查看更多
登录 后发表回答