Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper location of Thymeleaf views for Spring

I am running a spring boot application with Thymeleaf. When I run the application through my IDE (IntelliJ) everything runs fine. However, when I run the application through the command line (java -jar) the views do not resolve and I get the following error:

org.thymeleaf.exceptions.TemplateInputException: Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers
    at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:245)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011)
    at org.thymeleaf.spring3.view.ThymeleafView.renderFragment(ThymeleafView.java:335)
    at org.thymeleaf.spring3.view.ThymeleafView.render(ThymeleafView.java:190)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1225)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1012)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)

Here are my settings:

My Directory Structure

PROJECT-ROOT
  --src
    --main
      --java
        --controllers
          --[CLASS WITH MAIN METHOD]
        --views
          --index.html

My template resolver:

@Bean
  public ViewResolver viewResolver() {
    ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
    templateResolver.setTemplateMode("XHTML");
    templateResolver.setPrefix("views/");
    templateResolver.setSuffix(".html");
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setTemplateResolver(templateResolver);

    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    viewResolver.setTemplateEngine(engine);
    return viewResolver;
  }

Where should I put the views so that they can be correctly resolved when ran from a jar file?

like image 560
Nick Humrich Avatar asked Feb 02 '26 20:02

Nick Humrich


1 Answers

I think the answer is that it depends on your build configuration. The directory "src/main/views" is not a standard resource location for any common build tool, so you would have to explicitly add it to the configuration of the tool you use to build your jar.

If I were you I would go with the flow (why be different?), and just use "src/main/resources" for classpath resources. I would also leave out the thymeleaf configuration completely and let Spring Boot handle it, putting my templates in "src/main/resources/templates".

like image 199
Dave Syer Avatar answered Feb 05 '26 09:02

Dave Syer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!