Spring Boot使用Thymeleaf + Gradle构建war到Tomcat
SpringBoot以Jar的方式部署启动,这个不用介绍了,之前也介绍了关于SpringBoot+thymeleaf的简单使用,但是今天遇到一个问题,我先描述下问题的场景:
由于运维部门的需求,项目需要以war的形式放到tomcat运行 ,而不是原定的jar的方式运行
配置了一下午,也查了一下午的资料,以war的方式在Tomcat能运行,并且能访问Controller,但是在返回html视图时,找不到视图模板。最终发现问题在Thymeleaf的配置,话不多说,具体看操作步骤:
1、Springboot容器配置需要继承 SpringBootServletInitializer
这里我继承的是web.suport下面的SpringBootServletInitializer。
@SpringBootApplication publicclassApplicationextendsSpringBootServletInitializer{ @Override protectedSpringApplicationBuilderconfigure(SpringApplicationBuilderapplication){ returnapplication.sources(Application.class); } publicstaticvoidmain(String[]args)throwsException{ SpringApplication.run(Application.class,args); } }
2、更新你的MavenorGradle打包方式配置
下一步是更新你的构建配置,这样你的项目将产生一个war包而不是jar包。如果你使用Maven,并使用spring-boot-starter-parent(为了配置Maven的war插件),所有你需要做的就是更改pom.xml的packaging为war:
war
如果你使用Gradle,你需要修改build.gradle来将war插件应用到项目上:
applyplugin:'war'
3、确保内嵌的servlet容器不能干扰war包将部署的servlet容器
为了达到这个目的,你需要将内嵌容器的依赖标记为provided。
如果使用Maven:
org.springframework.boot spring-boot-starter-tomcat provided
如果使用Gradle:
dependencies{ //… providedRuntime'org.springframework.boot:spring-boot-starter-tomcat' //… }
以上步骤配置好,mavenorGradle在build的时候就会打成war包,这里可能还需要注意一个编码的问题,这个就大家自己去找了,具体详情参照:Spring源码
配置好这些,确实能在Tomcat启动了,但是对于Controller返回页面视图,却还不够,还需要配置模板的参数,这里我使用的是Thymeleaf,所以就介绍Thymeleaf的配置方式
4、Thymeleaf的配置
如果你是用的.properties方式配置的参数,那么只需要在你的application.properties配置下面加上:
#THYMELEAF(ThymeleafAutoConfiguration) spring.thymeleaf.check-template-location=true spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html spring.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模板路径了,所以这里需要重新指明一下,这个问题也困扰了我一下午加一晚上,刚刚才调完,现在记录下,后人谨记!!
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接