配置文件配置
将 application.properties 改为 application.yml ,写法不一样,本人比较习惯用 yaml 格式。
 配置项目名称和项目端口号。
application.yml
server:
  port: 8888
spring:
  application:
    name: system
配置外置 Servlet 容器
如果要在 Tomcat 容器中显示页面,则需要在启动类配置外置的 Servlet 容器。
SystemApplication.java
package com.lm.system;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class SystemApplication extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication.run(SystemApplication.class, args);
    }
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SystemApplication.class);
    }
}
Tomcat 依赖配置
因为需要将项目打成 war 包,放置到外置 tomcat 中,所以在 pom.xml 文件中,将 spring-boot-starter 依赖内置的 tomcat 依赖单独写出来,spring-boot-tomcat 依赖的标签改为,改为打包时打包 tomcat 依赖,如下依赖加在标签中,修改完改文件需要重新加载该 Maven 项目。
pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>
Web 依赖配置
如下依赖加在标签中,修改完改文件需要重新加载该 Maven 项目。
<!--   web起步依赖    -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
编写测试接口
1)在system目录下,新建 controller 目录,在 controller 目录下新建 HelloController 类。
  2)编写 Hello 接口,使用浏览器进行访问。
2)编写 Hello 接口,使用浏览器进行访问。
package com.lm.system.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * @Author: DuHaoLin
 * @Date: 2024/7/26
 */
@RestController
public class HelloController {
    @GetMapping("hello")
    public String hello() {
        return "hello";
    }
}
3)访问效果图
 
项目打包
打 war 包,放到本地的 tomcat 上。
 1)双击 Ctrl 按钮,显示 Run Anything 框,输入 Maven 命令:mvn clean package,先清除已经存在的 target,再打包。
 
 2)如果报该【错误: 无效的目标发行版:17】,则需要看 Settings 中,Java Compiler 的下图标记出是否变回17,如果是则需要改为11,还有右边的 Maven 栏位的 Profiles 栏位的 jdk-17 是否被勾上,如果被勾上则需要取消掉,不能勾上,再重新打包。
 
 
 3)默认打包后的名称为项目名加上版本号,可以在 pom.xml 的标签中加是 system 标签来指定打包后的包名,打包后控制台回返回包路径,可以按该路径找到打包后的 war 包。
 
 4)将该 war 包放到本地的 tomcat 中,启动 tomcat 进行访问(tomcat中bin目录下,双击startup.bat)。
 
 5)在 tomcat 中,只有启动时显示图中的 Spring 图标才算启动成功,不然就是启动失败,需要查看日志进行修复。如果启动 tomcat 时,直接闪退可能是安装时,系统环境参数配置错误,或者是端口号被占用。
  6)在 tomcat 中访问该接口,需要加是项目名称,项目名称不能为驼峰命名,否则可能访问不到,页面回404。
6)在 tomcat 中访问该接口,需要加是项目名称,项目名称不能为驼峰命名,否则可能访问不到,页面回404。
 驼峰命名如 webSystem,此时 tomcat 就访问不到项目。
 



















