当前位置:   article > 正文

【SpringBoot3+Vue3】二【实战篇】-后端

springboot3+vue3

目录

一、环境搭建

1、数据库脚本

2、pom

3、yml

4、通过mybatis-X生成实体pojo等

4.1 Article

4.2 Category

4.3 User

5、 Mapper

5.1 ArticleMapper

5.2 CategoryMapper

5.3 UserMapper

6、service

6.1 ArticleService

6.2 CategoryService

6.3 UserService

7、serviceImpl

7.1 ArticleServiceImpl

7.2 CategoryServiceImpl

7.3 UserServiceImpl

8、统一返回类Result

9、工具类

9.1 MD5加密工具类Md5Util

9.2 jwt生成token工具类JwtUtils 

9.3 工具类ThreadLocalUtil

 9.4 AliOSSProperties阿里云参数实体

9.5 阿里云AliOSSUtils

10、全局异常处理类GlobalExceptionHandler

11、拦截器LoginCheckInterceptor

12、配置类

 12.1 配置类WebConfig注册拦截器

12.2   MybatisPlus分页配置类MybatisPlusConfig

13、自定义注解(新增文章)

13.1 新增文章自定义注解State接口

13.2 新增文章自定义注解实现类StateValidation

14、封装分页实体PageBean

二、用户

1、注册

1.1 UserController

1.2 service

1.3 serviceImpl

2、登录

2.1 UserController

2.2 登录认证 

3、获取用户详细信息

3.1 UserController

 3.2 servcie

3.3 servcieImpl

3.4 优化版本UserController(使用ThreadLocal)

4、更新用户基本信息

4.1 UserController

4.2 servcie

4.3 serviceImpl

5、更新用户头像

5.2 UserController 

5.2 servcie

5.3 servcieImpl

6、更新用户密码

6.1 UserController

6.2 service

6.3 serviceImpl

三、文章分类

1、新增文章分类

1.1 CategoryController

1.2 service

1.3 servcieImpl

2、文章分类列表

2.1 CategoryController

2.2 service

2.3 servcieImpl

3、 获取文章分类详情

3.1 CategoryController

3.2 service

3.3 servcieImpl

4、更新文章分类

4.1 CategoryController

4.2 service

4.3 servcieImpl

5、删除文章分类

5.1 CategoryController

5.2 service

5.3 servcieImpl

四、文章管理

1、新增文章

1.1 ArticleCtroller

1.2 service

1.3 serviceImpl

2、文章列表(条件分页)

2.1 ArticleCtroller

2.2 service

2.3 serviceImpl

3、获取文章详情

3.1 ArticleCtroller

3.2 service

3.3 serviceImpl

4、更新文章

4.1 ArticleCtroller

4.2 service

4.3 serviceImpl

5、删除文章

5.1 ArticleCtroller

5.2 service

5.3 serviceImpl

五、上传接口

1、FileUploadController


前言:SpringBoot3+Vue3项目实战-后端

一、环境搭建

1、数据库脚本

  1. -- 用户表
  2. create table user (
  3. id int unsigned primary key auto_increment comment 'ID',
  4. username varchar(20) not null unique comment '用户名',
  5. password varchar(32) comment '密码',
  6. nickname varchar(10) default '' comment '昵称',
  7. email varchar(128) default '' comment '邮箱',
  8. user_pic varchar(128) default '' comment '头像',
  9. create_time datetime not null comment '创建时间',
  10. update_time datetime not null comment '修改时间'
  11. ) comment '用户表';
  12. -- 分类表
  13. create table category(
  14. id int unsigned primary key auto_increment comment 'ID',
  15. category_name varchar(32) not null comment '分类名称',
  16. category_alias varchar(32) not null comment '分类别名',
  17. create_user int unsigned not null comment '创建人ID',
  18. create_time datetime not null comment '创建时间',
  19. update_time datetime not null comment '修改时间',
  20. constraint fk_category_user foreign key (create_user) references user(id) -- 外键约束
  21. );
  22. -- 文章表
  23. create table article(
  24. id int unsigned primary key auto_increment comment 'ID',
  25. title varchar(30) not null comment '文章标题',
  26. content varchar(10000) not null comment '文章内容',
  27. cover_img varchar(128) not null comment '文章封面',
  28. state varchar(3) default '草稿' comment '文章状态: 只能是[已发布] 或者 [草稿]',
  29. category_id int unsigned comment '文章分类ID',
  30. create_user int unsigned not null comment '创建人ID',
  31. create_time datetime not null comment '创建时间',
  32. update_time datetime not null comment '修改时间',
  33. constraint fk_article_category foreign key (category_id) references category(id),-- 外键约束
  34. constraint fk_article_user foreign key (create_user) references user(id) -- 外键约束
  35. )

2、pom

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>3.1.5</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.bocai</groupId>
  12. <artifactId>mybatis-plus-module</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>mybatis-plus-module</name>
  15. <description>mybatis-plus-module</description>
  16. <properties>
  17. <java.version>17</java.version>
  18. <aliyun-sdk-oss.version>3.15.1</aliyun-sdk-oss.version>
  19. <jaxb-api.version>2.3.1</jaxb-api.version>
  20. <activation.version>1.1.1</activation.version>
  21. <jaxb-runtime.version>2.3.3</jaxb-runtime.version>
  22. <mybatis-plus.version>3.5.3</mybatis-plus.version>
  23. <druid.version>1.1.23</druid.version>
  24. <jjwt.version>0.9.0</jjwt.version>
  25. <fastjson.version>1.2.76</fastjson.version>
  26. </properties>
  27. <dependencies>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-web</artifactId>
  31. </dependency>
  32. <dependency>
  33. <groupId>com.mysql</groupId>
  34. <artifactId>mysql-connector-j</artifactId>
  35. <scope>runtime</scope>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.projectlombok</groupId>
  39. <artifactId>lombok</artifactId>
  40. <optional>true</optional>
  41. </dependency>
  42. <dependency>
  43. <groupId>org.springframework.boot</groupId>
  44. <artifactId>spring-boot-starter-test</artifactId>
  45. <scope>test</scope>
  46. </dependency>
  47. <!-- 校验 引入validation -->
  48. <dependency>
  49. <groupId>org.springframework.boot</groupId>
  50. <artifactId>spring-boot-starter-validation</artifactId>
  51. </dependency>
  52. <!-- 3、 引入mybatisplus -->
  53. <dependency>
  54. <groupId>com.baomidou</groupId>
  55. <artifactId>mybatis-plus-boot-starter</artifactId>
  56. <version>${mybatis-plus.version}</version>
  57. </dependency>
  58. <dependency>
  59. <groupId>com.alibaba</groupId>
  60. <artifactId>druid-spring-boot-starter</artifactId>
  61. <version>${druid.version}</version>
  62. </dependency>
  63. <!-- 阿里云OSS依赖-->
  64. <dependency>
  65. <groupId>com.aliyun.oss</groupId>
  66. <artifactId>aliyun-sdk-oss</artifactId>
  67. <version>${aliyun-sdk-oss.version}</version>
  68. </dependency>
  69. <!-- 如果是java9 还需要下面几个依赖 本项目按理不需要-->
  70. <dependency>
  71. <groupId>javax.xml.bind</groupId>
  72. <artifactId>jaxb-api</artifactId>
  73. <version>${jaxb-api.version}</version>
  74. </dependency>
  75. <dependency>
  76. <groupId>javax.activation</groupId>
  77. <artifactId>activation</artifactId>
  78. <version>${activation.version}</version>
  79. </dependency>
  80. <!-- no more than 2.3.3-->
  81. <dependency>
  82. <groupId>org.glassfish.jaxb</groupId>
  83. <artifactId>jaxb-runtime</artifactId>
  84. <version>${jaxb-runtime.version}</version>
  85. </dependency>
  86. <!-- 上面都是阿里云的 依赖- -->
  87. <!--JWT令牌-->
  88. <dependency>
  89. <groupId>io.jsonwebtoken</groupId>
  90. <artifactId>jjwt</artifactId>
  91. <version>${jjwt.version}</version>
  92. </dependency>
  93. <dependency>
  94. <groupId>com.alibaba</groupId>
  95. <artifactId>fastjson</artifactId>
  96. <version>${fastjson.version}</version>
  97. </dependency>
  98. </dependencies>
  99. <build>
  100. <plugins>
  101. <plugin>
  102. <groupId>org.springframework.boot</groupId>
  103. <artifactId>spring-boot-maven-plugin</artifactId>
  104. <configuration>
  105. <image>
  106. <builder>paketobuildpacks/builder-jammy-base:latest</builder>
  107. </image>
  108. <excludes>
  109. <exclude>
  110. <groupId>org.projectlombok</groupId>
  111. <artifactId>lombok</artifactId>
  112. </exclude>
  113. </excludes>
  114. </configuration>
  115. </plugin>
  116. </plugins>
  117. </build>
  118. </project>

3、yml

  1. spring:
  2. datasource:
  3. type: com.alibaba.druid.pool.DruidDataSource
  4. driver-class-name: com.mysql.cj.jdbc.Driver
  5. url: jdbc:mysql://localhost:3306/springboot_vue?serverTimezone=UTC
  6. username: root
  7. password: Miami
  8. main:
  9. banner-mode: off # 关闭控制台springboot的logo
  10. mybatis-plus:
  11. configuration:
  12. map-underscore-to-camel-case: true # 在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射
  13. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 控制台显示sql
  14. default-enum-type-handler: com.baomidou.mybatisplus.core.handlers.MybatisEnumTypeHandler # 配置全局枚举处理器,好像还有说json的
  15. global-config:
  16. db-config:
  17. id-type: auto # 数据库id生产规则全局 配置 # ASSIGN_ID雪花算法,数据库id建议使用Long类型
  18. logic-delete-field: deleted # 全局配置逻辑删除字段名
  19. logic-delete-value: 0 # 全局配置# 逻辑已删除值(默认为 1)这里因为我是反的所以改成0
  20. logic-not-delete-value: 1 # 逻辑未删除值(默认为 0)这里因为我是反的所以改成1
  21. # table-prefix: tbl_ # 数据库表前缀全局配置
  22. banner: false # 关闭控制台mybatis-plus的logo
  23. # type-enums-package: com.bocai.enums # 扫描通用枚举包 或者使用上面那个枚举全局配置
  24. # 阿里云OSS配置
  25. aliyun:
  26. oss:
  27. endpoint: https://oss-cn-hanzhou.aliyuncs.com
  28. accessKeyId: LTjfk332422slksPqy
  29. accessKeySecret: Pfslfksd2;lf2sALHfdsfsTHm6fdsfsdsR
  30. bucketName: web-spring3bocai

4、通过mybatis-X生成实体pojo等

4.1 Article

  1. package com.bocai.pojo;
  2. import com.baomidou.mybatisplus.annotation.IdType;
  3. import com.baomidou.mybatisplus.annotation.TableField;
  4. import com.baomidou.mybatisplus.annotation.TableId;
  5. import com.baomidou.mybatisplus.annotation.TableName;
  6. import java.io.Serializable;
  7. import java.time.LocalDateTime;
  8. import java.util.Date;
  9. import com.bocai.anno.State;
  10. import com.fasterxml.jackson.annotation.JsonFormat;
  11. import com.fasterxml.jackson.annotation.JsonIgnore;
  12. import jakarta.validation.constraints.NotEmpty;
  13. import jakarta.validation.constraints.NotNull;
  14. import jakarta.validation.constraints.Pattern;
  15. import jakarta.validation.groups.Default;
  16. import lombok.Data;
  17. import org.hibernate.validator.constraints.URL;
  18. /**
  19. *
  20. * @TableName article
  21. */
  22. @TableName(value ="article")
  23. @Data
  24. public class Article implements Serializable {
  25. /**
  26. * ID
  27. */
  28. @NotNull(groups = Article.Update.class)
  29. @TableId(type = IdType.AUTO)
  30. private Integer id;
  31. /**
  32. * 文章标题
  33. */
  34. @NotEmpty
  35. @Pattern(regexp = "^\\S{1,10}$")
  36. private String title;
  37. /**
  38. * 文章内容
  39. */
  40. @NotEmpty
  41. private String content;
  42. /**
  43. * 文章封面
  44. */
  45. @NotEmpty
  46. @URL
  47. private String coverImg;
  48. /**
  49. * 文章状态: 只能是[已发布] 或者 [草稿]
  50. */
  51. @State //自定义注解
  52. private String state;
  53. /**
  54. * 文章分类ID
  55. */
  56. @NotNull
  57. private Integer categoryId;
  58. /**
  59. * 创建人ID
  60. */
  61. @JsonIgnore // json返回不显示
  62. private Integer createUser;
  63. /**
  64. * 创建时间
  65. */
  66. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  67. private LocalDateTime createTime;
  68. /**
  69. * 修改时间
  70. */
  71. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  72. private LocalDateTime updateTime;
  73. @TableField(exist = false)
  74. private static final long serialVersionUID = 1L;
  75. // 如果说某个校验项没有指定分钟,默认属于Default分组
  76. //分组之间可以继承,A extend B, 那么A 就拥有B的所有校验项
  77. /**
  78. * 为了校验分组
  79. */
  80. public interface Add extends Default {
  81. }
  82. /**
  83. * 为了校验分组
  84. */
  85. public interface Update extends Default{
  86. }
  87. }

4.2 Category

  1. package com.bocai.pojo;
  2. import com.baomidou.mybatisplus.annotation.IdType;
  3. import com.baomidou.mybatisplus.annotation.TableField;
  4. import com.baomidou.mybatisplus.annotation.TableId;
  5. import com.baomidou.mybatisplus.annotation.TableName;
  6. import java.io.Serializable;
  7. import java.time.LocalDateTime;
  8. import java.util.Date;
  9. import com.fasterxml.jackson.annotation.JsonFormat;
  10. import com.fasterxml.jackson.annotation.JsonIgnore;
  11. import jakarta.validation.constraints.NotEmpty;
  12. import jakarta.validation.constraints.NotNull;
  13. import jakarta.validation.groups.Default;
  14. import lombok.Data;
  15. /**
  16. *
  17. * @TableName category
  18. */
  19. @TableName(value ="category")
  20. @Data
  21. public class Category implements Serializable {
  22. /**
  23. * ID
  24. */
  25. @NotNull(groups = Update.class)
  26. @TableId(type = IdType.AUTO)
  27. private Integer id;
  28. /**
  29. * 分类名称
  30. */
  31. @NotEmpty //值不能为空,并且内容不能为空
  32. private String categoryName;
  33. /**
  34. * 分类别名
  35. */
  36. @NotEmpty //值不能为空,并且内容不能为空
  37. // @NotEmpty(groups = {Update.class,Add.class})
  38. private String categoryAlias;
  39. /**
  40. * 创建人ID
  41. */
  42. @JsonIgnore // json返回不显示
  43. private Integer createUser;
  44. /**
  45. * 创建时间
  46. */
  47. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  48. private LocalDateTime createTime;
  49. /**
  50. * 修改时间
  51. */
  52. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  53. private LocalDateTime updateTime;
  54. @TableField(exist = false)
  55. private static final long serialVersionUID = 1L;
  56. // 如果说某个校验项没有指定分钟,默认属于Default分组
  57. //分组之间可以继承,A extend B, 那么A 就拥有B的所有校验项
  58. /**
  59. * 为了校验分组
  60. */
  61. public interface Add extends Default {
  62. }
  63. /**
  64. * 为了校验分组
  65. */
  66. public interface Update extends Default{
  67. }
  68. }

