SpringBoot项目使用外置tomcat

本文介绍如何将SpringBoot项目调整为可以部署在独立Tomcat服务器上的WAR包形式,并配置Thymeleaf模板引擎以支持页面视图的正确加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们知道SpringBoot使用的内置默认的tomcat,缺点好像是不支持jsp还是什么,但是在发布环节还是要放到tomcat中

第一步修改启动类
继承 SpringBootServletInitializer类并且重写* configure*方法


@SpringBootApplication
public class Application extends SpringBootServletInitializer{

    @Override  
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {  
        return application.sources(Application.class);  
    }  

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

之前的保持不变,然后让它继承SpringBootServletInitializer类,添加一个config方法。

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

    <packaging>war</packaging>  
apply plugin: 'war'  

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

    <dependencies>  
        <!-- … -->  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-tomcat</artifactId>  
            <scope>provided</scope>  
        </dependency>  
        <!-- … -->  
    </dependencies>  
    dependencies {  
        // …  
        providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'  
        // …  
    }  

maven or Gradle 在build的时候就会打成war包,这里可能还需要注意一个编码的问题

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

# 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
    spring:  
      thymeleaf:  
        cache: false  
        check-template-location: true  
        prefix: classpath:/templates/  
        suffix: .html  
        mode: HTML5  
        encoding: UTF-8  
        content-type: text/html  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值