web后端开发进阶

一、开发规范

1.前后端分离

  • image-20251031181207686

  • 接口文档统一开发接口

  • 进行测试时,可以使用俩款软件进行模拟彼此实现效果(接口测试)

    • Postmen
    • Apifox
  • 后端直接运行tomcat服务器就欧克

  • 前端需要运行nginx服务器

2.开发风格

  • Restful风格

    • 传统风格利用url名字确定执行方法

    • image-20251031181423192

    • restful风格

      • image-20251031181618476

      • 通过请求方法来确定执行含义,避免不同程序员命名方式而造成混乱

      • 1.REST是风格,是约定方式,约定不是规定,可以打破。

        2.描述功能模块通常使用复数形式(加s),表示此类资源,而非单个资源。如:users、books…

3.工程搭建

  • 创建空项目

    • 配置jdk
      • 设置->项目结构
    • 配置maven
      • 构建->构建工具->maven、
    • 文件编码
      • utf-8
  • 创建SpringBoot工程,并引入web开发起步依赖、mybatis、mysql驱动、lombok。

    • 创建项目时如果没有出现,等待依赖下载完成即可
    • 删除多余配置文件
    • 更改配置文件为yml格式
  • 创建数据库表dept,并在application.yml中配置数据库的基本信息。

    • spring:
        application:
          name: tlias_web
      
        datasource:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:
          username: 
          password: 
      
      mybatis:
        configuration:
          log-impl: org.apache.ibatis.logging.stdout.StdOutImpl //数据库操作回显
      
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35

      * **准备基础代码结构,并引入实体类Dept及统一的响应结果封装类 Result。**

      * ~~~java

      @Data
      public class Result {

      private Integer code; //编码:1成功,0为失败
      private String msg; //错误信息
      private Object data; //数据

      public static Result success() {
      Result result = new Result();
      result.code = 1;
      result.msg = "success";
      return result;
      }

      public static Result success(Object object) {
      Result result = new Result();
      result.data = object;
      result.code = 1;
      result.msg = "success";
      return result;
      }

      public static Result error(String msg) {
      Result result = new Result();
      result.msg = msg;
      result.code = 0;
      return result;
      }

      }
    • 规范返回数据

    • dept类对象属性命名为驼峰命名

  • 结构如图

    • image-20251031204912498

二、功能实现

