允许 Apache 的 FreeMarker 模板引擎从外部资源文件夹加载模板

我使用 Spring Initilizr 创建了一个 Spring Boot 应用程序。然后我包含了Apache's Freemarker模板引擎来从我的项目中加载模板。引擎默认从以下位置加载模板:src/main/resources/templates/文件夹。


index.ftl当用户访问网页时,我试图加载一个简单的文件作为模板http://localhost:8080。但我需要从文件夹加载模板src/main/webapp/。每当我尝试从文件夹外部加载模板时resources,模板引擎都无法找到模板。


我已经阅读了各种教程和 Stack Overflow 问题。没有人回答我的问题,我被困住了,404 ERROR因为引擎无法找到文件。


文件结构为:


|-src

|---main

|-----java

|-------MainApplication.java

|-------controllers

|---------ViewController.java

|-----resources

|-------static

|-------templates

|-------application.properties

|-----webapp

|-------index.ftl

经过大量挖掘,我发现了一篇帖子,他们建议更改模板引擎搜索文件的位置。它建议在 application.properties 中添加以下行:


spring.freemarker.enabled=true

spring.freemarker.template-loader-path=classpath:src/main/webapp/

这似乎根本不起作用。


当我访问http://localhost:8080 的网页时,我试图解析简单的索引页面。我编写了以下代码来映射 HTTP 请求ViewController.java:


@RequestMapping("/")

public ModelAndView home(Model model)

{

    return new ModelAndView("index");

}

不知道我是完全弄错了还是错过了一些配置。


皈依舞
浏览 196回答 2
2回答

慕后森

来自 Spring 文档:如果您的应用程序打包为 jar,请不要使用 src/main/webapp 目录。虽然这个目录是一个通用标准,但它只适用于 war 打包,并且在生成 war 时它会被大多数构建工具默默地忽略。src/main/webapp与web archive关联,生成war时会被maven war plugin打包。假设您需要一个单独的位置来保存 ftl 模板,并且您仍然希望打包为 jar,您可以按照以下步骤操作。在构建的 pom 文件中添加资源条目,以便资源插件可以将该目录复制到类路径。<build> &nbsp;&nbsp;&nbsp;&nbsp;<resources> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<resource> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<directory>src/main/webapp</directory> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</resource> &nbsp;&nbsp;&nbsp;&nbsp;<resources> <build>更改加载程序路径以从类路径的根目录读取。spring.freemarker.template-loader-path=classpath:如果它仅适用于 ftl 模板,我会将目录更改为src/main/ftls以避免混淆并在资源中更新相同的目录。更新其实我想构建一个WAR部署包你必须使用战争插件来建立战争。添加插件并在pom.xml中将包装更改为war。有关传统部署的更多信息:https://docs.spring.io/spring-boot/docs/current/reference/html/howto-traditional-deployment.html#howto-create-a-deployable-war-file

哆啦的时光机

编辑在嵌入式 tomcat 中,您可以在应用程序属性中定义静态资源路径&nbsp;spring.mvc.static-path-pattern=如果部署到 tomcat,在 tomcat 中使用可以在 server.xml 内部定义可以保存 freemarker 文件的静态上下文,如&nbsp;<Context&nbsp;docBase="/home/stuff"&nbsp;path="/static"&nbsp;/><Context>在元素内部添加一个元素<Host>。Context 有两个属性:docBase 是磁盘上包含您的静态文件的目录,path 是您要在其上提供文件的 URL。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java