4.3 User

  1. package com.bocai.pojo;
  2. import com.baomidou.mybatisplus.annotation.IdType;
  3. import com.baomidou.mybatisplus.annotation.TableField;
  4. import com.baomidou.mybatisplus.annotation.TableId;
  5. import com.baomidou.mybatisplus.annotation.TableName;
  6. import java.io.Serializable;
  7. import java.time.LocalDateTime;
  8. import java.util.Date;
  9. import com.fasterxml.jackson.annotation.JsonFormat;
  10. import com.fasterxml.jackson.annotation.JsonIgnore;
  11. import jakarta.validation.constraints.Email;
  12. import jakarta.validation.constraints.NotEmpty;
  13. import jakarta.validation.constraints.NotNull;
  14. import jakarta.validation.constraints.Pattern;
  15. import lombok.Data;
  16. /**
  17. * 用户表
  18. * @TableName user
  19. */
  20. @TableName(value ="user")
  21. @Data
  22. public class User implements Serializable {
  23. /**
  24. * ID
  25. */
  26. @NotNull //不能为空
  27. @TableId(type = IdType.AUTO)
  28. private Integer id;
  29. /**
  30. * 用户名
  31. */
  32. private String username;
  33. /**
  34. * 密码
  35. */
  36. @JsonIgnore //springboot把当前对象转换成json字符串的时候忽略这个字段
  37. private String password;
  38. /**
  39. * 昵称
  40. */
  41. @NotEmpty //值不能为空,并且内容不能为空
  42. @Pattern(regexp = "^\\S{1,10}$") //正则
  43. private String nickname;
  44. /**
  45. * 邮箱
  46. */
  47. @Email //满足邮箱格式
  48. private String email;
  49. /**
  50. * 头像
  51. */
  52. private String userPic;
  53. /**
  54. * 创建时间
  55. */
  56. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  57. private LocalDateTime createTime;
  58. /**
  59. * 修改时间
  60. */
  61. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  62. private LocalDateTime updateTime;
  63. @TableField(exist = false)
  64. private static final long serialVersionUID = 1L;
  65. }

5、 Mapper

5.1 ArticleMapper

  1. package com.bocai.mapper;
  2. import com.bocai.pojo.Article;
  3. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  4. import org.apache.ibatis.annotations.Mapper;
  5. /**
  6. * @author cheng
  7. * @description 针对表【article】的数据库操作Mapper
  8. * @createDate 2023-11-13 19:55:11
  9. * @Entity com.bocai.pojo.Article
  10. */
  11. @Mapper
  12. public interface ArticleMapper extends BaseMapper<Article> {
  13. }

5.2 CategoryMapper

  1. package com.bocai.mapper;
  2. import com.bocai.pojo.Category;
  3. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  4. import org.apache.ibatis.annotations.Mapper;
  5. /**
  6. * @author cheng
  7. * @description 针对表【category】的数据库操作Mapper
  8. * @createDate 2023-11-13 19:55:04
  9. * @Entity com.bocai.pojo.Category
  10. */
  11. @Mapper
  12. public interface CategoryMapper extends BaseMapper<Category> {
  13. }

5.3 UserMapper

  1. package com.bocai.mapper;
  2. import com.bocai.pojo.User;
  3. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  4. import org.apache.ibatis.annotations.Mapper;
  5. /**
  6. * @author cheng
  7. * @description 针对表【user(用户表)】的数据库操作Mapper
  8. * @createDate 2023-11-13 19:54:41
  9. * @Entity com.bocai.pojo.User
  10. */
  11. @Mapper
  12. public interface UserMapper extends BaseMapper<User> {
  13. }

6、service

6.1 ArticleService

  1. package com.bocai.service;
  2. import com.bocai.pojo.Article;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. /**
  5. * @author cheng
  6. * @description 针对表【article】的数据库操作Service
  7. * @createDate 2023-11-13 19:55:11
  8. */
  9. public interface ArticleService extends IService<Article> {
  10. }

6.2 CategoryService

  1. package com.bocai.service;
  2. import com.bocai.pojo.Category;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. /**
  5. * @author cheng
  6. * @description 针对表【category】的数据库操作Service
  7. * @createDate 2023-11-13 19:55:04
  8. */
  9. public interface CategoryService extends IService<Category> {
  10. }

6.3 UserService

  1. package com.bocai.service;
  2. import com.bocai.pojo.User;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. /**
  5. * @author cheng
  6. * @description 针对表【user(用户表)】的数据库操作Service
  7. * @createDate 2023-11-13 19:54:41
  8. */
  9. public interface UserService extends IService<User> {
  10. }

7、serviceImpl

7.1 ArticleServiceImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  3. import com.bocai.pojo.Article;
  4. import com.bocai.service.ArticleService;
  5. import com.bocai.mapper.ArticleMapper;
  6. import org.springframework.stereotype.Service;
  7. /**
  8. * @author cheng
  9. * @description 针对表【article】的数据库操作Service实现
  10. * @createDate 2023-11-13 19:55:11
  11. */
  12. @Service
  13. public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>
  14. implements ArticleService{
  15. }

7.2 CategoryServiceImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  3. import com.bocai.pojo.Category;
  4. import com.bocai.service.CategoryService;
  5. import com.bocai.mapper.CategoryMapper;
  6. import org.springframework.stereotype.Service;
  7. /**
  8. * @author cheng
  9. * @description 针对表【category】的数据库操作Service实现
  10. * @createDate 2023-11-13 19:55:04
  11. */
  12. @Service
  13. public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
  14. implements CategoryService{
  15. }

7.3 UserServiceImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  3. import com.bocai.pojo.User;
  4. import com.bocai.service.UserService;
  5. import com.bocai.mapper.UserMapper;
  6. import org.springframework.stereotype.Service;
  7. /**
  8. * @author cheng
  9. * @description 针对表【user(用户表)】的数据库操作Service实现
  10. * @createDate 2023-11-13 19:54:41
  11. */
  12. @Service
  13. public class UserServiceImpl extends ServiceImpl<UserMapper, User>
  14. implements UserService{
  15. }

8、统一返回类Result

  1. package com.bocai.common;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. @Data
  6. @NoArgsConstructor
  7. @AllArgsConstructor
  8. public class Result {
  9. private Integer code;//响应码,1 代表成功; 0 代表失败
  10. private String msg; //响应信息 描述字符串
  11. private Object data; //返回的数据
  12. //增删改 成功响应
  13. public static Result success(){
  14. return new Result(1,"success",null);
  15. }
  16. //查询 成功响应
  17. public static Result success(Object data){
  18. return new Result(1,"success",data);
  19. }
  20. //失败响应
  21. public static Result error(String msg){
  22. return new Result(0,msg,null);
  23. }
  24. }

9、工具类

9.1 MD5加密工具类Md5Util

  1. package com.bocai.utils;
  2. import java.security.MessageDigest;
  3. import java.security.NoSuchAlgorithmException;
  4. public class Md5Util {
  5. /**
  6. * 默认的密码字符串组合,用来将字节转换成 16 进制表示的字符,apache校验下载的文件的正确性用的就是默认的这个组合
  7. */
  8. protected static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  9. protected static MessageDigest messagedigest = null;
  10. static {
  11. try {
  12. messagedigest = MessageDigest.getInstance("MD5");
  13. } catch (NoSuchAlgorithmException nsaex) {
  14. System.err.println(Md5Util.class.getName() + "初始化失败,MessageDigest不支持MD5Util。");
  15. nsaex.printStackTrace();
  16. }
  17. }
  18. /**
  19. * 生成字符串的md5校验值
  20. *
  21. * @param s
  22. * @return
  23. */
  24. public static String getMD5String(String s) {
  25. return getMD5String(s.getBytes());
  26. }
  27. /**
  28. * 判断字符串的md5校验码是否与一个已知的md5码相匹配
  29. *
  30. * @param password 要校验的字符串
  31. * @param md5PwdStr 已知的md5校验码
  32. * @return
  33. */
  34. public static boolean checkPassword(String password, String md5PwdStr) {
  35. String s = getMD5String(password);
  36. return s.equals(md5PwdStr);
  37. }
  38. public static String getMD5String(byte[] bytes) {
  39. messagedigest.update(bytes);
  40. return bufferToHex(messagedigest.digest());
  41. }
  42. private static String bufferToHex(byte bytes[]) {
  43. return bufferToHex(bytes, 0, bytes.length);
  44. }
  45. private static String bufferToHex(byte bytes[], int m, int n) {
  46. StringBuffer stringbuffer = new StringBuffer(2 * n);
  47. int k = m + n;
  48. for (int l = m; l < k; l++) {
  49. appendHexPair(bytes[l], stringbuffer);
  50. }
  51. return stringbuffer.toString();
  52. }
  53. private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
  54. char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换, >>>
  55. // 为逻辑右移,将符号位一起右移,此处未发现两种符号有何不同
  56. char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换
  57. stringbuffer.append(c0);
  58. stringbuffer.append(c1);
  59. }
  60. }

9.2 jwt生成token工具类JwtUtils 

  1. package com.bocai.utils;
  2. import io.jsonwebtoken.Claims;
  3. import io.jsonwebtoken.Jwts;
  4. import io.jsonwebtoken.SignatureAlgorithm;
  5. import java.util.Date;
  6. import java.util.Map;
  7. public class JwtUtils {
  8. private static String signKey = "bocai";
  9. private static Long expire = 43200000L; // 12h
  10. /**
  11. * 生成JWT令牌
  12. * @param claims JWT第二部分负载 payload 中存储的内容
  13. * @return
  14. */
  15. public static String generateJwt(Map<String, Object> claims){
  16. String jwt = Jwts.builder()
  17. .addClaims(claims)
  18. .signWith(SignatureAlgorithm.HS256, signKey)
  19. .setExpiration(new Date(System.currentTimeMillis() + expire))
  20. .compact();
  21. return jwt;
  22. }
  23. /**
  24. * 解析JWT令牌
  25. * @param jwt JWT令牌
  26. * @return JWT第二部分负载 payload 中存储的内容
  27. */
  28. public static Claims parseJWT(String jwt){
  29. Claims claims = Jwts.parser()
  30. .setSigningKey(signKey)
  31. .parseClaimsJws(jwt)
  32. .getBody();
  33. return claims;
  34. }
  35. }

9.3 工具类ThreadLocalUtil

  1. package com.bocai.utils;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. /**
  5. * ThreadLocal 工具类
  6. */
  7. @SuppressWarnings("all")
  8. public class ThreadLocalUtil {
  9. //提供ThreadLocal对象,
  10. private static final ThreadLocal THREAD_LOCAL = new ThreadLocal();
  11. //根据键获取值
  12. public static <T> T get(){
  13. return (T) THREAD_LOCAL.get();
  14. }
  15. //存储键值对
  16. public static void set(Object value){
  17. THREAD_LOCAL.set(value);
  18. }
  19. //清除ThreadLocal 防止内存泄漏
  20. public static void remove(){
  21. THREAD_LOCAL.remove();
  22. }
  23. }

 9.4 AliOSSProperties阿里云参数实体

  1. package com.bocai.utils;
  2. import lombok.Data;
  3. import org.springframework.boot.context.properties.ConfigurationProperties;
  4. import org.springframework.stereotype.Component;
  5. @Data
  6. @Component
  7. @ConfigurationProperties(prefix = "aliyun.oss")
  8. public class AliOSSProperties {
  9. private String endpoint;
  10. private String accessKeyId;
  11. private String accessKeySecret;
  12. private String bucketName;
  13. }

9.5 阿里云AliOSSUtils

  1. package com.bocai.utils;
  2. import com.aliyun.oss.OSS;
  3. import com.aliyun.oss.OSSClientBuilder;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Component;
  6. import org.springframework.web.multipart.MultipartFile;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.util.UUID;
  10. /**
  11. * 阿里云 OSS 工具类
  12. */
  13. @Component
  14. public class AliOSSUtils {
  15. // @Value("${aliyun.oss.endpoint}")
  16. // private String endpoint;
  17. // @Value("${aliyun.oss.accessKeyId}")
  18. // private String accessKeyId;
  19. // @Value("${aliyun.oss.accessKeySecret}")
  20. // private String accessKeySecret;
  21. // @Value("${aliyun.oss.bucketName}")
  22. // private String bucketName;
  23. @Autowired
  24. private AliOSSProperties aliOSSProperties;
  25. /**
  26. * 实现上传图片到OSS
  27. */
  28. public String upload(MultipartFile file) throws IOException {
  29. // 获取阿里云OSS参数
  30. String endpoint = aliOSSProperties.getEndpoint();
  31. String accessKeyId = aliOSSProperties.getAccessKeyId();
  32. String accessKeySecret = aliOSSProperties.getAccessKeySecret();
  33. String bucketName = aliOSSProperties.getBucketName();
  34. // 获取上传的文件的输入流
  35. InputStream inputStream = file.getInputStream();
  36. // 避免文件覆盖
  37. String originalFilename = file.getOriginalFilename();
  38. String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
  39. //上传文件到 OSS
  40. OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
  41. ossClient.putObject(bucketName, fileName, inputStream);
  42. //文件访问路径
  43. String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
  44. // 关闭ossClient
  45. ossClient.shutdown();
  46. return url;// 把上传到oss的路径返回
  47. }
  48. }

10、全局异常处理类GlobalExceptionHandler

  1. package com.bocai.exception;
  2. import com.bocai.common.Result;
  3. import org.springframework.web.bind.annotation.ExceptionHandler;
  4. import org.springframework.web.bind.annotation.RestControllerAdvice;
  5. /**
  6. * =========================全局异常处理器========================
  7. */
  8. @RestControllerAdvice
  9. public class GlobalExceptionHandler {
  10. @ExceptionHandler(Exception.class)//捕获所有异常
  11. public Result ex(Exception ex){
  12. ex.printStackTrace();
  13. return Result.error("对不起,操作失败,请联系管理员");
  14. }
  15. }

11、拦截器LoginCheckInterceptor

  1. package com.bocai.interceptor;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.bocai.common.Result;
  4. import com.bocai.utils.JwtUtils;
  5. import com.bocai.utils.ThreadLocalUtil;
  6. import jakarta.servlet.http.HttpServletRequest;
  7. import jakarta.servlet.http.HttpServletResponse;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.springframework.stereotype.Component;
  10. import org.springframework.util.StringUtils;
  11. import org.springframework.web.servlet.HandlerInterceptor;
  12. import org.springframework.web.servlet.ModelAndView;
  13. import java.util.Map;
  14. /**
  15. * =========================LoginCheckInterceptor 拦截器 interceptor========================
  16. */
  17. @Slf4j
  18. @Component
  19. public class LoginCheckInterceptor implements HandlerInterceptor {
  20. @Override //目标资源方法运行前运行, 返回true: 放行, 放回false, 不放行
  21. public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
  22. //1.获取请求url。
  23. String url = req.getRequestURL().toString();
  24. log.info("请求的url: {}",url);
  25. //2.判断请求url中是否包含login,如果包含,说明是登录操作,放行。
  26. if(url.contains("login")){
  27. log.info("登录操作, 放行...");
  28. return true;
  29. }
  30. //3.获取请求头中的令牌( Authorization)。
  31. String jwt = req.getHeader("Authorization");
  32. //4.判断令牌是否存在,如果不存在,返回错误结果(未登录)。
  33. if(!StringUtils.hasLength(jwt)){
  34. log.info("请求头Authorization为空,返回未登录的信息");
  35. Result error = Result.error("NOT_LOGIN");
  36. //手动转换 对象--json --------> 阿里巴巴fastJSON
  37. String notLogin = JSONObject.toJSONString(error);
  38. resp.getWriter().write(notLogin);
  39. return false;
  40. }
  41. //5.解析token,如果解析失败,返回错误结果(未登录)。
  42. try {
  43. Map<String, Object> claims = JwtUtils.parseJWT(jwt);
  44. //6.把业务数据存储到ThreadLocal中
  45. ThreadLocalUtil.set(claims);
  46. //7.放行。
  47. log.info("令牌合法, 放行");
  48. return true;
  49. } catch (Exception e) {//jwt解析失败
  50. e.printStackTrace();
  51. log.info("解析令牌失败, 返回未登录错误信息");
  52. Result error = Result.error("NOT_LOGIN");
  53. //手动转换 对象--json --------> 阿里巴巴fastJSON
  54. String notLogin = JSONObject.toJSONString(error);
  55. resp.getWriter().write(notLogin);
  56. return false;
  57. }
  58. }
  59. @Override //目标资源方法运行后运行
  60. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  61. System.out.println("postHandle ...");
  62. }
  63. @Override //视图渲染完毕后运行, 最后运行
  64. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  65. // 清空ThreadLocal中的数据,防止内存泄漏
  66. ThreadLocalUtil.remove();
  67. System.out.println("afterCompletion...");
  68. }
  69. }

