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

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

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

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

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

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

@SpringBootApplication
public 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=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 模板路径了,所以这里需要重新指明一下,这个问题也困扰了我一下午加一晚上,刚刚才调完, 现在记录下,后人谨记!!

总结

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

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。