好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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 。

?

1

2

3

4

5

6

7

8

9

10

@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 :

?

1

<packaging>war</packaging>

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

?

1

apply plugin: 'war'

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

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

如果使用 maven :

?

1

2

3

4

5

6

7

8

9

<dependencies>

   <!-- … -->

   <dependency>

     <groupid>org.springframework.boot</groupid>

     <artifactid>spring-boot-starter-tomcat</artifactid>

     <scope>provided</scope>

   </dependency>

   <!-- … -->

</dependencies>

如果使用 gradle :

?

1

2

3

4

5

dependencies {

   // …

   providedruntime 'org.springframework.boot:spring-boot-starter-tomcat'

   // …

}

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

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

4、thymeleaf 的配置

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

?

1

2

3

4

5

6

7

8

# 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 里面配置如下参数:

?

1

2

3

4

5

6

7

8

9

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

总结

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

原文链接:https://blog.csdn.net/moneyshi/article/details/53524533

查看更多关于Spring Boot使用Thymeleaf + Gradle构建war到Tomcat的详细内容...

  阅读:7次