12、配置类

 12.1 配置类WebConfig注册拦截器

  1. package com.bocai.config;
  2. import com.bocai.interceptor.LoginCheckInterceptor;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  6. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  7. /**
  8. * =========================LoginCheckInterceptor 的配置类 ========================
  9. */
  10. @Configuration //配置类
  11. public class WebConfig implements WebMvcConfigurer {
  12. @Autowired
  13. private LoginCheckInterceptor loginCheckInterceptor;
  14. /**
  15. * 注册拦截器, 拦截所有url,除登录
  16. * @param registry
  17. */
  18. @Override
  19. public void addInterceptors(InterceptorRegistry registry) {
  20. registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**").excludePathPatterns("/user/login","/user/register");
  21. }
  22. }

12.2   MybatisPlus分页配置类MybatisPlusConfig

  1. package com.bocai.config;
  2. import com.baomidou.mybatisplus.annotation.DbType;
  3. import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
  4. import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
  5. import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. /**
  9. * 配置MP的分页插件
  10. */
  11. @Configuration
  12. public class MybatisPlusConfig {
  13. @Bean
  14. public MybatisPlusInterceptor mybatisPlusInterceptor(){
  15. // 1、定义MybatisPlus拦截器
  16. MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
  17. // 2、添加分页的拦截器
  18. mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
  19. // 3、添加乐观锁的拦截器
  20. mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
  21. return mybatisPlusInterceptor;
  22. }
  23. }

13、自定义注解(新增文章)

13.1 新增文章自定义注解State接口

  1. package com.bocai.anno;
  2. import com.bocai.validation.StateValidation;
  3. import jakarta.validation.Constraint;
  4. import jakarta.validation.Payload;
  5. import jakarta.validation.constraints.NotEmpty;
  6. import java.lang.annotation.Documented;
  7. import java.lang.annotation.Repeatable;
  8. import java.lang.annotation.Retention;
  9. import java.lang.annotation.Target;
  10. import static java.lang.annotation.ElementType.*;
  11. import static java.lang.annotation.ElementType.TYPE_USE;
  12. import static java.lang.annotation.RetentionPolicy.RUNTIME;
  13. @Documented//元注解
  14. @Target({ FIELD})//元注解
  15. @Retention(RUNTIME)//元注解
  16. @Constraint(validatedBy = { StateValidation.class})//指定提供校验规则的类
  17. public @interface State {
  18. //提供校验失败后的提示信息
  19. String message() default "state参数的值只能是已发布或者草稿";
  20. //指定分组
  21. Class<?>[] groups() default { };
  22. //负载 获取到State注解的附加信息
  23. Class<? extends Payload>[] payload() default { };
  24. }

13.2 新增文章自定义注解实现类StateValidation

  1. package com.bocai.validation;
  2. import com.bocai.anno.State;
  3. import jakarta.validation.ConstraintValidator;
  4. import jakarta.validation.ConstraintValidatorContext;
  5. public class StateValidation implements ConstraintValidator<State,String> {
  6. /**
  7. *
  8. * @param value 将来要校验的数据
  9. * @param context context in which the constraint is evaluated
  10. *
  11. * @return 如果返回false,则校验不通过,如果返回true,则校验通过
  12. */
  13. @Override
  14. public boolean isValid(String value, ConstraintValidatorContext context) {
  15. //提供校验规则
  16. if (value == null){
  17. return false;
  18. }
  19. if (value.equals("已发布") || value.equals("草稿")){
  20. return true;
  21. }
  22. return false;
  23. }
  24. }

14、封装分页实体PageBean

  1. package com.bocai.pojo;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. import java.util.List;
  6. /**
  7. * 分页查询结果封装类
  8. */
  9. @Data
  10. @NoArgsConstructor
  11. @AllArgsConstructor
  12. public class PageBean {
  13. private Long total;//总记录数
  14. private List items;//数据列表
  15. }

二、用户

1、注册

1.1 UserController

  1. package com.bocai.controller;
  2. import com.bocai.common.Result;
  3. import com.bocai.pojo.User;
  4. import com.bocai.service.UserService;
  5. import jakarta.validation.constraints.Pattern;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.validation.annotation.Validated;
  9. import org.springframework.web.bind.annotation.GetMapping;
  10. import org.springframework.web.bind.annotation.PostMapping;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RestController;
  13. @RestController
  14. @Slf4j
  15. @Validated
  16. @RequestMapping("/user")
  17. public class UserController {
  18. @Autowired
  19. private UserService userService;
  20. /**
  21. * 用户注册
  22. * @param username
  23. * @param password
  24. * @return
  25. */
  26. @PostMapping("/register")
  27. public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password){
  28. log.info("注册用户名:{},密码为:{}",username,password);
  29. // 查询用户
  30. User user = userService.queryUserByUsername(username,password);
  31. if (user == null){
  32. //没有占用,可以注册
  33. //注册用户
  34. userService.register(username,password);
  35. return Result.success();
  36. }else{
  37. return Result.error("用户名被占用");
  38. }
  39. }
  40. }

1.2 service

  1. package com.bocai.service;
  2. import com.bocai.pojo.User;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. /**
  5. * @author cheng
  6. * @description 针对表【user(用户表)】的数据库操作Service
  7. * @createDate 2023-11-13 19:54:41
  8. */
  9. public interface UserService extends IService<User> {
  10. /**
  11. * 用户注册
  12. * @param username
  13. * @param password
  14. */
  15. void register(String username, String password);
  16. /**
  17. * 根据用户名 --查询用户
  18. * @param username
  19. * @return
  20. */
  21. User queryUserByUsername(String username);
  22. }

1.3 serviceImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  4. import com.bocai.pojo.User;
  5. import com.bocai.service.UserService;
  6. import com.bocai.mapper.UserMapper;
  7. import com.bocai.utils.Md5Util;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Service;
  10. import java.time.LocalDateTime;
  11. /**
  12. * @author cheng
  13. * @description 针对表【user(用户表)】的数据库操作Service实现
  14. * @createDate 2023-11-13 19:54:41
  15. */
  16. @Service
  17. public class UserServiceImpl extends ServiceImpl<UserMapper, User>
  18. implements UserService{
  19. @Autowired
  20. private UserMapper userMapper;
  21. /**
  22. * 注册
  23. * @param username
  24. * @param password
  25. */
  26. @Override
  27. public void register(String username, String password) {
  28. //密码加密
  29. String md5String = Md5Util.getMD5String(password);
  30. User user = new User();
  31. user.setUsername(username);
  32. user.setPassword(md5String);
  33. user.setCreateTime(LocalDateTime.now());
  34. user.setUpdateTime(LocalDateTime.now());
  35. userMapper.insert(user);
  36. }
  37. /**
  38. * 查询用户
  39. * @param username
  40. * @return
  41. */
  42. @Override
  43. public User queryUserByUsername(String username) {
  44. //查询用户
  45. LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  46. lambdaQueryWrapper.eq(username != null, User::getUsername,username);
  47. User user = userMapper.selectOne(lambdaQueryWrapper);
  48. return user;
  49. }
  50. }

2、登录

2.1 UserController

  1. package com.bocai.controller;
  2. import com.bocai.common.Result;
  3. import com.bocai.pojo.User;
  4. import com.bocai.service.UserService;
  5. import com.bocai.utils.Md5Util;
  6. import jakarta.validation.constraints.Pattern;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.validation.annotation.Validated;
  10. import org.springframework.web.bind.annotation.GetMapping;
  11. import org.springframework.web.bind.annotation.PostMapping;
  12. import org.springframework.web.bind.annotation.RequestMapping;
  13. import org.springframework.web.bind.annotation.RestController;
  14. @RestController
  15. @Slf4j
  16. @Validated
  17. @RequestMapping("/user")
  18. public class UserController {
  19. @Autowired
  20. private UserService userService;
  21. /**
  22. * 用户注册
  23. * @param username
  24. * @param password
  25. * @return
  26. */
  27. @PostMapping("/register")
  28. public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password){
  29. log.info("注册用户名:{},密码为:{}",username,password);
  30. // 查询用户
  31. User user = userService.queryUserByUsername(username);
  32. if (user == null){
  33. //没有占用,可以注册
  34. //注册用户
  35. userService.register(username,password);
  36. return Result.success();
  37. }else{
  38. return Result.error("用户名被占用");
  39. }
  40. }
  41. @PostMapping("/login")
  42. public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password) {
  43. log.info("登录用户名:{},密码为:{}", username, password);
  44. // 查询用户
  45. User loginUser = userService.queryUserByUsername(username);
  46. // 判断用户是否存在
  47. if (loginUser == null) {
  48. return Result.error("用户名不存在");
  49. }
  50. // 判断密码是否正确,loginUser对象中的password是密文
  51. if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
  52. // 登录成功
  53. return Result.success("JWT");
  54. }
  55. return Result.error("密码错误!");
  56. }
  57. }

2.2 登录认证 

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  4. import com.bocai.pojo.User;
  5. import com.bocai.service.UserService;
  6. import com.bocai.mapper.UserMapper;
  7. import com.bocai.utils.Md5Util;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Service;
  10. import java.time.LocalDateTime;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13. /**
  14. * @author cheng
  15. * @description 针对表【user(用户表)】的数据库操作Service实现
  16. * @createDate 2023-11-13 19:54:41
  17. */
  18. @Service
  19. public class UserServiceImpl extends ServiceImpl<UserMapper, User>
  20. implements UserService{
  21. @Autowired
  22. private UserMapper userMapper;
  23. /**
  24. * 注册
  25. * @param username
  26. * @param password
  27. */
  28. @Override
  29. public void register(String username, String password) {
  30. //密码加密
  31. String md5String = Md5Util.getMD5String(password);
  32. User user = new User();
  33. user.setUsername(username);
  34. user.setPassword(md5String);
  35. user.setCreateTime(LocalDateTime.now());
  36. user.setUpdateTime(LocalDateTime.now());
  37. userMapper.insert(user);
  38. }
  39. /**
  40. * 查询用户
  41. * @param username
  42. * @return
  43. */
  44. @Override
  45. public User queryUserByUsername(String username) {
  46. //查询用户
  47. LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  48. lambdaQueryWrapper.eq(username != null, User::getUsername,username);
  49. User user = userMapper.selectOne(lambdaQueryWrapper);
  50. return user;
  51. }
  52. }

3、获取用户详细信息

3.1 UserController

  1. package com.bocai.controller;
  2. import com.bocai.common.Result;
  3. import com.bocai.pojo.User;
  4. import com.bocai.service.UserService;
  5. import com.bocai.utils.JwtUtils;
  6. import com.bocai.utils.Md5Util;
  7. import jakarta.validation.constraints.Pattern;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.validation.annotation.Validated;
  11. import org.springframework.web.bind.annotation.*;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14. @RestController
  15. @Slf4j
  16. @Validated
  17. @RequestMapping("/user")
  18. public class UserController {
  19. @Autowired
  20. private UserService userService;
  21. /**
  22. * 用户注册
  23. * @param username
  24. * @param password
  25. * @return
  26. */
  27. @PostMapping("/register")
  28. public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password){
  29. log.info("注册用户名:{},密码为:{}",username,password);
  30. // 查询用户
  31. User user = userService.queryUserByUsername(username);
  32. if (user == null){
  33. //没有占用,可以注册
  34. //注册用户
  35. userService.register(username,password);
  36. return Result.success();
  37. }else{
  38. return Result.error("用户名被占用");
  39. }
  40. }
  41. @PostMapping("/login")
  42. public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password) {
  43. log.info("登录用户名:{},密码为:{}", username, password);
  44. // 查询用户
  45. User loginUser = userService.queryUserByUsername(username);
  46. // 判断用户是否存在
  47. if (loginUser == null) {
  48. return Result.error("用户名不存在");
  49. }
  50. // 判断密码是否正确,loginUser对象中的password是密文
  51. if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
  52. // 登录成功
  53. Map<String, Object> claims = new HashMap<>();
  54. claims.put("id", loginUser.getId());
  55. claims.put("username",loginUser.getUsername());
  56. String jwt = JwtUtils.generateJwt(claims); //让jwt包含了当前登录的员工信息
  57. return Result.success(jwt);
  58. }
  59. return Result.error("密码错误!");
  60. }
  61. /**
  62. * 查询用户信息(从token获取)
  63. * @param token
  64. * @return
  65. */
  66. @GetMapping("/userInfo")
  67. public Result userInfo(@RequestHeader(name = "Authorization")String token){
  68. log.info("查询用户全部信息");
  69. //根据用户名查询用户
  70. Map<String, Object> claims = JwtUtils.parseJWT(token);
  71. String username = (String) claims.get("username");
  72. User user = userService.queryUserByUsername(username);
  73. return Result.success(user);
  74. }
  75. }

 3.2 servcie

  1. package com.bocai.service;
  2. import com.bocai.pojo.User;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. /**
  5. * @author cheng
  6. * @description 针对表【user(用户表)】的数据库操作Service
  7. * @createDate 2023-11-13 19:54:41
  8. */
  9. public interface UserService extends IService<User> {
  10. /**
  11. * 用户注册
  12. * @param username
  13. * @param password
  14. */
  15. void register(String username, String password);
  16. /**
  17. * 根据用户名 --查询用户
  18. * @param username
  19. * @return
  20. */
  21. User queryUserByUsername(String username);
  22. /**
  23. * 更新用户
  24. * @param user
  25. */
  26. void updateUser(User user);
  27. }

3.3 servcieImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  4. import com.bocai.pojo.User;
  5. import com.bocai.service.UserService;
  6. import com.bocai.mapper.UserMapper;
  7. import com.bocai.utils.Md5Util;
  8. import com.bocai.utils.ThreadLocalUtil;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Service;
  11. import java.time.LocalDateTime;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14. /**
  15. * @author cheng
  16. * @description 针对表【user(用户表)】的数据库操作Service实现
  17. * @createDate 2023-11-13 19:54:41
  18. */
  19. @Service
  20. public class UserServiceImpl extends ServiceImpl<UserMapper, User>
  21. implements UserService{
  22. @Autowired
  23. private UserMapper userMapper;
  24. /**
  25. * 注册
  26. * @param username
  27. * @param password
  28. */
  29. @Override
  30. public void register(String username, String password) {
  31. //密码加密
  32. String md5String = Md5Util.getMD5String(password);
  33. User user = new User();
  34. user.setUsername(username);
  35. user.setPassword(md5String);
  36. user.setCreateTime(LocalDateTime.now());
  37. user.setUpdateTime(LocalDateTime.now());
  38. userMapper.insert(user);
  39. }
  40. /**
  41. * 查询用户
  42. * @param username
  43. * @return
  44. */
  45. @Override
  46. public User queryUserByUsername(String username) {
  47. //查询用户
  48. LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  49. lambdaQueryWrapper.eq(username != null, User::getUsername,username);
  50. User user = userMapper.selectOne(lambdaQueryWrapper);
  51. return user;
  52. }
  53. /**
  54. * 更新用户
  55. * @param user
  56. */
  57. @Override
  58. public void updateUser(User user) {
  59. user.setUpdateTime(LocalDateTime.now());
  60. userMapper.updateById(user);
  61. }
  62. }

