Shi*_*aik 6 java freemarker spring-boot
我使用Spring Initilizr创建了一个Spring Boot Application。然后,我包括Apache's Freemarker模板引擎以从我的项目中加载模板。默认情况下,引擎从以下位置加载模板:src/main/resources/templates/文件夹。
我正在尝试index.ftl在用户访问网页时加载一个简单的文件作为模板http://localhost:8080。但是我需要从src/main/webapp/文件夹加载模板。每当我尝试从resources文件夹外部加载模板时,模板引擎都无法找到模板。
我经历了各种教程和堆栈溢出问题。没有人回答我的问题,我被困住了,404 ERROR因为引擎无法找到文件。
文件结构为:
|-src
|---main
|-----java
|-------MainApplication.java
|-------controllers
|---------ViewController.java
|-----resources
|-------static
|-------templates
|-------application.properties
|-----webapp
|-------index.ftl
Run Code Online (Sandbox Code Playgroud)
经过大量的挖掘,我遇到了一个帖子,他们建议更改模板引擎搜索文件的位置。建议在application.properties中添加以下行:
spring.freemarker.enabled=true
spring.freemarker.template-loader-path=classpath:src/main/webapp/
Run Code Online (Sandbox Code Playgroud)
这似乎根本不起作用。
当我访问位于http:// localhost:8080的网页时,我试图解析简单的索引页。我已经编写了以下代码来映射HTTP请求ViewController.java:
@RequestMapping("/")
public ModelAndView home(Model model)
{
return new ModelAndView("index");
}
Run Code Online (Sandbox Code Playgroud)
不知道我是完全搞错了还是错过了一些配置。
来自 Spring 文档:
如果您的应用程序打包为 jar,请勿使用 src/main/webapp 目录。尽管此目录是通用标准,但它仅适用于 war 打包,并且当您生成 war 时,大多数构建工具都会默默地忽略它。
src/main/webapp与web archive相关联,生成war时会被maven war插件打包。
假设您需要一个单独的位置来保存 ftl 模板,并且您仍然希望打包为 jar,您可以按照以下步骤操作。
在 pom 文件中的构建中添加资源条目,以便资源插件可以将该目录复制到类路径。
<build>
<resources>
<resource>
<directory>src/main/webapp</directory>
</resource>
<resources>
<build>
Run Code Online (Sandbox Code Playgroud)
更改加载器路径以从类路径的根目录读取。
spring.freemarker.template-loader-path=classpath:
Run Code Online (Sandbox Code Playgroud)
如果它仅适用于 ftl 模板,我会将目录更改为src/main/ftls避免混淆并更新资源中的相同目录。
更新
我其实想构建一个WAR部署包
你必须使用 war 插件来构建 war。添加插件并在pom.xml中将打包更改为war。
| 归档时间: |
|
| 查看次数: |
316 次 |
| 最近记录: |