gpt4 book ai didi

java - TemplateEngine 未在模板文件夹中查找文件

转载 作者:行者123 更新时间:2023-11-30 06:04:58 24 4
gpt4 key购买 nike

我正在构建一个 SpringBoot 应用程序,该应用程序从数据库加载国际化消息。(Followed this tutorial)

由此,我必须创建一个 ThymeleafConfiguration 类并设置一个 SpringTemplateEngine Bean。本教程仅给出了有关此配置的粗略想法(仅配置了消息源,但没有配置其他模板引擎配置),因此它破坏了我的 Controller 页面渲染( Controller 现在返回字符串而不是 View )。

我正在尝试配置 TemplateEngine 的其余部分(例如 TemplateResolver,我认为这是渲染不正确的原因),但是,我不知道如何正确执行它[我保留收到“模板解析期间发生错误(模板:“ServletContext 资源 [/templates/login.html]”)”消息]。

如何正确配置SpringTemplateEngine?

到目前为止我的配置:

@Configuration
public class ThymeleafConfiguration implements WebMvcConfigurer, ApplicationContextAware{

private ApplicationContext applicationContext;

@Autowired
private DatabaseMessageSource databaseMessageSource;

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

private ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}


@Bean
public SpringTemplateEngine thymeleafTemplateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver());
engine.setTemplateEngineMessageSource(databaseMessageSource);
return engine;
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;

}

}

Controller 类:

 @Controller
public class ApplicationController {


@RequestMapping("/home")
public String home() {
return "/home.html";
}


@RequestMapping("/core/index")
public String index() {
return "/core/index.html";
}

@RequestMapping("/login")
public String login() {
return "login";
}

File structure

最佳答案

问题在于

private ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/templates/"); // Here!!!
resolver.setSuffix(".html");
return resolver;
}

由于模板位于 src/main/resources 中,因此必须指向类路径,如下所示:

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

此外,从接口(interface)到实现类有一些变化,但不会影响结果。

关于java - TemplateEngine 未在模板文件夹中查找文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51526162/

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