3.4 优化版本UserController(使用ThreadLocal)

 

  1. package com.bocai.controller;
  2. import com.bocai.common.Result;
  3. import com.bocai.pojo.User;
  4. import com.bocai.service.UserService;
  5. import com.bocai.utils.JwtUtils;
  6. import com.bocai.utils.Md5Util;
  7. import com.bocai.utils.ThreadLocalUtil;
  8. import jakarta.validation.constraints.Pattern;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.validation.annotation.Validated;
  12. import org.springframework.web.bind.annotation.*;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. @RestController
  16. @Slf4j
  17. @Validated
  18. @RequestMapping("/user")
  19. public class UserController {
  20. @Autowired
  21. private UserService userService;
  22. /**
  23. * 用户注册
  24. * @param username
  25. * @param password
  26. * @return
  27. */
  28. @PostMapping("/register")
  29. public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password){
  30. log.info("注册用户名:{},密码为:{}",username,password);
  31. // 查询用户
  32. User user = userService.queryUserByUsername(username);
  33. if (user == null){
  34. //没有占用,可以注册
  35. //注册用户
  36. userService.register(username,password);
  37. return Result.success();
  38. }else{
  39. return Result.error("用户名被占用");
  40. }
  41. }
  42. @PostMapping("/login")
  43. public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password) {
  44. log.info("登录用户名:{},密码为:{}", username, password);
  45. // 查询用户
  46. User loginUser = userService.queryUserByUsername(username);
  47. // 判断用户是否存在
  48. if (loginUser == null) {
  49. return Result.error("用户名不存在");
  50. }
  51. // 判断密码是否正确,loginUser对象中的password是密文
  52. if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
  53. // 登录成功
  54. Map<String, Object> claims = new HashMap<>();
  55. claims.put("id", loginUser.getId());
  56. claims.put("username",loginUser.getUsername());
  57. String jwt = JwtUtils.generateJwt(claims); //让jwt包含了当前登录的员工信息
  58. return Result.success(jwt);
  59. }
  60. return Result.error("密码错误!");
  61. }
  62. /**
  63. * 查询用户信息(从线程获取)
  64. * @return
  65. */
  66. @GetMapping("/userInfo")
  67. public Result userInfo(){
  68. // 从线程获取存储的jwt信息
  69. Map<String, Object> map = ThreadLocalUtil.get();
  70. String username = (String) map.get("username");
  71. log.info("查询用户全部信息,从token获取信息为:{}",username);
  72. //根据用户名查询用户
  73. User user = userService.queryUserByUsername(username);
  74. return Result.success(user);
  75. }
  76. //使用上面的的优化版本
  77. // /**
  78. // * 查询用户信息(从token获取)
  79. // * @param token
  80. // * @return
  81. // */
  82. // @GetMapping("/userInfo")
  83. // public Result userInfo(@RequestHeader(name = "Authorization")String token){
  84. // log.info("查询用户全部信息,从token获取信息为:{}",token);
  85. // //根据用户名查询用户
  86. // Map<String, Object> claims = JwtUtils.parseJWT(token);
  87. // String username = (String) claims.get("username");
  88. // User user = userService.queryUserByUsername(username);
  89. // return Result.success(user);
  90. // }
  91. }

4、更新用户基本信息

4.1 UserController

@Validated

  1. package com.bocai.controller;
  2. import com.bocai.common.Result;
  3. import com.bocai.pojo.User;
  4. import com.bocai.service.UserService;
  5. import com.bocai.utils.JwtUtils;
  6. import com.bocai.utils.Md5Util;
  7. import com.bocai.utils.ThreadLocalUtil;
  8. import jakarta.validation.constraints.Pattern;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.validation.annotation.Validated;
  12. import org.springframework.web.bind.annotation.*;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. @RestController
  16. @Slf4j
  17. @Validated
  18. @RequestMapping("/user")
  19. public class UserController {
  20. @Autowired
  21. private UserService userService;
  22. /**
  23. * 用户注册
  24. * @param username
  25. * @param password
  26. * @return
  27. */
  28. @PostMapping("/register")
  29. public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password){
  30. log.info("注册用户名:{},密码为:{}",username,password);
  31. // 查询用户
  32. User user = userService.queryUserByUsername(username);
  33. if (user == null){
  34. //没有占用,可以注册
  35. //注册用户
  36. userService.register(username,password);
  37. return Result.success();
  38. }else{
  39. return Result.error("用户名被占用");
  40. }
  41. }
  42. @PostMapping("/login")
  43. public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password) {
  44. log.info("登录用户名:{},密码为:{}", username, password);
  45. // 查询用户
  46. User loginUser = userService.queryUserByUsername(username);
  47. // 判断用户是否存在
  48. if (loginUser == null) {
  49. return Result.error("用户名不存在");
  50. }
  51. // 判断密码是否正确,loginUser对象中的password是密文
  52. if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
  53. // 登录成功
  54. Map<String, Object> claims = new HashMap<>();
  55. claims.put("id", loginUser.getId());
  56. claims.put("username",loginUser.getUsername());
  57. String jwt = JwtUtils.generateJwt(claims); //让jwt包含了当前登录的员工信息
  58. return Result.success(jwt);
  59. }
  60. return Result.error("密码错误!");
  61. }
  62. /**
  63. * 查询用户信息(从线程获取)
  64. * @return
  65. */
  66. @GetMapping("/userInfo")
  67. public Result userInfo(){
  68. // 从线程获取存储的jwt信息
  69. Map<String, Object> map = ThreadLocalUtil.get();
  70. String username = (String) map.get("username");
  71. log.info("查询用户全部信息,从token获取信息为:{}",username);
  72. //根据用户名查询用户
  73. User user = userService.queryUserByUsername(username);
  74. return Result.success(user);
  75. }
  76. //使用上面的的优化版本
  77. // /**
  78. // * 查询用户信息(从token获取)
  79. // * @param token
  80. // * @return
  81. // */
  82. // @GetMapping("/userInfo")
  83. // public Result userInfo(@RequestHeader(name = "Authorization")String token){
  84. // log.info("查询用户全部信息,从token获取信息为:{}",token);
  85. // //根据用户名查询用户
  86. // Map<String, Object> claims = JwtUtils.parseJWT(token);
  87. // String username = (String) claims.get("username");
  88. // User user = userService.queryUserByUsername(username);
  89. // return Result.success(user);
  90. // }
  91. /**
  92. * 更新用户
  93. * @param user
  94. * @return
  95. */
  96. @PutMapping("/update")
  97. public Result update(@RequestBody @Validated User user){
  98. log.info("修改的用户为:{}",user);
  99. userService.updateUser(user);
  100. return Result.success();
  101. }
  102. }

4.2 servcie

  1. package com.bocai.service;
  2. import com.bocai.pojo.User;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. /**
  5. * @author cheng
  6. * @description 针对表【user(用户表)】的数据库操作Service
  7. * @createDate 2023-11-13 19:54:41
  8. */
  9. public interface UserService extends IService<User> {
  10. /**
  11. * 用户注册
  12. * @param username
  13. * @param password
  14. */
  15. void register(String username, String password);
  16. /**
  17. * 根据用户名 --查询用户
  18. * @param username
  19. * @return
  20. */
  21. User queryUserByUsername(String username);
  22. /**
  23. * 更新用户
  24. * @param user
  25. */
  26. void updateUser(User user);
  27. }

4.3 serviceImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  4. import com.bocai.pojo.User;
  5. import com.bocai.service.UserService;
  6. import com.bocai.mapper.UserMapper;
  7. import com.bocai.utils.Md5Util;
  8. import com.bocai.utils.ThreadLocalUtil;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Service;
  11. import java.time.LocalDateTime;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14. /**
  15. * @author cheng
  16. * @description 针对表【user(用户表)】的数据库操作Service实现
  17. * @createDate 2023-11-13 19:54:41
  18. */
  19. @Service
  20. public class UserServiceImpl extends ServiceImpl<UserMapper, User>
  21. implements UserService{
  22. @Autowired
  23. private UserMapper userMapper;
  24. /**
  25. * 注册
  26. * @param username
  27. * @param password
  28. */
  29. @Override
  30. public void register(String username, String password) {
  31. //密码加密
  32. String md5String = Md5Util.getMD5String(password);
  33. User user = new User();
  34. user.setUsername(username);
  35. user.setPassword(md5String);
  36. user.setCreateTime(LocalDateTime.now());
  37. user.setUpdateTime(LocalDateTime.now());
  38. userMapper.insert(user);
  39. }
  40. /**
  41. * 查询用户
  42. * @param username
  43. * @return
  44. */
  45. @Override
  46. public User queryUserByUsername(String username) {
  47. //查询用户
  48. LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  49. lambdaQueryWrapper.eq(username != null, User::getUsername,username);
  50. User user = userMapper.selectOne(lambdaQueryWrapper);
  51. return user;
  52. }
  53. /**
  54. * 更新用户
  55. * @param user
  56. */
  57. @Override
  58. public void updateUser(User user) {
  59. user.setUpdateTime(LocalDateTime.now());
  60. userMapper.updateById(user);
  61. }
  62. }

5、更新用户头像

5.2 UserController 

本内容2个知识点:

1、@URL 判断传参是不是url

2、@PatchMapping

@PutMapping和@PatchMapping是Spring MVC中用于处理HTTP请求的注解,它们在功能和使用上有一些区别。

  1. 请求方式:@PutMapping用于处理PUT请求,而@PatchMapping用于处理PATCH请求。
  2. 请求范围:@PutMapping通常用于执行大规模的替换操作,而不是更新操作。如果省略了订单上的某个属性,那么该属性的值应该被NULL所替代,甚至订单中的某个物品的实体数据也应一起重新设置,否则它们将从订单中移除。而@PatchMapping则用于对资源的部分更新,即只更新请求中指定的属性或关系。
  3. 参数绑定:@PutMapping可以使用@RequestBody注解将请求体中的JSON数据映射到Java对象中,而@PatchMapping则无法直接使用@RequestBody注解,需要使用其他方式来解析请求体中的JSON数据。
  1. package com.bocai.controller;
  2. import com.bocai.common.Result;
  3. import com.bocai.pojo.User;
  4. import com.bocai.service.UserService;
  5. import com.bocai.utils.JwtUtils;
  6. import com.bocai.utils.Md5Util;
  7. import com.bocai.utils.ThreadLocalUtil;
  8. import jakarta.validation.constraints.Pattern;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.hibernate.validator.constraints.URL;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.validation.annotation.Validated;
  13. import org.springframework.web.bind.annotation.*;
  14. import java.util.HashMap;
  15. import java.util.Map;
  16. @RestController
  17. @Slf4j
  18. @Validated
  19. @RequestMapping("/user")
  20. public class UserController {
  21. @Autowired
  22. private UserService userService;
  23. /**
  24. * 用户注册
  25. * @param username
  26. * @param password
  27. * @return
  28. */
  29. @PostMapping("/register")
  30. public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password){
  31. log.info("注册用户名:{},密码为:{}",username,password);
  32. // 查询用户
  33. User user = userService.queryUserByUsername(username);
  34. if (user == null){
  35. //没有占用,可以注册
  36. //注册用户
  37. userService.register(username,password);
  38. return Result.success();
  39. }else{
  40. return Result.error("用户名被占用");
  41. }
  42. }
  43. @PostMapping("/login")
  44. public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password) {
  45. log.info("登录用户名:{},密码为:{}", username, password);
  46. // 查询用户
  47. User loginUser = userService.queryUserByUsername(username);
  48. // 判断用户是否存在
  49. if (loginUser == null) {
  50. return Result.error("用户名不存在");
  51. }
  52. // 判断密码是否正确,loginUser对象中的password是密文
  53. if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
  54. // 登录成功
  55. Map<String, Object> claims = new HashMap<>();
  56. claims.put("id", loginUser.getId());
  57. claims.put("username",loginUser.getUsername());
  58. String jwt = JwtUtils.generateJwt(claims); //让jwt包含了当前登录的员工信息
  59. return Result.success(jwt);
  60. }
  61. return Result.error("密码错误!");
  62. }
  63. /**
  64. * 查询用户信息(从线程获取)
  65. * @return
  66. */
  67. @GetMapping("/userInfo")
  68. public Result userInfo(){
  69. // 从线程获取存储的jwt信息
  70. Map<String, Object> map = ThreadLocalUtil.get();
  71. String username = (String) map.get("username");
  72. log.info("查询用户全部信息,从token获取信息为:{}",username);
  73. //根据用户名查询用户
  74. User user = userService.queryUserByUsername(username);
  75. return Result.success(user);
  76. }
  77. //使用上面的的优化版本
  78. // /**
  79. // * 查询用户信息(从token获取)
  80. // * @param token
  81. // * @return
  82. // */
  83. // @GetMapping("/userInfo")
  84. // public Result userInfo(@RequestHeader(name = "Authorization")String token){
  85. // log.info("查询用户全部信息,从token获取信息为:{}",token);
  86. // //根据用户名查询用户
  87. // Map<String, Object> claims = JwtUtils.parseJWT(token);
  88. // String username = (String) claims.get("username");
  89. // User user = userService.queryUserByUsername(username);
  90. // return Result.success(user);
  91. // }
  92. /**
  93. * 更新用户
  94. * @param user
  95. * @return
  96. */
  97. @PutMapping("/update")
  98. public Result update(@RequestBody @Validated User user){
  99. log.info("修改的用户为:{}",user);
  100. userService.updateUser(user);
  101. return Result.success();
  102. }
  103. /**
  104. * 更新头像
  105. * @param avatarUrl
  106. * @return
  107. */
  108. @PatchMapping("/updateAvatar")
  109. public Result updateAvatar(@RequestParam @URL String avatarUrl){
  110. log.info("头像地址是{}",avatarUrl);
  111. userService.updateAvatar(avatarUrl);
  112. return Result.success();
  113. }
  114. }

5.2 servcie

  1. package com.bocai.service;
  2. import com.bocai.pojo.User;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. /**
  5. * @author cheng
  6. * @description 针对表【user(用户表)】的数据库操作Service
  7. * @createDate 2023-11-13 19:54:41
  8. */
  9. public interface UserService extends IService<User> {
  10. /**
  11. * 用户注册
  12. * @param username
  13. * @param password
  14. */
  15. void register(String username, String password);
  16. /**
  17. * 根据用户名 --查询用户
  18. * @param username
  19. * @return
  20. */
  21. User queryUserByUsername(String username);
  22. /**
  23. * 更新用户
  24. * @param user
  25. */
  26. void updateUser(User user);
  27. /**
  28. * 更新头像
  29. * @param avatarUrl
  30. */
  31. void updateAvatar(String avatarUrl);
  32. }

5.3 servcieImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  4. import com.bocai.pojo.User;
  5. import com.bocai.service.UserService;
  6. import com.bocai.mapper.UserMapper;
  7. import com.bocai.utils.Md5Util;
  8. import com.bocai.utils.ThreadLocalUtil;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Service;
  11. import java.time.LocalDateTime;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14. /**
  15. * @author cheng
  16. * @description 针对表【user(用户表)】的数据库操作Service实现
  17. * @createDate 2023-11-13 19:54:41
  18. */
  19. @Service
  20. public class UserServiceImpl extends ServiceImpl<UserMapper, User>
  21. implements UserService{
  22. @Autowired
  23. private UserMapper userMapper;
  24. /**
  25. * 注册
  26. * @param username
  27. * @param password
  28. */
  29. @Override
  30. public void register(String username, String password) {
  31. //密码加密
  32. String md5String = Md5Util.getMD5String(password);
  33. User user = new User();
  34. user.setUsername(username);
  35. user.setPassword(md5String);
  36. user.setCreateTime(LocalDateTime.now());
  37. user.setUpdateTime(LocalDateTime.now());
  38. userMapper.insert(user);
  39. }
  40. /**
  41. * 查询用户
  42. * @param username
  43. * @return
  44. */
  45. @Override
  46. public User queryUserByUsername(String username) {
  47. //查询用户
  48. LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  49. lambdaQueryWrapper.eq(username != null, User::getUsername,username);
  50. User user = userMapper.selectOne(lambdaQueryWrapper);
  51. return user;
  52. }
  53. /**
  54. * 更新用户
  55. * @param user
  56. */
  57. @Override
  58. public void updateUser(User user) {
  59. user.setUpdateTime(LocalDateTime.now());
  60. userMapper.updateById(user);
  61. }
  62. /**
  63. * 更新头像
  64. * @param avatarUrl
  65. */
  66. @Override
  67. public void updateAvatar(String avatarUrl) {
  68. Map<String, Object> map = ThreadLocalUtil.get();
  69. Integer id = (Integer) map.get("id");
  70. User user = new User();
  71. user.setId(id);
  72. user.setUpdateTime(LocalDateTime.now());
  73. user.setUserPic(avatarUrl);
  74. userMapper.updateById(user);
  75. }
  76. }

6、更新用户密码

