Spring Boot —— Thymeleaf + Gradle run on Tomcat(war形式)

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,因为 放到tomat里面之后, Thymeleaf  就找不到默认的templates 模板路径了,所以这里需要重新指明一下,这个问题也困扰了我一下午加一晚上,刚刚才调完, 现在写篇博客记录下,后人谨记!!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值