Spring Boot使用Thymeleaf + Gradle构建war到Tomcat

时间:2021-05-20

Spring Boot 以Jar的方式部署启动,这个不用介绍了, 之前也介绍了关于 Spring Boot + thymeleaf 的简单使用 ,但是今天遇到一个问题, 我先描述下问题的场景:

由于运维部门的需求,项目需要以war的形式放到tomcat运行,而不是原定的jar的方式运行

配置了一下午,也查了一下午的资料,以war的方式在Tomcat能运行,并且能访问Controller,但是在返回html视图时,找不到视图模板。最终发现问题在Thymeleaf的配置,话不多说,具体看操作步骤:

1、Spring boot 容器配置需要继承SpringBootServletInitializer

这里我继承的是web.suport下面的SpringBootServletInitializer。

@SpringBootApplicationpublic class Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); }}

2、更新你的Maven or Gradle 打包方式配置

下一步是更新你的构建配置,这样你的项目将产生一个war包而不是jar包。如果你使用Maven,并使用spring-boot-starter-parent(为了配置Maven的war插件),所有你需要做的就是更改pom.xml的packaging为war:

<packaging>war</packaging>

如果你使用Gradle,你需要修改build.gradle来将war插件应用到项目上:

apply plugin: 'war'

3、确保内嵌的servlet容器不能干扰war包将部署的servlet容器

为了达到这个目的,你需要将内嵌容器的依赖标记为provided。

如果使用Maven:

<dependencies> <!-- … --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <!-- … --></dependencies>

如果使用Gradle:

dependencies { // … providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat' // …}

以上步骤配置好,maven or Gradle 在build的时候就会打成war包,这里可能还需要注意一个编码的问题,这个就大家自己去找了,具体详情参照:Spring 源码

配置好这些,确实能在Tomcat启动了,但是对于Controller返回页面视图,却还不够,还需要配置模板的参数,这里我使用的是Thymeleaf ,所以就介绍Thymeleaf 的配置方式

4、Thymeleaf 的配置

如果你是用的.properties方式配置的 参数,那么只需要在你的application.properties配置下面加上:

# THYMELEAF (ThymeleafAutoConfiguration)spring.thymeleaf.check-template-location=truespring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.suffix=.htmlspring.thymeleaf.mode=HTML5spring.thymeleaf.encoding=UTF-8spring.thymeleaf.content-type=text/htmlspring.thymeleaf.cache=false

每一个配置项的具体意思就自己去查了,这里不细说, 如果你是用.yml的方式进行配置项的话,那么需要在application.yml里面配置如下参数:

spring: thymeleaf: cache: false check-template-location: true prefix: classpath:/templates/ suffix: .html mode: HTML5 encoding: UTF-8 content-type: text/html

其实重要的就是prefix,因为放到tomcat里面之后,Thymeleaf就找不到默认的templates 模板路径了,所以这里需要重新指明一下,这个问题也困扰了我一下午加一晚上,刚刚才调完, 现在记录下,后人谨记!!

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章