6.1 UserController

  1. package com.bocai.controller;
  2. import com.bocai.common.Result;
  3. import com.bocai.pojo.User;
  4. import com.bocai.service.UserService;
  5. import com.bocai.utils.JwtUtils;
  6. import com.bocai.utils.Md5Util;
  7. import com.bocai.utils.ThreadLocalUtil;
  8. import jakarta.validation.constraints.Pattern;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.hibernate.validator.constraints.URL;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.util.StringUtils;
  13. import org.springframework.validation.annotation.Validated;
  14. import org.springframework.web.bind.annotation.*;
  15. import java.util.HashMap;
  16. import java.util.Map;
  17. @RestController
  18. @Slf4j
  19. @Validated
  20. @RequestMapping("/user")
  21. public class UserController {
  22. @Autowired
  23. private UserService userService;
  24. /**
  25. * 用户注册
  26. * @param username
  27. * @param password
  28. * @return
  29. */
  30. @PostMapping("/register")
  31. public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password){
  32. log.info("注册用户名:{},密码为:{}",username,password);
  33. // 查询用户
  34. User user = userService.queryUserByUsername(username);
  35. if (user == null){
  36. //没有占用,可以注册
  37. //注册用户
  38. userService.register(username,password);
  39. return Result.success();
  40. }else{
  41. return Result.error("用户名被占用");
  42. }
  43. }
  44. @PostMapping("/login")
  45. public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password) {
  46. log.info("登录用户名:{},密码为:{}", username, password);
  47. // 查询用户
  48. User loginUser = userService.queryUserByUsername(username);
  49. // 判断用户是否存在
  50. if (loginUser == null) {
  51. return Result.error("用户名不存在");
  52. }
  53. // 判断密码是否正确,loginUser对象中的password是密文
  54. if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
  55. // 登录成功
  56. Map<String, Object> claims = new HashMap<>();
  57. claims.put("id", loginUser.getId());
  58. claims.put("username",loginUser.getUsername());
  59. String jwt = JwtUtils.generateJwt(claims); //让jwt包含了当前登录的员工信息
  60. return Result.success(jwt);
  61. }
  62. return Result.error("密码错误!");
  63. }
  64. /**
  65. * 查询用户信息(从线程获取)
  66. * @return
  67. */
  68. @GetMapping("/userInfo")
  69. public Result userInfo(){
  70. // 从线程获取存储的jwt信息
  71. Map<String, Object> map = ThreadLocalUtil.get();
  72. String username = (String) map.get("username");
  73. log.info("查询用户全部信息,从token获取信息为:{}",username);
  74. //根据用户名查询用户
  75. User user = userService.queryUserByUsername(username);
  76. return Result.success(user);
  77. }
  78. //使用上面的的优化版本
  79. // /**
  80. // * 查询用户信息(从token获取)
  81. // * @param token
  82. // * @return
  83. // */
  84. // @GetMapping("/userInfo")
  85. // public Result userInfo(@RequestHeader(name = "Authorization")String token){
  86. // log.info("查询用户全部信息,从token获取信息为:{}",token);
  87. // //根据用户名查询用户
  88. // Map<String, Object> claims = JwtUtils.parseJWT(token);
  89. // String username = (String) claims.get("username");
  90. // User user = userService.queryUserByUsername(username);
  91. // return Result.success(user);
  92. // }
  93. /**
  94. * 更新用户
  95. * @param user
  96. * @return
  97. */
  98. @PutMapping("/update")
  99. public Result update(@RequestBody @Validated User user){
  100. log.info("修改的用户为:{}",user);
  101. userService.updateUser(user);
  102. return Result.success();
  103. }
  104. /**
  105. * 更新头像
  106. * @param avatarUrl
  107. * @return
  108. */
  109. @PatchMapping("/updateAvatar")
  110. public Result updateAvatar(@RequestParam @URL String avatarUrl){
  111. log.info("头像地址是{}",avatarUrl);
  112. userService.updateAvatar(avatarUrl);
  113. return Result.success();
  114. }
  115. /**
  116. * 更新密码
  117. * @param params json数据包含old_pwd,new_pwd,re_pwd
  118. * @return
  119. */
  120. @PatchMapping("/updatePwd")
  121. public Result updatePwd(@RequestBody Map<String, String> params){
  122. log.info("修改密码传过来数据是:{}",params);
  123. // 1、校验参数
  124. String old_pwd = params.get("old_pwd");
  125. String new_pwd = params.get("new_pwd");
  126. String re_pwd = params.get("re_pwd");
  127. if(!StringUtils.hasLength(old_pwd) || !StringUtils.hasLength(new_pwd) || !StringUtils.hasLength(re_pwd)){
  128. return Result.error("缺少必要参数!");
  129. }
  130. //原密码是否正确
  131. Map<String, Object> map = ThreadLocalUtil.get();
  132. String username = (String) map.get("username");
  133. User loginUser = userService.queryUserByUsername(username);
  134. if(!loginUser.getPassword().equals(Md5Util.getMD5String(old_pwd))){
  135. return Result.error("原密码不正确!");
  136. }
  137. //新、老密码是否一致
  138. if(old_pwd.equals(new_pwd)){
  139. return Result.error("新、老密码一样!!");
  140. }
  141. //新密码和确认密码不一致!
  142. if(!re_pwd.equals(new_pwd)){
  143. return Result.error("新密码和确认密码不一致!!");
  144. }
  145. // 2 、调用userService
  146. userService.updatePwd(new_pwd);
  147. return Result.success();
  148. }
  149. }

6.2 service

  1. package com.bocai.service;
  2. import com.bocai.pojo.User;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. /**
  5. * @author cheng
  6. * @description 针对表【user(用户表)】的数据库操作Service
  7. * @createDate 2023-11-13 19:54:41
  8. */
  9. public interface UserService extends IService<User> {
  10. /**
  11. * 用户注册
  12. * @param username
  13. * @param password
  14. */
  15. void register(String username, String password);
  16. /**
  17. * 根据用户名 --查询用户
  18. * @param username
  19. * @return
  20. */
  21. User queryUserByUsername(String username);
  22. /**
  23. * 更新用户
  24. * @param user
  25. */
  26. void updateUser(User user);
  27. /**
  28. * 更新头像
  29. * @param avatarUrl
  30. */
  31. void updateAvatar(String avatarUrl);
  32. /**
  33. * 更新密码
  34. * @param newPwd
  35. */
  36. void updatePwd(String newPwd);
  37. }

6.3 serviceImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  4. import com.bocai.pojo.User;
  5. import com.bocai.service.UserService;
  6. import com.bocai.mapper.UserMapper;
  7. import com.bocai.utils.Md5Util;
  8. import com.bocai.utils.ThreadLocalUtil;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Service;
  11. import java.time.LocalDateTime;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14. /**
  15. * @author cheng
  16. * @description 针对表【user(用户表)】的数据库操作Service实现
  17. * @createDate 2023-11-13 19:54:41
  18. */
  19. @Service
  20. public class UserServiceImpl extends ServiceImpl<UserMapper, User>
  21. implements UserService{
  22. @Autowired
  23. private UserMapper userMapper;
  24. /**
  25. * 注册
  26. * @param username
  27. * @param password
  28. */
  29. @Override
  30. public void register(String username, String password) {
  31. //密码加密
  32. String md5String = Md5Util.getMD5String(password);
  33. User user = new User();
  34. user.setUsername(username);
  35. user.setPassword(md5String);
  36. user.setCreateTime(LocalDateTime.now());
  37. user.setUpdateTime(LocalDateTime.now());
  38. userMapper.insert(user);
  39. }
  40. /**
  41. * 查询用户
  42. * @param username
  43. * @return
  44. */
  45. @Override
  46. public User queryUserByUsername(String username) {
  47. //查询用户
  48. LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  49. lambdaQueryWrapper.eq(username != null, User::getUsername,username);
  50. User user = userMapper.selectOne(lambdaQueryWrapper);
  51. return user;
  52. }
  53. /**
  54. * 更新用户
  55. * @param user
  56. */
  57. @Override
  58. public void updateUser(User user) {
  59. user.setUpdateTime(LocalDateTime.now());
  60. userMapper.updateById(user);
  61. }
  62. /**
  63. * 更新头像
  64. * @param avatarUrl
  65. */
  66. @Override
  67. public void updateAvatar(String avatarUrl) {
  68. Map<String, Object> map = ThreadLocalUtil.get();
  69. Integer id = (Integer) map.get("id");
  70. User user = new User();
  71. user.setId(id);
  72. user.setUpdateTime(LocalDateTime.now());
  73. user.setUserPic(avatarUrl);
  74. userMapper.updateById(user);
  75. }
  76. /**
  77. * 更新密码
  78. * @param newPwd
  79. */
  80. @Override
  81. public void updatePwd(String newPwd) {
  82. Map<String, Object> map = ThreadLocalUtil.get();
  83. Integer id = (Integer) map.get("id");
  84. User user = new User();
  85. user.setId(id);
  86. user.setUpdateTime(LocalDateTime.now());
  87. user.setPassword(Md5Util.getMD5String(newPwd));
  88. userMapper.updateById(user);
  89. }
  90. }

三、文章分类

1、新增文章分类

1.1 CategoryController

@Validated

  1. package com.bocai.controller;
  2. import com.bocai.common.Result;
  3. import com.bocai.pojo.Category;
  4. import com.bocai.pojo.User;
  5. import com.bocai.service.CategoryService;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.validation.annotation.Validated;
  9. import org.springframework.web.bind.annotation.PostMapping;
  10. import org.springframework.web.bind.annotation.RequestBody;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RestController;
  13. @RestController
  14. @Slf4j
  15. @RequestMapping("/category")
  16. public class CategoryController {
  17. @Autowired
  18. private CategoryService categoryService;
  19. /**
  20. * 添加文章分类
  21. * @param category
  22. * @return
  23. */
  24. @PostMapping
  25. public Result add(@RequestBody @Validated(Category.Add.class) Category category){
  26. log.info("新增的文章为:{}",category);
  27. // 查询文章分类是否已被创建
  28. Category queryCategory = categoryService.queryCategoryByCategoryName(category);
  29. if (queryCategory == null){
  30. //文章分类没有被创建
  31. categoryService.add(category);
  32. return Result.success();
  33. }else{
  34. return Result.error("文章分类被占用,不能创建重复");
  35. }
  36. }
  37. }

1.2 service

  1. package com.bocai.service;
  2. import com.bocai.pojo.Category;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. /**
  5. * @author cheng
  6. * @description 针对表【category】的数据库操作Service
  7. * @createDate 2023-11-13 19:55:04
  8. */
  9. public interface CategoryService extends IService<Category> {
  10. /**
  11. * 新增文章分类
  12. * @param category
  13. */
  14. void add(Category category);
  15. /**
  16. * 根据分类名称查询文章分类
  17. * @param category
  18. * @return
  19. */
  20. Category queryCategoryByCategoryName(Category category);
  21. }

1.3 servcieImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  4. import com.bocai.pojo.Category;
  5. import com.bocai.service.CategoryService;
  6. import com.bocai.mapper.CategoryMapper;
  7. import com.bocai.utils.ThreadLocalUtil;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Service;
  10. import java.time.LocalDateTime;
  11. import java.util.Map;
  12. /**
  13. * @author cheng
  14. * @description 针对表【category】的数据库操作Service实现
  15. * @createDate 2023-11-13 19:55:04
  16. */
  17. @Service
  18. public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
  19. implements CategoryService{
  20. @Autowired
  21. private CategoryMapper categoryMapper;
  22. /**
  23. * 新增文章分类
  24. * @param category
  25. */
  26. @Override
  27. public void add(Category category) {
  28. Map<String, Object> map = ThreadLocalUtil.get();
  29. Integer createUserId = (Integer) map.get("id");
  30. category.setCreateTime(LocalDateTime.now());
  31. category.setUpdateTime(LocalDateTime.now());
  32. category.setCreateUser(createUserId);
  33. categoryMapper.insert(category);
  34. }
  35. /**
  36. * 根据传入参数判断当前对象是否在对象中存在
  37. * @param category
  38. * @return
  39. */
  40. @Override
  41. public Category queryCategoryByCategoryName(Category category) {
  42. LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  43. lambdaQueryWrapper.eq(category.getCategoryName() != null, Category::getCategoryName,category.getCategoryName())
  44. .ne(category.getId() != null, Category::getId,category.getId()) ;
  45. Category queryCategory = categoryMapper.selectOne(lambdaQueryWrapper);
  46. return queryCategory;
  47. }
  48. }

2、文章分类列表

2.1 CategoryController

1、实体类Category指定日期返回格式   @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")

2、实体类Category   @JsonIgnore // json返回不显示

  1. package com.bocai.controller;
  2. import com.bocai.common.Result;
  3. import com.bocai.pojo.Category;
  4. import com.bocai.pojo.User;
  5. import com.bocai.service.CategoryService;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.validation.annotation.Validated;
  9. import org.springframework.web.bind.annotation.*;
  10. import java.util.List;
  11. @RestController
  12. @Slf4j
  13. @RequestMapping("/category")
  14. public class CategoryController {
  15. @Autowired
  16. private CategoryService categoryService;
  17. /**
  18. * 添加文章分类
  19. * @param category
  20. * @return
  21. */
  22. @PostMapping
  23. public Result add(@RequestBody @Validated(Category.Add.class) Category category){
  24. log.info("新增的文章为:{}",category);
  25. // 查询文章分类是否已被创建
  26. Category queryCategory = categoryService.queryCategoryByCategoryName(category);
  27. if (queryCategory == null){
  28. //文章分类没有被创建
  29. categoryService.add(category);
  30. return Result.success();
  31. }else{
  32. return Result.error("文章分类被占用,不能创建重复");
  33. }
  34. }
  35. /**
  36. * 列表查询当前登录用户创建的文章分类
  37. * @return
  38. */
  39. @GetMapping
  40. public Result list(){
  41. log.info("列表查询当前登录用户创建的文章分类");
  42. List list = categoryService.categorylist();
  43. return Result.success(list);
  44. }
  45. }

2.2 service

  1. package com.bocai.service;
  2. import com.bocai.pojo.Category;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. import java.util.List;
  5. /**
  6. * @author cheng
  7. * @description 针对表【category】的数据库操作Service
  8. * @createDate 2023-11-13 19:55:04
  9. */
  10. public interface CategoryService extends IService<Category> {
  11. /**
  12. * 新增文章分类
  13. * @param category
  14. */
  15. void add(Category category);
  16. /**
  17. * 根据分类名称查询文章分类
  18. * @param category
  19. * @return
  20. */
  21. Category queryCategoryByCategoryName(Category category);
  22. /**
  23. * 列表查询当前登录用户创建的文章分类
  24. * @return
  25. */
  26. List categorylist();
  27. }

2.3 servcieImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  4. import com.bocai.pojo.Category;
  5. import com.bocai.service.CategoryService;
  6. import com.bocai.mapper.CategoryMapper;
  7. import com.bocai.utils.ThreadLocalUtil;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Service;
  10. import java.time.LocalDateTime;
  11. import java.util.List;
  12. import java.util.Map;
  13. /**
  14. * @author cheng
  15. * @description 针对表【category】的数据库操作Service实现
  16. * @createDate 2023-11-13 19:55:04
  17. */
  18. @Service
  19. public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
  20. implements CategoryService{
  21. @Autowired
  22. private CategoryMapper categoryMapper;
  23. /**
  24. * 新增文章分类
  25. * @param category
  26. */
  27. @Override
  28. public void add(Category category) {
  29. Map<String, Object> map = ThreadLocalUtil.get();
  30. Integer createUserId = (Integer) map.get("id");
  31. category.setCreateTime(LocalDateTime.now());
  32. category.setUpdateTime(LocalDateTime.now());
  33. category.setCreateUser(createUserId);
  34. categoryMapper.insert(category);
  35. }
  36. /**
  37. * 根据传入参数判断当前对象是否在对象中存在
  38. * @param category
  39. * @return
  40. */
  41. @Override
  42. public Category queryCategoryByCategoryName(Category category) {
  43. LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  44. lambdaQueryWrapper.eq(category.getCategoryName() != null, Category::getCategoryName,category.getCategoryName())
  45. .ne(category.getId() != null, Category::getId,category.getId()) ;
  46. Category queryCategory = categoryMapper.selectOne(lambdaQueryWrapper);
  47. return queryCategory;
  48. }
  49. /**
  50. * 列表查询当前登录用户创建的文章分类
  51. * @return
  52. */
  53. @Override
  54. public List categorylist() {
  55. Map<String, Object> map = ThreadLocalUtil.get();
  56. Integer userId = (Integer) map.get("id");
  57. LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  58. lambdaQueryWrapper.eq(userId != null,Category::getCreateUser,userId);
  59. return categoryMapper.selectList(lambdaQueryWrapper);
  60. }
  61. }