1.知识点

  • 如果请求路径公共,我们可以直接将其加到类之前进行注解

    • @RequestMapping("/depts")
      @RestController
      public class DeptController {
          @Autowired
          private DeptService deptService;
      
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11

      * **完整路径为类上的加上方法上的**

      * **路径变量型传参**

      * ~~~java
      @GetMapping("depts/{id}")//使用这个占位符
      public Result findbyid(@PathVariable Integer id){
      Dept dept = deptService.findbyid(id);
      return Result.success(dept);
      }
    • @PathVariable注解

    • 多个参数如图

      • image-20251101171535644
  • 提前实现依赖注入与控制管理

    • controller层
          
      public class DeptController {
          @Autowired
          private DeptService deptService;  //依赖注入service对象
      
      service层
          
      public class DeptServiceimpl implements DeptService {
          @Autowired
          private DeptMapper deptmapper;//依赖注入 mapper接口
      
      1
      2
      3
      4
      5
      6

      * **实现单一方式请求**

      * ~~~java
      1.@RequestMapping(value = "/depts",method = RequestMethod.GET)
      2.@GetMapping("/depts") //衍生注解直接实现
  • 数据封装

    • 如果字段名与属性名相同可以自动识别,不同的话以下方法解决

    • 1.使用results注解
          @Results({
              @Result(column = "create_time",property = "createTime"),
              @Result(column = "update_time",property = "updateTime")
          })
          @Select("select id, name, create_time, update_time from dept order by update_time desc")
          List<Dept> findall();
      2.查询时起别名(在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样。)
          @Select("select id, name, create_time createTime, update_time updateTime from dept order by update_time desc")
      3.开启驼峰命名开关
          mybatis:
                configuration: 
                  map-underscore-to-camel-case: true
      
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10

      * **获取参数**

      * **通过原始HttpServletRequest对象**

      * ~~~java
      @DeleteMapping("/depts")
      public Result delete(HttpServletRequest request){
      String idStr = request.getParameter("id");
      int id = Integer.parseInt(idStr);
    • 通过RequestParam注解实现

      • public Result delete(@RequestParam("id")Integer id){
                deptService.delete(id);
                return Result.success();
            }
        定义后必须给参数,否则报错(required参数默认为true)
        
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12

        * **如果参数与形参名字相同**

        * **直接省略**

        * ~~~java
        @DeleteMapping("/depts")
        public Result delete(Integer id){

        deptService.delete(id);
        return Result.success();
        }
  • json传参

    • JSON数据的键名与方法形参对象的属性名相同,并需要使用@RequestBody注解标识。

    •     @PostMapping("/depts")
          public Result add(@RequestBody Dept dept){
              deptService.add(dept);
              return Result.success();
          }
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10

      *

      ### 2.前端nginx环境

      * **目录结构**

      * ~~~shell
      conf为配置文件
      html为前端文件
  • 反向代理

    • image-20251031222759085

    • 通过网络收集

      • http://127.0.0.1:90/api/depts
        
        1
        2
        3
        4
        5
        6
        7
        8

        * **配置文件**

        * ~~~shell
        location ^~ /api/ {
        rewrite ^/api/(.*)$ /$1 break; //重写请求路径
        proxy_pass http://localhost:8080; //真实路径
        }
    • 安全、灵活、负载均衡

3.查询部门

  • DeptController

    • @RequestMapping("/depts")
      public Result findall(){
          System.out.println("查询全部部门数据");
          List<Dept> deptList = deptService.findall();
          return Result.success(deptList);
      }
      
      1
      2
      3
      4
      5
      6
      7

      * **DeptServiceimpl**

      * ~~~java
      public List<Dept> findall() {
      return deptmapper.findall();
      }
  • DeptMapper

    • @Mapper
      public interface DeptMapper {
          @Select("select id, name, create_time, update_time from dept order by update_time desc")
          List<Dept> findall();
      }
      
      1
      2
      3
      4

      * ~~~shell
      访问http://127.0.0.1:8080/depts
      实现接口

4.删除部门

  • DeptController

    •     @DeleteMapping("/depts")
          public Result delete(Integer id){
      
              deptService.delete(id);
              return Result.success();
          }
      
      1
      2
      3
      4
      5
      6
      7
      8

      * **DeptServiceimpl**

      * ~~~java
      @Override
      public void delete(Integer id) {
      deptmapper.delete(id);
      }
  • DeptMapper

    •     @Delete("delete from dept where id = #{id}")
          void delete(Integer id);
      
      1
      2
      3
      4

      * ~~~shell
      访问http://127.0.0.1:8080/depts
      实现接口

5.新增部门

  • DeptController

    •     @PostMapping("/depts")
          public Result add(@RequestBody Dept dept){
              deptService.add(dept);
              return Result.success();
          }
      
      1
      2
      3
      4
      5
      6
      7
      8
      9

      * **DeptServiceimpl**

      * ~~~java
      public void add(Dept dept) {
      dept.setCreateTime(LocalDateTime.now());
      dept.setUpdateTime(LocalDateTime.now());
      deptmapper.add(dept);
      }
  • DeptMapper

    •     @Insert("insert into dept (name,update_time,create_time) values (#{name},#{updateTime},#{createTime})")
          void add(Dept dept);
      
      1
      2
      3
      4

      * ~~~shell
      访问http://127.0.0.1:8080/depts
      实现接口

6.新增部门

  • 查询回显

    • DeptController

      •    @GetMapping("depts/{id}")
            public Result findbyid(@PathVariable Integer id){
                Dept dept = deptService.findbyid(id);
                return Result.success(dept);
            }
        
        1
        2
        3
        4
        5
        6
        7
        8
        9

        * **DeptServiceimpl**

        * ~~~java
        @Override
        public Dept findbyid(Integer id) {
        Dept dept = deptmapper.findbyid(id);
        return dept;
        }
    • DeptMapper

      • @Select("select id, name, create_time, update_time from dept where id = #{id}")
            Dept findbyid(Integer id);
        
        1
        2
        3
        4

        * ~~~shell
        访问http://127.0.0.1:8080/depts
        实现接口
  • 修改操作

    • DeptController

      •     @PutMapping("/depts")
            public Result update(@RequestBody Dept dept){
                deptService.update(dept);
                return Result.success();
            }
        
        1
        2
        3
        4
        5
        6
        7
        8
        9

        * **DeptServiceimpl**

        * ~~~java
        @Override
        public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptmapper.update(dept);
        }
    • DeptMapper

      •     @Update("update dept set name=#{name},update_time=#{updateTime} where id=#{id}")
            void update(Dept dept);
        
        1
        2
        3
        4

        * ~~~shell
        访问http://127.0.0.1:8080/depts
        实现接口

三、日志功能

  • 通过lobbok包可以直接实现

    • @Slf4j
      注解即可
      
      1
      2
      3
      4

      * **拼接字符串可以使用占位方式实现**

      * ~~~java

1.日志技术

  • image-20251101183553307

  • slf4j为接口门户,提供所有的标准

2.实现

  • 引入依赖

    • <dependency>
      <groupId>ch.qos.logback</groupId>   
      <artifactId>logback-classic</artifactId>
      <version>1.4.11</version>
      </dependency>
      
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57

      * **配置文件**

      * **logback.xml**

      * **记录日志**

      * ```java
      public class LogTest {
      private static final Logger log = LoggerFactory.getLogger(LogTest.class);
      @Test
      public void testLog(){
      System.out.println(LocalDateTime.now() + " : 开始计算...");
      log.info("开始计算...");
      }
      }
      ```

      ### 3.配置文件

      * **logback.xml**

      * ~~~shell
      <?xml version="1.0" encoding="UTF-8"?>
      <configuration>
      <!-- 控制台输出 -->
      <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
      <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
      <!--格式化输出:%d 表示日期,%thread 表示线程名,%-5level表示级别从左显示5个字符宽度,%logger显示日志记录器的名称, %msg表示日志消息,%n表示换行符 -->
      <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}-%msg%n</pattern>
      </encoder>
      </appender>

      <!-- 系统文件输出 -->
      <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
      <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
      <!-- 日志文件输出的文件名, %i表示序号 -->
      <FileNamePattern>D:/tlias-%d{yyyy-MM-dd}-%i.log</FileNamePattern>
      <!-- 最多保留的历史日志文件数量 -->
      <MaxHistory>30</MaxHistory>
      <!-- 最大文件大小,超过这个大小会触发滚动到新文件,默认为 10MB -->
      <maxFileSize>10MB</maxFileSize>
      </rollingPolicy>

      <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
      <!--格式化输出:%d 表示日期,%thread 表示线程名,%-5level表示级别从左显示5个字符宽度,%msg表示日志消息,%n表示换行符 -->
      <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}-%msg%n</pattern>
      </encoder>
      </appender>

      <!-- 日志输出级别 -->
      <root level="ALL">
      <appender-ref ref="STDOUT" />
      <appender-ref ref="FILE" />
      </root>
      </configuration>

4.日志级别

  • image-20251101201527008
  • 上述级别由低到高
  • All开启所有日志,OFF为关闭所有日志,开关为级别则代表展示某某某以上的界别