3、 获取文章分类详情

3.1 CategoryController

  1. package com.bocai.controller;
  2. import com.bocai.common.Result;
  3. import com.bocai.pojo.Category;
  4. import com.bocai.pojo.User;
  5. import com.bocai.service.CategoryService;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.validation.annotation.Validated;
  9. import org.springframework.web.bind.annotation.*;
  10. import java.util.List;
  11. @RestController
  12. @Slf4j
  13. @RequestMapping("/category")
  14. public class CategoryController {
  15. @Autowired
  16. private CategoryService categoryService;
  17. /**
  18. * 添加文章分类
  19. * @param category
  20. * @return
  21. */
  22. @PostMapping
  23. public Result add(@RequestBody @Validated(Category.Add.class) Category category){
  24. log.info("新增的文章为:{}",category);
  25. // 查询文章分类是否已被创建
  26. Category queryCategory = categoryService.queryCategoryByCategoryName(category);
  27. if (queryCategory == null){
  28. //文章分类没有被创建
  29. categoryService.add(category);
  30. return Result.success();
  31. }else{
  32. return Result.error("文章分类被占用,不能创建重复");
  33. }
  34. }
  35. /**
  36. * 列表查询当前登录用户创建的文章分类
  37. * @return
  38. */
  39. @GetMapping
  40. public Result list(){
  41. log.info("列表查询当前登录用户创建的文章分类");
  42. List list = categoryService.categorylist();
  43. return Result.success(list);
  44. }
  45. /**
  46. * 根据id查询文章分类
  47. * @param id
  48. * @return
  49. */
  50. @GetMapping("/detail")
  51. public Result detail(Integer id){
  52. log.info("查询ID为:{}文章分类详情",id);
  53. Category category = categoryService.queryCategoryById(id);
  54. return Result.success(category);
  55. }
  56. }

3.2 service

  1. package com.bocai.service;
  2. import com.bocai.pojo.Category;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. import java.util.List;
  5. /**
  6. * @author cheng
  7. * @description 针对表【category】的数据库操作Service
  8. * @createDate 2023-11-13 19:55:04
  9. */
  10. public interface CategoryService extends IService<Category> {
  11. /**
  12. * 新增文章分类
  13. * @param category
  14. */
  15. void add(Category category);
  16. /**
  17. * 根据分类名称查询文章分类
  18. * @param category
  19. * @return
  20. */
  21. Category queryCategoryByCategoryName(Category category);
  22. /**
  23. * 列表查询当前登录用户创建的文章分类
  24. * @return
  25. */
  26. List categorylist();
  27. /**
  28. * 根据id查询文章分类
  29. * @param id
  30. * @return
  31. */
  32. Category queryCategoryById(Integer id);
  33. }

3.3 servcieImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  4. import com.bocai.pojo.Category;
  5. import com.bocai.service.CategoryService;
  6. import com.bocai.mapper.CategoryMapper;
  7. import com.bocai.utils.ThreadLocalUtil;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Service;
  10. import java.time.LocalDateTime;
  11. import java.util.List;
  12. import java.util.Map;
  13. /**
  14. * @author cheng
  15. * @description 针对表【category】的数据库操作Service实现
  16. * @createDate 2023-11-13 19:55:04
  17. */
  18. @Service
  19. public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
  20. implements CategoryService{
  21. @Autowired
  22. private CategoryMapper categoryMapper;
  23. /**
  24. * 新增文章分类
  25. * @param category
  26. */
  27. @Override
  28. public void add(Category category) {
  29. Map<String, Object> map = ThreadLocalUtil.get();
  30. Integer createUserId = (Integer) map.get("id");
  31. category.setCreateTime(LocalDateTime.now());
  32. category.setUpdateTime(LocalDateTime.now());
  33. category.setCreateUser(createUserId);
  34. categoryMapper.insert(category);
  35. }
  36. /**
  37. * 根据传入参数判断当前对象是否在对象中存在
  38. * @param category
  39. * @return
  40. */
  41. @Override
  42. public Category queryCategoryByCategoryName(Category category) {
  43. LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  44. lambdaQueryWrapper.eq(category.getCategoryName() != null, Category::getCategoryName,category.getCategoryName())
  45. .ne(category.getId() != null, Category::getId,category.getId()) ;
  46. Category queryCategory = categoryMapper.selectOne(lambdaQueryWrapper);
  47. return queryCategory;
  48. }
  49. /**
  50. * 列表查询当前登录用户创建的文章分类
  51. * @return
  52. */
  53. @Override
  54. public List categorylist() {
  55. Map<String, Object> map = ThreadLocalUtil.get();
  56. Integer userId = (Integer) map.get("id");
  57. LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  58. lambdaQueryWrapper.eq(userId != null,Category::getCreateUser,userId);
  59. return categoryMapper.selectList(lambdaQueryWrapper);
  60. }
  61. /**
  62. * 根据id查询文章分类
  63. * @param id
  64. * @return
  65. */
  66. @Override
  67. public Category queryCategoryById(Integer id) {
  68. return categoryMapper.selectById(id);
  69. }
  70. }

4、更新文章分类

4.1 CategoryController

分组校验,这里主要原因是实体id字段新增不需要验证,修改需要验证。

在实体类进行修改,然后在CategoryController指定使用哪个分组

  1. package com.bocai.controller;
  2. import com.bocai.common.Result;
  3. import com.bocai.pojo.Category;
  4. import com.bocai.pojo.User;
  5. import com.bocai.service.CategoryService;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.validation.annotation.Validated;
  9. import org.springframework.web.bind.annotation.*;
  10. import java.util.List;
  11. @RestController
  12. @Slf4j
  13. @RequestMapping("/category")
  14. public class CategoryController {
  15. @Autowired
  16. private CategoryService categoryService;
  17. /**
  18. * 添加文章分类
  19. * @param category
  20. * @return
  21. */
  22. @PostMapping
  23. public Result add(@RequestBody @Validated(Category.Add.class) Category category){
  24. log.info("新增的文章为:{}",category);
  25. // 查询文章分类是否已被创建
  26. Category queryCategory = categoryService.queryCategoryByCategoryName(category);
  27. if (queryCategory == null){
  28. //文章分类没有被创建
  29. categoryService.add(category);
  30. return Result.success();
  31. }else{
  32. return Result.error("文章分类被占用,不能创建重复");
  33. }
  34. }
  35. /**
  36. * 列表查询当前登录用户创建的文章分类
  37. * @return
  38. */
  39. @GetMapping
  40. public Result list(){
  41. log.info("列表查询当前登录用户创建的文章分类");
  42. List list = categoryService.categorylist();
  43. return Result.success(list);
  44. }
  45. /**
  46. * 根据id查询文章分类
  47. * @param id
  48. * @return
  49. */
  50. @GetMapping("/detail")
  51. public Result detail(Integer id){
  52. log.info("查询ID为:{}文章分类详情",id);
  53. Category category = categoryService.queryCategoryById(id);
  54. return Result.success(category);
  55. }
  56. /**
  57. * 根据id修改文章分类
  58. * @param category
  59. * @return
  60. */
  61. @PutMapping
  62. public Result update(@RequestBody @Validated(Category.Update.class) Category category) {
  63. log.info("修改的文章分类为:{}", category);
  64. // 查询文章分类是否已被创建
  65. Category queryCategory = categoryService.queryCategoryByCategoryName(category);
  66. if (queryCategory == null){
  67. //文章分类没有重复
  68. categoryService.updateCategoryById(category);
  69. return Result.success();
  70. }else{
  71. return Result.error("文章分类被占用,不能修改为重复");
  72. }
  73. }
  74. }

4.2 service

  1. package com.bocai.service;
  2. import com.bocai.pojo.Category;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. import java.util.List;
  5. /**
  6. * @author cheng
  7. * @description 针对表【category】的数据库操作Service
  8. * @createDate 2023-11-13 19:55:04
  9. */
  10. public interface CategoryService extends IService<Category> {
  11. /**
  12. * 新增文章分类
  13. * @param category
  14. */
  15. void add(Category category);
  16. /**
  17. * 根据分类名称查询文章分类
  18. * @param category
  19. * @return
  20. */
  21. Category queryCategoryByCategoryName(Category category);
  22. /**
  23. * 列表查询当前登录用户创建的文章分类
  24. * @return
  25. */
  26. List categorylist();
  27. /**
  28. * 根据id查询文章分类
  29. * @param id
  30. * @return
  31. */
  32. Category queryCategoryById(Integer id);
  33. /**
  34. * 根据id修改文章分类
  35. * @param category
  36. */
  37. void updateCategoryById(Category category);
  38. }

4.3 servcieImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  4. import com.bocai.pojo.Category;
  5. import com.bocai.service.CategoryService;
  6. import com.bocai.mapper.CategoryMapper;
  7. import com.bocai.utils.ThreadLocalUtil;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Service;
  10. import java.time.LocalDateTime;
  11. import java.util.List;
  12. import java.util.Map;
  13. /**
  14. * @author cheng
  15. * @description 针对表【category】的数据库操作Service实现
  16. * @createDate 2023-11-13 19:55:04
  17. */
  18. @Service
  19. public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
  20. implements CategoryService{
  21. @Autowired
  22. private CategoryMapper categoryMapper;
  23. /**
  24. * 新增文章分类
  25. * @param category
  26. */
  27. @Override
  28. public void add(Category category) {
  29. Map<String, Object> map = ThreadLocalUtil.get();
  30. Integer createUserId = (Integer) map.get("id");
  31. category.setCreateTime(LocalDateTime.now());
  32. category.setUpdateTime(LocalDateTime.now());
  33. category.setCreateUser(createUserId);
  34. categoryMapper.insert(category);
  35. }
  36. /**
  37. * 根据传入参数判断当前对象是否在对象中存在
  38. * @param category
  39. * @return
  40. */
  41. @Override
  42. public Category queryCategoryByCategoryName(Category category) {
  43. LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  44. lambdaQueryWrapper.eq(category.getCategoryName() != null, Category::getCategoryName,category.getCategoryName())
  45. .ne(category.getId() != null, Category::getId,category.getId()) ;
  46. Category queryCategory = categoryMapper.selectOne(lambdaQueryWrapper);
  47. return queryCategory;
  48. }
  49. /**
  50. * 列表查询当前登录用户创建的文章分类
  51. * @return
  52. */
  53. @Override
  54. public List categorylist() {
  55. Map<String, Object> map = ThreadLocalUtil.get();
  56. Integer userId = (Integer) map.get("id");
  57. LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  58. lambdaQueryWrapper.eq(userId != null,Category::getCreateUser,userId);
  59. return categoryMapper.selectList(lambdaQueryWrapper);
  60. }
  61. /**
  62. * 根据id查询文章分类
  63. * @param id
  64. * @return
  65. */
  66. @Override
  67. public Category queryCategoryById(Integer id) {
  68. return categoryMapper.selectById(id);
  69. }
  70. /**
  71. * 根据id修改文章分类
  72. * @param category
  73. */
  74. @Override
  75. public void updateCategoryById(Category category) {
  76. category.setUpdateTime(LocalDateTime.now());
  77. categoryMapper.updateById(category);
  78. }
  79. }

5、删除文章分类

5.1 CategoryController

  1. package com.bocai.controller;
  2. import com.bocai.common.Result;
  3. import com.bocai.pojo.Category;
  4. import com.bocai.pojo.User;
  5. import com.bocai.service.CategoryService;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.apache.ibatis.annotations.Delete;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.validation.annotation.Validated;
  10. import org.springframework.web.bind.annotation.*;
  11. import java.util.List;
  12. @RestController
  13. @Slf4j
  14. @RequestMapping("/category")
  15. public class CategoryController {
  16. @Autowired
  17. private CategoryService categoryService;
  18. /**
  19. * 添加文章分类
  20. * @param category
  21. * @return
  22. */
  23. @PostMapping
  24. public Result add(@RequestBody @Validated(Category.Add.class) Category category){
  25. log.info("新增的文章为:{}",category);
  26. // 查询文章分类是否已被创建
  27. Category queryCategory = categoryService.queryCategoryByCategoryName(category);
  28. if (queryCategory == null){
  29. //文章分类没有被创建
  30. categoryService.add(category);
  31. return Result.success();
  32. }else{
  33. return Result.error("文章分类被占用,不能创建重复");
  34. }
  35. }
  36. /**
  37. * 列表查询当前登录用户创建的文章分类
  38. * @return
  39. */
  40. @GetMapping
  41. public Result list(){
  42. log.info("列表查询当前登录用户创建的文章分类");
  43. List list = categoryService.categorylist();
  44. return Result.success(list);
  45. }
  46. /**
  47. * 根据id查询文章分类
  48. * @param id
  49. * @return
  50. */
  51. @GetMapping("/detail")
  52. public Result detail(Integer id){
  53. log.info("查询ID为:{}文章分类详情",id);
  54. Category category = categoryService.queryCategoryById(id);
  55. return Result.success(category);
  56. }
  57. /**
  58. * 根据id修改文章分类
  59. * @param category
  60. * @return
  61. */
  62. @PutMapping
  63. public Result update(@RequestBody @Validated(Category.Update.class) Category category) {
  64. log.info("修改的文章分类为:{}", category);
  65. // 查询文章分类是否已被创建
  66. Category queryCategory = categoryService.queryCategoryByCategoryName(category);
  67. if (queryCategory == null){
  68. //文章分类没有重复
  69. categoryService.updateCategoryById(category);
  70. return Result.success();
  71. }else{
  72. return Result.error("文章分类被占用,不能修改为重复");
  73. }
  74. }
  75. /**
  76. * 根据id删除文章分类
  77. * @param id
  78. * @return
  79. */
  80. @DeleteMapping
  81. public Result delete(Integer id){
  82. log.info("根据id删除文章分类{}",id);
  83. categoryService.deleteCategoryById(id);
  84. return Result.success();
  85. }
  86. }

5.2 service

  1. package com.bocai.service;
  2. import com.bocai.pojo.Category;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. import java.util.List;
  5. /**
  6. * @author cheng
  7. * @description 针对表【category】的数据库操作Service
  8. * @createDate 2023-11-13 19:55:04
  9. */
  10. public interface CategoryService extends IService<Category> {
  11. /**
  12. * 新增文章分类
  13. * @param category
  14. */
  15. void add(Category category);
  16. /**
  17. * 根据分类名称查询文章分类
  18. * @param category
  19. * @return
  20. */
  21. Category queryCategoryByCategoryName(Category category);
  22. /**
  23. * 列表查询当前登录用户创建的文章分类
  24. * @return
  25. */
  26. List categorylist();
  27. /**
  28. * 根据id查询文章分类
  29. * @param id
  30. * @return
  31. */
  32. Category queryCategoryById(Integer id);
  33. /**
  34. * 根据id修改文章分类
  35. * @param category
  36. */
  37. void updateCategoryById(Category category);
  38. /**
  39. * 根据id删除文章分类
  40. * @param id
  41. */
  42. void deleteCategoryById(Integer id);
  43. }

5.3 servcieImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  4. import com.bocai.pojo.Category;
  5. import com.bocai.service.CategoryService;
  6. import com.bocai.mapper.CategoryMapper;
  7. import com.bocai.utils.ThreadLocalUtil;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Service;
  10. import java.time.LocalDateTime;
  11. import java.util.List;
  12. import java.util.Map;
  13. /**
  14. * @author cheng
  15. * @description 针对表【category】的数据库操作Service实现
  16. * @createDate 2023-11-13 19:55:04
  17. */
  18. @Service
  19. public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
  20. implements CategoryService{
  21. @Autowired
  22. private CategoryMapper categoryMapper;
  23. /**
  24. * 新增文章分类
  25. * @param category
  26. */
  27. @Override
  28. public void add(Category category) {
  29. Map<String, Object> map = ThreadLocalUtil.get();
  30. Integer createUserId = (Integer) map.get("id");
  31. category.setCreateTime(LocalDateTime.now());
  32. category.setUpdateTime(LocalDateTime.now());
  33. category.setCreateUser(createUserId);
  34. categoryMapper.insert(category);
  35. }
  36. @Override
  37. public Category queryCategoryByCategoryName(String categoryName) {
  38. LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  39. lambdaQueryWrapper.eq(categoryName != null, Category::getCategoryName,categoryName);
  40. Category category = categoryMapper.selectOne(lambdaQueryWrapper);
  41. return category;
  42. }
  43. /**
  44. * 列表查询当前登录用户创建的文章分类
  45. * @return
  46. */
  47. @Override
  48. public List categorylist() {
  49. Map<String, Object> map = ThreadLocalUtil.get();
  50. Integer userId = (Integer) map.get("id");
  51. LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  52. lambdaQueryWrapper.eq(userId != null,Category::getCreateUser,userId);
  53. return categoryMapper.selectList(lambdaQueryWrapper);
  54. }
  55. /**
  56. * 根据id查询文章分类
  57. * @param id
  58. * @return
  59. */
  60. @Override
  61. public Category queryCategoryById(Integer id) {
  62. return categoryMapper.selectById(id);
  63. }
  64. /**
  65. * 根据id修改文章分类
  66. * @param category
  67. */
  68. @Override
  69. public void updateCategoryById(Category category) {
  70. category.setUpdateTime(LocalDateTime.now());
  71. categoryMapper.updateById(category);
  72. }
  73. /**
  74. * 根据id删除文章分类
  75. * @param id
  76. */
  77. @Override
  78. public void deleteCategoryById(Integer id) {
  79. categoryMapper.deleteById(id);
  80. }
  81. }

四、文章管理

1、新增文章

1.1 ArticleCtroller

自定义校验

  1. package com.bocai.controller;
  2. import com.bocai.common.Result;
  3. import com.bocai.pojo.Article;
  4. import com.bocai.pojo.Category;
  5. import com.bocai.service.ArticleService;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.validation.annotation.Validated;
  9. import org.springframework.web.bind.annotation.PostMapping;
  10. import org.springframework.web.bind.annotation.RequestBody;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RestController;
  13. @RestController
  14. @Slf4j
  15. @RequestMapping("/article")
  16. public class ArticleCtroller {
  17. @Autowired
  18. private ArticleService articleService;
  19. /**
  20. * 添加文章
  21. * @param article
  22. * @return
  23. */
  24. @PostMapping
  25. public Result add(@RequestBody @Validated Article article){
  26. log.info("新增文章为:{}",article);
  27. //查询文章标题是否被创建
  28. Article queryArticle = articleService.queryArticleByTitle(article);
  29. if(queryArticle == null){
  30. //没有重复的文章标题
  31. articleService.add(article);
  32. return Result.success();
  33. }
  34. else {
  35. // 存在重复文章标题
  36. return Result.error("文章标题重复!");
  37. }
  38. }
  39. }

1.2 service

  1. package com.bocai.service;
  2. import com.bocai.pojo.Article;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. /**
  5. * @author cheng
  6. * @description 针对表【article】的数据库操作Service
  7. * @createDate 2023-11-13 19:55:11
  8. */
  9. public interface ArticleService extends IService<Article> {
  10. /**
  11. * 新增文章
  12. * @param article
  13. */
  14. void add(Article article);
  15. /**
  16. * 根据文章标题查询文章
  17. * @param article
  18. * @return
  19. */
  20. Article queryArticleByTitle(Article article);
  21. }

1.3 serviceImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  4. import com.bocai.pojo.Article;
  5. import com.bocai.pojo.Category;
  6. import com.bocai.service.ArticleService;
  7. import com.bocai.mapper.ArticleMapper;
  8. import com.bocai.utils.ThreadLocalUtil;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Service;
  11. import java.time.LocalDateTime;
  12. import java.util.Map;
  13. /**
  14. * @author cheng
  15. * @description 针对表【article】的数据库操作Service实现
  16. * @createDate 2023-11-13 19:55:11
  17. */
  18. @Service
  19. public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>
  20. implements ArticleService{
  21. @Autowired
  22. private ArticleMapper articleMapper;
  23. /**
  24. * 新增文章
  25. * @param article
  26. */
  27. @Override
  28. public void add(Article article) {
  29. Map<String, Object> map = ThreadLocalUtil.get();
  30. Integer createUserId = (Integer) map.get("id");
  31. article.setCreateUser(createUserId);
  32. article.setCreateTime(LocalDateTime.now());
  33. article.setUpdateTime(LocalDateTime.now());
  34. articleMapper.insert(article);
  35. }
  36. /**
  37. * 根据文章标题查询文章
  38. * @param article
  39. * @return
  40. */
  41. @Override
  42. public Article queryArticleByTitle(Article article) {
  43. LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  44. lambdaQueryWrapper.eq(article.getTitle() != null, Article::getTitle,article.getTitle())
  45. .ne(article.getId() != null,Article::getId,article.getId());
  46. return articleMapper.selectOne(lambdaQueryWrapper);
  47. }
  48. }

2、文章列表(条件分页)

2.1 ArticleCtroller

  1. package com.bocai.controller;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
  4. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  5. import com.bocai.common.Result;
  6. import com.bocai.pojo.Article;
  7. import com.bocai.pojo.Category;
  8. import com.bocai.pojo.Emp;
  9. import com.bocai.pojo.PageBean;
  10. import com.bocai.service.ArticleService;
  11. import lombok.extern.slf4j.Slf4j;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.format.annotation.DateTimeFormat;
  14. import org.springframework.validation.annotation.Validated;
  15. import org.springframework.web.bind.annotation.*;
  16. import java.time.LocalDate;
  17. @RestController
  18. @Slf4j
  19. @RequestMapping("/article")
  20. public class ArticleCtroller {
  21. @Autowired
  22. private ArticleService articleService;
  23. /**
  24. * 添加文章
  25. * @param article
  26. * @return
  27. */
  28. @PostMapping
  29. public Result add(@RequestBody @Validated Article article){
  30. log.info("新增文章为:{}",article);
  31. //查询文章标题是否被创建
  32. Article queryArticle = articleService.queryArticleByTitle(article);
  33. if(queryArticle == null){
  34. //没有重复的文章标题
  35. articleService.add(article);
  36. return Result.success();
  37. }
  38. else {
  39. // 存在重复文章标题
  40. return Result.error("文章标题重复!");
  41. }
  42. }
  43. /**
  44. * 文章根据条件查询,并分页
  45. * @param pageNum
  46. * @param pageSize
  47. * @param categoryId
  48. * @param state
  49. * @return
  50. */
  51. @GetMapping
  52. public Result page(@RequestParam(defaultValue = "1") Integer pageNum,
  53. @RequestParam(defaultValue = "10") Integer pageSize,
  54. String categoryId, String state){
  55. log.info("分页查询参数:当前页:{} 每页条数: {} 文章分类ID:{} 状态:{} ",pageNum,pageSize,categoryId,state);
  56. PageBean pageBean = articleService.pageList(pageNum,pageSize,categoryId,state);
  57. return Result.success(pageBean);
  58. }
  59. }

2.2 service

  1. package com.bocai.service;
  2. import com.bocai.pojo.Article;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. import com.bocai.pojo.PageBean;
  5. /**
  6. * @author cheng
  7. * @description 针对表【article】的数据库操作Service
  8. * @createDate 2023-11-13 19:55:11
  9. */
  10. public interface ArticleService extends IService<Article> {
  11. /**
  12. * 新增文章
  13. * @param article
  14. */
  15. void add(Article article);
  16. /**
  17. * 根据文章标题查询文章
  18. * @param article
  19. * @return
  20. */
  21. Article queryArticleByTitle(Article article);
  22. /**
  23. * 文章根据条件查询,并分页
  24. * @param pageNum 当前页码
  25. * @param pageSize 每页条数
  26. * @param categoryId 文章分类ID
  27. * @param state 状态
  28. * @return
  29. */
  30. PageBean pageList(Integer pageNum, Integer pageSize, String categoryId, String state);
  31. }

2.3 serviceImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
  4. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  5. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  6. import com.bocai.pojo.Article;
  7. import com.bocai.pojo.Category;
  8. import com.bocai.pojo.PageBean;
  9. import com.bocai.service.ArticleService;
  10. import com.bocai.mapper.ArticleMapper;
  11. import com.bocai.utils.ThreadLocalUtil;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.stereotype.Service;
  14. import java.time.LocalDateTime;
  15. import java.util.Map;
  16. /**
  17. * @author cheng
  18. * @description 针对表【article】的数据库操作Service实现
  19. * @createDate 2023-11-13 19:55:11
  20. */
  21. @Service
  22. public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>
  23. implements ArticleService{
  24. @Autowired
  25. private ArticleMapper articleMapper;
  26. /**
  27. * 新增文章
  28. * @param article
  29. */
  30. @Override
  31. public void add(Article article) {
  32. Map<String, Object> map = ThreadLocalUtil.get();
  33. Integer createUserId = (Integer) map.get("id");
  34. article.setCreateUser(createUserId);
  35. article.setCreateTime(LocalDateTime.now());
  36. article.setUpdateTime(LocalDateTime.now());
  37. articleMapper.insert(article);
  38. }
  39. /**
  40. * 根据文章标题查询文章
  41. * @param article
  42. * @return
  43. */
  44. @Override
  45. public Article queryArticleByTitle(Article article) {
  46. LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  47. lambdaQueryWrapper.eq(article.getTitle() != null, Article::getTitle,article.getTitle())
  48. .ne(article.getId() != null,Article::getId,article.getId());
  49. return articleMapper.selectOne(lambdaQueryWrapper);
  50. }
  51. /**
  52. * 文章根据条件查询,并分页
  53. * @param pageNum 当前页码
  54. * @param pageSize 每页条数
  55. * @param categoryId 文章分类ID
  56. * @param state 状态
  57. * @return
  58. */
  59. @Override
  60. public PageBean pageList(Integer pageNum, Integer pageSize, String categoryId, String state) {
  61. Map<String,Object> map = ThreadLocalUtil.get();
  62. String userId = (String) map.get("id");
  63. LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  64. lambdaQueryWrapper.eq(categoryId != null,Article::getCategoryId,categoryId)
  65. .eq(state != null,Article::getState,state)
  66. .eq(userId != null,Article::getCreateUser,userId);
  67. Page<Article> pageArticle = new Page<>(pageNum,pageSize);
  68. articleMapper.selectPage(pageArticle,lambdaQueryWrapper);
  69. PageBean pageBean = new PageBean(pageArticle.getTotal(),pageArticle.getRecords());
  70. return pageBean;
  71. }
  72. }

3、获取文章详情

3.1 ArticleCtroller

  1. package com.bocai.controller;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
  4. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  5. import com.bocai.common.Result;
  6. import com.bocai.pojo.Article;
  7. import com.bocai.pojo.Category;
  8. import com.bocai.pojo.Emp;
  9. import com.bocai.pojo.PageBean;
  10. import com.bocai.service.ArticleService;
  11. import lombok.extern.slf4j.Slf4j;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.format.annotation.DateTimeFormat;
  14. import org.springframework.validation.annotation.Validated;
  15. import org.springframework.web.bind.annotation.*;
  16. import java.time.LocalDate;
  17. @RestController
  18. @Slf4j
  19. @RequestMapping("/article")
  20. public class ArticleCtroller {
  21. @Autowired
  22. private ArticleService articleService;
  23. /**
  24. * 添加文章
  25. * @param article
  26. * @return
  27. */
  28. @PostMapping
  29. public Result add(@RequestBody @Validated Article article){
  30. log.info("新增文章为:{}",article);
  31. //查询文章标题是否被创建
  32. String articleTitle = article.getTitle();
  33. Article queryArticle = articleService.queryArticleByTitle(articleTitle);
  34. if(queryArticle == null){
  35. //没有重复的文章标题
  36. articleService.add(article);
  37. return Result.success();
  38. }
  39. else {
  40. // 存在重复文章标题
  41. return Result.error("文章标题重复!");
  42. }
  43. }
  44. /**
  45. * 文章根据条件查询,并分页
  46. * @param pageNum
  47. * @param pageSize
  48. * @param categoryId
  49. * @param state
  50. * @return
  51. */
  52. @GetMapping
  53. public Result page(@RequestParam(defaultValue = "1") Integer pageNum,
  54. @RequestParam(defaultValue = "10") Integer pageSize,
  55. String categoryId, String state){
  56. log.info("分页查询参数:当前页:{} 每页条数: {} 文章分类ID:{} 状态:{} ",pageNum,pageSize,categoryId,state);
  57. PageBean pageBean = articleService.pageList(pageNum,pageSize,categoryId,state);
  58. return Result.success(pageBean);
  59. }
  60. /**
  61. * 文章详情
  62. * @param id
  63. * @return
  64. */
  65. @GetMapping("/detail")
  66. public Result detail(Integer id){
  67. log.info("文章id{}详情",id);
  68. Article article = articleService.detail(id);
  69. return Result.success(article);
  70. }
  71. }

3.2 service

  1. package com.bocai.service;
  2. import com.bocai.pojo.Article;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. import com.bocai.pojo.PageBean;
  5. /**
  6. * @author cheng
  7. * @description 针对表【article】的数据库操作Service
  8. * @createDate 2023-11-13 19:55:11
  9. */
  10. public interface ArticleService extends IService<Article> {
  11. /**
  12. * 新增文章
  13. * @param article
  14. */
  15. void add(Article article);
  16. /**
  17. * 根据文章标题查询文章
  18. * @param articleTitle
  19. * @return
  20. */
  21. Article queryArticleByTitle(String articleTitle);
  22. /**
  23. * 文章根据条件查询,并分页
  24. * @param pageNum 当前页码
  25. * @param pageSize 每页条数
  26. * @param categoryId 文章分类ID
  27. * @param state 状态
  28. * @return
  29. */
  30. PageBean pageList(Integer pageNum, Integer pageSize, String categoryId, String state);
  31. /**
  32. * 文章详情
  33. * @param id
  34. * @return
  35. */
  36. Article detail(Integer id);
  37. }

3.3 serviceImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
  4. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  5. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  6. import com.bocai.pojo.Article;
  7. import com.bocai.pojo.Category;
  8. import com.bocai.pojo.PageBean;
  9. import com.bocai.service.ArticleService;
  10. import com.bocai.mapper.ArticleMapper;
  11. import com.bocai.utils.ThreadLocalUtil;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.stereotype.Service;
  14. import java.time.LocalDateTime;
  15. import java.util.Map;
  16. /**
  17. * @author cheng
  18. * @description 针对表【article】的数据库操作Service实现
  19. * @createDate 2023-11-13 19:55:11
  20. */
  21. @Service
  22. public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>
  23. implements ArticleService{
  24. @Autowired
  25. private ArticleMapper articleMapper;
  26. /**
  27. * 新增文章
  28. * @param article
  29. */
  30. @Override
  31. public void add(Article article) {
  32. Map<String, Object> map = ThreadLocalUtil.get();
  33. Integer createUserId = (Integer) map.get("id");
  34. article.setCreateUser(createUserId);
  35. article.setCreateTime(LocalDateTime.now());
  36. article.setUpdateTime(LocalDateTime.now());
  37. articleMapper.insert(article);
  38. }
  39. /**
  40. * 根据文章标题查询文章
  41. * @param articleTitle
  42. * @return
  43. */
  44. @Override
  45. public Article queryArticleByTitle(String articleTitle) {
  46. LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  47. lambdaQueryWrapper.eq(articleTitle != null, Article::getTitle,articleTitle);
  48. return articleMapper.selectOne(lambdaQueryWrapper);
  49. }
  50. /**
  51. * 文章根据条件查询,并分页
  52. * @param pageNum 当前页码
  53. * @param pageSize 每页条数
  54. * @param categoryId 文章分类ID
  55. * @param state 状态
  56. * @return
  57. */
  58. @Override
  59. public PageBean pageList(Integer pageNum, Integer pageSize, String categoryId, String state) {
  60. Map<String,Object> map = ThreadLocalUtil.get();
  61. String userId = (String) map.get("id");
  62. LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  63. lambdaQueryWrapper.eq(categoryId != null,Article::getCategoryId,categoryId)
  64. .eq(state != null,Article::getState,state)
  65. .eq(userId != null,Article::getCreateUser,userId);
  66. Page<Article> pageArticle = new Page<>(pageNum,pageSize);
  67. articleMapper.selectPage(pageArticle,lambdaQueryWrapper);
  68. PageBean pageBean = new PageBean(pageArticle.getTotal(),pageArticle.getRecords());
  69. return pageBean;
  70. }
  71. /**
  72. * 文章详情
  73. * @param id
  74. * @return
  75. */
  76. @Override
  77. public Article detail(Integer id) {
  78. return articleMapper.selectById(id);
  79. }
  80. }

4、更新文章

4.1 ArticleCtroller

  1. package com.bocai.controller;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
  4. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  5. import com.bocai.common.Result;
  6. import com.bocai.pojo.Article;
  7. import com.bocai.pojo.Category;
  8. import com.bocai.pojo.Emp;
  9. import com.bocai.pojo.PageBean;
  10. import com.bocai.service.ArticleService;
  11. import lombok.extern.slf4j.Slf4j;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.format.annotation.DateTimeFormat;
  14. import org.springframework.validation.annotation.Validated;
  15. import org.springframework.web.bind.annotation.*;
  16. import java.time.LocalDate;
  17. @RestController
  18. @Slf4j
  19. @RequestMapping("/article")
  20. public class ArticleCtroller {
  21. @Autowired
  22. private ArticleService articleService;
  23. /**
  24. * 添加文章
  25. * @param article
  26. * @return
  27. */
  28. @PostMapping
  29. public Result add(@RequestBody @Validated(Article.Add.class) Article article){
  30. log.info("新增文章为:{}",article);
  31. //查询文章标题是否被创建
  32. Article queryArticle = articleService.queryArticleByTitle(article);
  33. if(queryArticle == null){
  34. //没有重复的文章标题
  35. articleService.add(article);
  36. return Result.success();
  37. }
  38. else {
  39. // 存在重复文章标题
  40. return Result.error("文章标题重复!");
  41. }
  42. }
  43. /**
  44. * 文章根据条件查询,并分页
  45. * @param pageNum
  46. * @param pageSize
  47. * @param categoryId
  48. * @param state
  49. * @return
  50. */
  51. @GetMapping
  52. public Result page(@RequestParam(defaultValue = "1") Integer pageNum,
  53. @RequestParam(defaultValue = "10") Integer pageSize,
  54. String categoryId, String state){
  55. log.info("分页查询参数:当前页:{} 每页条数: {} 文章分类ID:{} 状态:{} ",pageNum,pageSize,categoryId,state);
  56. PageBean pageBean = articleService.pageList(pageNum,pageSize,categoryId,state);
  57. return Result.success(pageBean);
  58. }
  59. /**
  60. * 文章详情
  61. * @param id
  62. * @return
  63. */
  64. @GetMapping("/detail")
  65. public Result detail(Integer id){
  66. log.info("文章id{}详情",id);
  67. Article article = articleService.detail(id);
  68. return Result.success(article);
  69. }
  70. /**
  71. * 根据id更新文章
  72. * @param article
  73. * @return
  74. */
  75. @PutMapping
  76. public Result update(@RequestBody @Validated(Article.Update.class) Article article){
  77. log.info("根据id更新文章这些属性{}",article);
  78. Article queryArticle = articleService.queryArticleByTitle(article);
  79. if(queryArticle == null){
  80. articleService.updateArticleById(article);
  81. return Result.success();
  82. }else {
  83. return Result.error("不能修改为文章标题重复名称");
  84. }
  85. }
  86. }

4.2 service

  1. package com.bocai.service;
  2. import com.bocai.pojo.Article;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. import com.bocai.pojo.PageBean;
  5. /**
  6. * @author cheng
  7. * @description 针对表【article】的数据库操作Service
  8. * @createDate 2023-11-13 19:55:11
  9. */
  10. public interface ArticleService extends IService<Article> {
  11. /**
  12. * 新增文章
  13. * @param article
  14. */
  15. void add(Article article);
  16. /**
  17. * 根据文章标题查询文章
  18. * @param article
  19. * @return
  20. */
  21. Article queryArticleByTitle(Article article);
  22. /**
  23. * 文章根据条件查询,并分页
  24. * @param pageNum 当前页码
  25. * @param pageSize 每页条数
  26. * @param categoryId 文章分类ID
  27. * @param state 状态
  28. * @return
  29. */
  30. PageBean pageList(Integer pageNum, Integer pageSize, String categoryId, String state);
  31. /**
  32. * 文章详情
  33. * @param id
  34. * @return
  35. */
  36. Article detail(Integer id);
  37. /**
  38. * 根据id更新文章
  39. * @param article
  40. */
  41. void updateArticleById(Article article);
  42. }

4.3 serviceImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
  4. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  5. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  6. import com.bocai.pojo.Article;
  7. import com.bocai.pojo.Category;
  8. import com.bocai.pojo.PageBean;
  9. import com.bocai.service.ArticleService;
  10. import com.bocai.mapper.ArticleMapper;
  11. import com.bocai.utils.ThreadLocalUtil;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.stereotype.Service;
  14. import java.time.LocalDateTime;
  15. import java.util.Map;
  16. /**
  17. * @author cheng
  18. * @description 针对表【article】的数据库操作Service实现
  19. * @createDate 2023-11-13 19:55:11
  20. */
  21. @Service
  22. public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>
  23. implements ArticleService{
  24. @Autowired
  25. private ArticleMapper articleMapper;
  26. /**
  27. * 新增文章
  28. * @param article
  29. */
  30. @Override
  31. public void add(Article article) {
  32. Map<String, Object> map = ThreadLocalUtil.get();
  33. Integer createUserId = (Integer) map.get("id");
  34. article.setCreateUser(createUserId);
  35. article.setCreateTime(LocalDateTime.now());
  36. article.setUpdateTime(LocalDateTime.now());
  37. articleMapper.insert(article);
  38. }
  39. /**
  40. * 根据文章标题查询文章
  41. * @param article
  42. * @return
  43. */
  44. @Override
  45. public Article queryArticleByTitle(Article article) {
  46. LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  47. lambdaQueryWrapper.eq(article.getTitle() != null, Article::getTitle,article.getTitle())
  48. .ne(article.getId() != null,Article::getId,article.getId());
  49. return articleMapper.selectOne(lambdaQueryWrapper);
  50. }
  51. /**
  52. * 文章根据条件查询,并分页
  53. * @param pageNum 当前页码
  54. * @param pageSize 每页条数
  55. * @param categoryId 文章分类ID
  56. * @param state 状态
  57. * @return
  58. */
  59. @Override
  60. public PageBean pageList(Integer pageNum, Integer pageSize, String categoryId, String state) {
  61. Map<String,Object> map = ThreadLocalUtil.get();
  62. String userId = (String) map.get("id");
  63. LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  64. lambdaQueryWrapper.eq(categoryId != null,Article::getCategoryId,categoryId)
  65. .eq(state != null,Article::getState,state)
  66. .eq(userId != null,Article::getCreateUser,userId);
  67. Page<Article> pageArticle = new Page<>(pageNum,pageSize);
  68. articleMapper.selectPage(pageArticle,lambdaQueryWrapper);
  69. PageBean pageBean = new PageBean(pageArticle.getTotal(),pageArticle.getRecords());
  70. return pageBean;
  71. }
  72. /**
  73. * 文章详情
  74. * @param id
  75. * @return
  76. */
  77. @Override
  78. public Article detail(Integer id) {
  79. return articleMapper.selectById(id);
  80. }
  81. /**
  82. * 根据id更新文章
  83. * @param article
  84. */
  85. @Override
  86. public void updateArticleById(Article article) {
  87. article.setUpdateTime(LocalDateTime.now());
  88. articleMapper.updateById(article);
  89. }
  90. }

5、删除文章

5.1 ArticleCtroller

  1. package com.bocai.controller;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
  4. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  5. import com.bocai.common.Result;
  6. import com.bocai.pojo.Article;
  7. import com.bocai.pojo.Category;
  8. import com.bocai.pojo.Emp;
  9. import com.bocai.pojo.PageBean;
  10. import com.bocai.service.ArticleService;
  11. import lombok.extern.slf4j.Slf4j;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.format.annotation.DateTimeFormat;
  14. import org.springframework.validation.annotation.Validated;
  15. import org.springframework.web.bind.annotation.*;
  16. import java.time.LocalDate;
  17. @RestController
  18. @Slf4j
  19. @RequestMapping("/article")
  20. public class ArticleCtroller {
  21. @Autowired
  22. private ArticleService articleService;
  23. /**
  24. * 添加文章
  25. * @param article
  26. * @return
  27. */
  28. @PostMapping
  29. public Result add(@RequestBody @Validated(Article.Add.class) Article article){
  30. log.info("新增文章为:{}",article);
  31. //查询文章标题是否被创建
  32. Article queryArticle = articleService.queryArticleByTitle(article);
  33. if(queryArticle == null){
  34. //没有重复的文章标题
  35. articleService.add(article);
  36. return Result.success();
  37. }
  38. else {
  39. // 存在重复文章标题
  40. return Result.error("文章标题重复!");
  41. }
  42. }
  43. /**
  44. * 文章根据条件查询,并分页
  45. * @param pageNum
  46. * @param pageSize
  47. * @param categoryId
  48. * @param state
  49. * @return
  50. */
  51. @GetMapping
  52. public Result page(@RequestParam(defaultValue = "1") Integer pageNum,
  53. @RequestParam(defaultValue = "10") Integer pageSize,
  54. String categoryId, String state){
  55. log.info("分页查询参数:当前页:{} 每页条数: {} 文章分类ID:{} 状态:{} ",pageNum,pageSize,categoryId,state);
  56. PageBean pageBean = articleService.pageList(pageNum,pageSize,categoryId,state);
  57. return Result.success(pageBean);
  58. }
  59. /**
  60. * 文章详情
  61. * @param id
  62. * @return
  63. */
  64. @GetMapping("/detail")
  65. public Result detail(Integer id){
  66. log.info("文章id{}详情",id);
  67. Article article = articleService.detail(id);
  68. return Result.success(article);
  69. }
  70. /**
  71. * 根据id更新文章
  72. * @param article
  73. * @return
  74. */
  75. @PutMapping
  76. public Result update(@RequestBody @Validated(Article.Update.class) Article article){
  77. log.info("根据id更新文章这些属性{}",article);
  78. Article queryArticle = articleService.queryArticleByTitle(article);
  79. if(queryArticle == null){
  80. articleService.updateArticleById(article);
  81. return Result.success();
  82. }else {
  83. return Result.error("不能修改为文章标题重复名称");
  84. }
  85. }
  86. /**
  87. * 根据id删除文章
  88. * @param id
  89. * @return
  90. */
  91. @DeleteMapping
  92. public Result delete(Integer id){
  93. log.info("根据id{},删除文章",id);
  94. articleService.deleteArticleById(id);
  95. return Result.success();
  96. }
  97. }

5.2 service

  1. package com.bocai.service;
  2. import com.bocai.pojo.Article;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. import com.bocai.pojo.PageBean;
  5. /**
  6. * @author cheng
  7. * @description 针对表【article】的数据库操作Service
  8. * @createDate 2023-11-13 19:55:11
  9. */
  10. public interface ArticleService extends IService<Article> {
  11. /**
  12. * 新增文章
  13. * @param article
  14. */
  15. void add(Article article);
  16. /**
  17. * 根据文章标题查询文章
  18. * @param article
  19. * @return
  20. */
  21. Article queryArticleByTitle(Article article);
  22. /**
  23. * 文章根据条件查询,并分页
  24. * @param pageNum 当前页码
  25. * @param pageSize 每页条数
  26. * @param categoryId 文章分类ID
  27. * @param state 状态
  28. * @return
  29. */
  30. PageBean pageList(Integer pageNum, Integer pageSize, String categoryId, String state);
  31. /**
  32. * 文章详情
  33. * @param id
  34. * @return
  35. */
  36. Article detail(Integer id);
  37. /**
  38. * 根据id更新文章
  39. * @param article
  40. */
  41. void updateArticleById(Article article);
  42. /**
  43. * 根据id删除文章
  44. * @param id
  45. */
  46. void deleteArticleById(Integer id);
  47. }

5.3 serviceImpl

  1. package com.bocai.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
  4. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  5. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  6. import com.bocai.pojo.Article;
  7. import com.bocai.pojo.Category;
  8. import com.bocai.pojo.PageBean;
  9. import com.bocai.service.ArticleService;
  10. import com.bocai.mapper.ArticleMapper;
  11. import com.bocai.utils.ThreadLocalUtil;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.stereotype.Service;
  14. import java.time.LocalDateTime;
  15. import java.util.Map;
  16. /**
  17. * @author cheng
  18. * @description 针对表【article】的数据库操作Service实现
  19. * @createDate 2023-11-13 19:55:11
  20. */
  21. @Service
  22. public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>
  23. implements ArticleService{
  24. @Autowired
  25. private ArticleMapper articleMapper;
  26. /**
  27. * 新增文章
  28. * @param article
  29. */
  30. @Override
  31. public void add(Article article) {
  32. Map<String, Object> map = ThreadLocalUtil.get();
  33. Integer createUserId = (Integer) map.get("id");
  34. article.setCreateUser(createUserId);
  35. article.setCreateTime(LocalDateTime.now());
  36. article.setUpdateTime(LocalDateTime.now());
  37. articleMapper.insert(article);
  38. }
  39. /**
  40. * 根据文章标题查询文章
  41. * @param article
  42. * @return
  43. */
  44. @Override
  45. public Article queryArticleByTitle(Article article) {
  46. LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  47. lambdaQueryWrapper.eq(article.getTitle() != null, Article::getTitle,article.getTitle())
  48. .ne(article.getId() != null,Article::getId,article.getId());
  49. return articleMapper.selectOne(lambdaQueryWrapper);
  50. }
  51. /**
  52. * 文章根据条件查询,并分页
  53. * @param pageNum 当前页码
  54. * @param pageSize 每页条数
  55. * @param categoryId 文章分类ID
  56. * @param state 状态
  57. * @return
  58. */
  59. @Override
  60. public PageBean pageList(Integer pageNum, Integer pageSize, String categoryId, String state) {
  61. Map<String,Object> map = ThreadLocalUtil.get();
  62. String userId = (String) map.get("id");
  63. LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
  64. lambdaQueryWrapper.eq(categoryId != null,Article::getCategoryId,categoryId)
  65. .eq(state != null,Article::getState,state)
  66. .eq(userId != null,Article::getCreateUser,userId);
  67. Page<Article> pageArticle = new Page<>(pageNum,pageSize);
  68. articleMapper.selectPage(pageArticle,lambdaQueryWrapper);
  69. PageBean pageBean = new PageBean(pageArticle.getTotal(),pageArticle.getRecords());
  70. return pageBean;
  71. }
  72. /**
  73. * 文章详情
  74. * @param id
  75. * @return
  76. */
  77. @Override
  78. public Article detail(Integer id) {
  79. return articleMapper.selectById(id);
  80. }
  81. /**
  82. * 根据id更新文章
  83. * @param article
  84. */
  85. @Override
  86. public void updateArticleById(Article article) {
  87. article.setUpdateTime(LocalDateTime.now());
  88. articleMapper.updateById(article);
  89. }
  90. /**
  91. * 根据id删除文章
  92. * @param id
  93. */
  94. @Override
  95. public void deleteArticleById(Integer id) {
  96. articleMapper.deleteById(id);
  97. }
  98. }

五、上传接口

1、FileUploadController

  1. package com.bocai.controller;
  2. import com.bocai.common.Result;
  3. import com.bocai.utils.AliOSSUtils;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.web.bind.annotation.PostMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import org.springframework.web.multipart.MultipartFile;
  9. import java.io.IOException;
  10. @RestController
  11. @Slf4j
  12. public class FileUploadController {
  13. @Autowired
  14. private AliOSSUtils aliOSSUtils;
  15. @PostMapping("/upload")
  16. public Result upload(MultipartFile file) throws IOException {
  17. log.info("上传的文件名:{}",file.getOriginalFilename());
  18. String url = aliOSSUtils.upload(file);
  19. return Result.success(url);
  20. }
  21. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/567696
推荐阅读
相关标签
  

闽ICP备14008679号