- 资料地址
- 2 - 前后端交互篇
- 3 - 文件上传
目录
- 一、项目简介
- 二、MySQL环境
- 三、项目架构
- 四、搭建父工程
- 五、搭建service工程
- 六、搭建service-edu模块
- 七、后台讲师管理模块
- 八、跨域配置
- 九、整合Swagger
- 十、统一返回结果
- 十一、分页和多条件查询接口开发
- 十二、新增和修改讲师接口开发
- 十三、统一异常处理
- 十四、统一日志处理
一、项目简介
1.1、项目简介
在线教育顾名思义,是以网络为介质的教学方式,通过网络,学员与教师即使相隔万里也可以开展教学活动;此外,借助网络课件,学员还可以随时随地进行学习,真正打破了时间和空间的限制,对于工作繁忙,学习时间不固定的职场人而言网络远程教育是最方便不过的学习方式。
谷粒学院,是一个B2C模式的职业技能在线教育系统,分为前台用户系统和后台运营平台。
1.2、系统模块
1.3、系统架构
二、MySQL环境
1、新建数据库 guli
2、运行资料的 guli_edu.sql
三、项目架构
四、搭建父工程
1、创建sprigboot工程 guli_parent
- 2.2.1.RELEASE
2、删除 src 目录
3、打包方式指定为pom
<artifactId>guli-parentartifactId>
<packaging>pompackaging>
4、完整POM
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.2.1.RELEASEversion>
<relativePath/>
parent>
<groupId>com.laptoygroupId>
<artifactId>guli_parentartifactId>
<packaging>pompackaging>
<version>0.0.1-SNAPSHOTversion>
<name>guli_parentname>
<description>父工程依赖管理description>
<properties>
<java.version>1.8java.version>
<guli.version>0.0.1-SNAPSHOTguli.version>
<mybatis-plus.version>3.0.5mybatis-plus.version>
<velocity.version>2.0velocity.version>
<swagger.version>2.7.0swagger.version>
<aliyun.oss.version>2.8.3aliyun.oss.version>
<jodatime.version>2.10.1jodatime.version>
<poi.version>3.17poi.version>
<commons-fileupload.version>1.3.1commons-fileupload.version>
<commons-io.version>2.6commons-io.version>
<httpclient.version>4.5.1httpclient.version>
<jwt.version>0.7.0jwt.version>
<aliyun-java-sdk-core.version>4.3.3aliyun-java-sdk-core.version>
<aliyun-sdk-oss.version>3.1.0aliyun-sdk-oss.version>
<aliyun-java-sdk-vod.version>2.15.2aliyun-java-sdk-vod.version>
<aliyun-java-vod-upload.version>1.4.11aliyun-java-vod-upload.version>
<aliyun-sdk-vod-upload.version>1.4.11aliyun-sdk-vod-upload.version>
<fastjson.version>1.2.28fastjson.version>
<gson.version>2.8.2gson.version>
<json.version>20170516json.version>
<commons-dbutils.version>1.7commons-dbutils.version>
<canal.client.version>1.1.0canal.client.version>
<docker.image.prefix>zxdocker.image.prefix>
<cloud-alibaba.version>0.2.2.RELEASEcloud-alibaba.version>
properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-dependenciesartifactId>
<version>Hoxton.RELEASEversion>
<type>pomtype>
<scope>importscope>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-alibaba-dependenciesartifactId>
<version>${cloud-alibaba.version}version>
<type>pomtype>
<scope>importscope>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>${mybatis-plus.version}version>
dependency>
<dependency>
<groupId>org.apache.velocitygroupId>
<artifactId>velocity-engine-coreartifactId>
<version>${velocity.version}version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>${swagger.version}version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>${swagger.version}version>
dependency>
<dependency>
<groupId>com.aliyun.ossgroupId>
<artifactId>aliyun-sdk-ossartifactId>
<version>${aliyun.oss.version}version>
dependency>
<dependency>
<groupId>joda-timegroupId>
<artifactId>joda-timeartifactId>
<version>${jodatime.version}version>
dependency>
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poiartifactId>
<version>${poi.version}version>
dependency>
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poi-ooxmlartifactId>
<version>${poi.version}version>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>${commons-fileupload.version}version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>${commons-io.version}version>
dependency>
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
<version>${httpclient.version}version>
dependency>
<dependency>
<groupId>com.google.code.gsongroupId>
<artifactId>gsonartifactId>
<version>${gson.version}version>
dependency>
<dependency>
<groupId>io.jsonwebtokengroupId>
<artifactId>jjwtartifactId>
<version>${jwt.version}version>
dependency>
<dependency>
<groupId>com.aliyungroupId>
<artifactId>aliyun-java-sdk-coreartifactId>
<version>${aliyun-java-sdk-core.version}version>
dependency>
<dependency>
<groupId>com.aliyun.ossgroupId>
<artifactId>aliyun-sdk-ossartifactId>
<version>${aliyun-sdk-oss.version}version>
dependency>
<dependency>
<groupId>com.aliyungroupId>
<artifactId>aliyun-java-sdk-vodartifactId>
<version>${aliyun-java-sdk-vod.version}version>
dependency>
<dependency>
<groupId>com.aliyungroupId>
<artifactId>aliyun-java-vod-uploadartifactId>
<version>${aliyun-java-vod-upload.version}version>
dependency>
<dependency>
<groupId>com.aliyungroupId>
<artifactId>aliyun-sdk-vod-uploadartifactId>
<version>${aliyun-sdk-vod-upload.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>${fastjson.version}version>
dependency>
<dependency>
<groupId>org.jsongroupId>
<artifactId>jsonartifactId>
<version>${json.version}version>
dependency>
<dependency>
<groupId>commons-dbutilsgroupId>
<artifactId>commons-dbutilsartifactId>
<version>${commons-dbutils.version}version>
dependency>
<dependency>
<groupId>com.alibaba.ottergroupId>
<artifactId>canal.clientartifactId>
<version>${canal.client.version}version>
dependency>
dependencies>
dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
五、搭建service工程
1、在父工程 guli_parent
下面创建 Maven模块 service
2、删除service模块的src目录
3、指定打包方式
<artifactId>serviceartifactId>
<packaging>pompackaging>
4、添加依赖
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>guli_parentartifactId>
<groupId>com.laptoygroupId>
<version>0.0.1-SNAPSHOTversion>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>serviceartifactId>
<packaging>pompackaging>
<properties>
<maven.compiler.source>8maven.compiler.source>
<maven.compiler.target>8maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>org.apache.velocitygroupId>
<artifactId>velocity-engine-coreartifactId>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
dependency>
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poiartifactId>
dependency>
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poi-ooxmlartifactId>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
dependency>
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
dependency>
<dependency>
<groupId>com.google.code.gsongroupId>
<artifactId>gsonartifactId>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
dependencies>
project>
六、搭建service-edu模块
1、在父工程 service
模块下面创建 maven模块 service_edu
2、YML
spring:
# 服务名
application:
name: service-edu
# 环境设置:dev、test、prod
profiles:
active: dev
# mysql数据库连接
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.88.130:3306/guli?useSSL=false&useUnicode=true&characterEncoding=utf-8&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
username: root
password: root
# 统一返回的json时间格式
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
# mybatis日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 服务端口
server:
port: 8001
3、在test/java目录下创建包 com.laptoy.eduservice
,创建代码生成器:CodeGenerator.java
public class CodeGenerator {
@Test
public void run() {
// 1、创建代码生成器
AutoGenerator mpg = new AutoGenerator();
// 2、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir("D:\MyCode\IdeaCode\Project\guli_parent\service\service_edu" + "/src/main/java"); //输出目录
gc.setAuthor("Laptoy"); //作者名
gc.setOpen(false); //生成后是否打开资源管理器
gc.setFileOverride(false); //重新生成时文件是否覆盖
gc.setServiceName("%sService"); //去掉Service接口的首字母I
gc.setIdType(IdType.ID_WORKER_STR); //主键策略
gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
gc.setSwagger2(true);//开启Swagger2模式
mpg.setGlobalConfig(gc);
// 3、数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://192.168.88.130:3306/guli?useSSL=false&useUnicode=true&characterEncoding=utf-8&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 4、包配置
PackageConfig pc = new PackageConfig();
//生成包:com.laptoy.eduservice
pc.setModuleName("eduservice"); //模块名
pc.setParent("com.laptoy");
//生成包:com.laptoy.eduservice.xxx
pc.setController("controller");
pc.setEntity("entity");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 5、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("edu_teacher");//根据数据库哪张表生成,有多张表就加逗号继续填写
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀
strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式 *** 作
strategy.setRestControllerStyle(true); //restful api风格控制器
strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符
mpg.setStrategy(strategy);
// 6、执行
mpg.execute();
}
}
七、后台讲师管理模块
7.1、测试查询全部功能
1、MBP配置类
@Configuration
@EnableTransactionManagement
@MapperScan("com.laptoy.eduservice.mapper")
public class MyBatisPlusConfig {
/**
* SQL 执行性能分析插件
* 开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长
*/
@Bean
@Profile({"dev", "test"})// 设置 dev test 环境开启
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(1000);//ms,超过此处设置的ms则sql不执行
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
}
2、主启动
@SpringBootApplication
public class Service_edu_Main8001 {
public static void main(String[] args) {
SpringApplication.run(Service_edu_Main8001.class,args);
}
}
3、编写控制层代码进行测试
@RestController
@RequestMapping("/eduservice/teacher")
public class EduTeacherController {
@Autowired
private EduTeacherService eduTeacherService;
/**
* 查询所有讲师
*/
@GetMapping("/findAll")
public List<EduTeacher> list() {
return eduTeacherService.list(null);
}
}
4、访问 http://localhost:8001/eduservice/teacher/findAll
7.2、测试逻辑删除功能
1、在实体类上对应标注注解
@TableLogic
private Boolean isDeleted;
2、MyBatisPlusConfig 中配置逻辑删除插件 (MBP3.1.1以上版本无需配置)
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
3、EduTeacherController 控制器
@DeleteMapping("/deleteTeacherById/{id}")
public boolean deleteTeacherById(@PathVariable String id) {
return eduTeacherService.removeById(id);
}
4、访问 http://localhost:8001/eduservice/teacher/deleteTeacherById/1
八、跨域配置
浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域 。前后端分离开发中,需要考虑ajax跨域的问题。这里我们可以从服务端解决这个问题
在Controller类上添加注解 @CrossOrigin
@RestController
@CrossOrigin //解决跨域问题
@RequestMapping("/eduservice/teacher")
public class EduTeacherController {}
九、整合Swagger
创建common公共模块,为了让所有模块都可使用
1、在 guli-parent 下创建Maven模块 common
(删除 src 目录)
2、POM
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
<scope>provided scope>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<scope>provided scope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<scope>provided scope>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<scope>provided scope>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<scope>provided scope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
3、在 common 模块下创建Maven工程 service-base
4、创建包 com.laptoy.servicebase.config
,创建类 SwaggerConfig
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket webApiConfig() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("webApi")
.apiInfo(webApiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/admin/.*")))
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
private ApiInfo webApiInfo() {
return new ApiInfoBuilder()
.title("谷粒学院API文档")
.description("本文档描述了课程中心微服务接口定义")
.version("1.0")
.contact(new Contact("Laptoy", "http://laptoy.gitee.io", "laptoy458@163.com"))
.build();
}
}
5、service模块 引入 common模块
<dependency>
<groupId>com.laptoygroupId>
<artifactId>service_baseartifactId>
<version>0.0.1-SNAPSHOTversion>
dependency>
6、主启动类扫描该配置类(跨模块的@Configuration 无法自动加载)
@SpringBootApplication
@ComponentScan(basePackages = "com.laptoy")
public class Service_edu_Main8001 {
public static void main(String[] args) {
SpringApplication.run(Service_edu_Main8001.class,args);
}
}
7、优化控制器
@Api(tags = "讲师管理模块")
@RestController
@CrossOrigin //解决跨域问题
@RequestMapping("/eduservice/teacher")
public class EduTeacherController {
@Autowired
private EduTeacherService eduTeacherService;
/**
* 查询所有讲师
*/
@ApiOperation("查询所有讲师")
@GetMapping("/findAll")
public List<EduTeacher> list() {
return eduTeacherService.list(null);
}
/**
* 逻辑删除讲师
*/
@ApiOperation("逻辑删除讲师")
@DeleteMapping("/deleteTeacherById/{id}")
public boolean deleteTeacherById(@ApiParam(name = "id", value = "讲师ID", required = true) @PathVariable String id) {
return eduTeacherService.removeById(id);
}
}
8、运行启动类
访问 http://localhost:8001/swagger-ui.html
十、统一返回结果
10.1、简介
- 将响应封装成json,将所有接口的数据格式统一, 使前端(iOS Android,Web)对数据的 *** 作更一致、轻松
- 统一返回数据格式没有固定的格式,只要能描述清楚返回的数据状态以及要返回的具体数据就可以。
- 但是一般会包含状态码、返回消息、数据这几部分内容
{
"success": bollean, //响应是否成功
"code": int, //响应码
"message": String, //返回消息
"data": HashMap //返回数据,放在键值对中
}
10.2、创建
1、在common模块下创建子模块 common_utils
2、创建状态码类 com.laptoy.commonutils
package com.laptoy.commonutils;
public interface ResultCode {
//状态码:成功
public static Integer SUCCESS = 20000;
//状态码:失败
public static Integer ERROR = 40000;
}
3、创建结果类 com.laptoy.commonutils
package com.laptoy.commonutils;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
@Data
public class R {
@ApiModelProperty("是否成功")
private boolean success;
@ApiModelProperty("响应码")
private Integer code;
@ApiModelProperty("返回信息")
private String message;
@ApiModelProperty("返回数据")
private Map<String, Object> data = new HashMap<String, Object>();
//无参构造方法私有
private R() {
}
//成功 静态方法
public static R ok() {
R r = new R();
r.setSuccess(true);
r.setCode(ResultCode.SUCCESS);
r.setMessage("成功");
return r;
}
//失败 静态方法
public static R error() {
R r = new R();
r.setSuccess(false);
r.setCode(ResultCode.ERROR);
r.setMessage("失败");
return r;
}
// 链式编程写法
// 自定义是否成功或失败
// R.ok().success(true/false)
public R success(Boolean success) {
this.setSuccess(success);
return this;
}
// 自定义响应码
// R.ok().code(xx)
public R code(Integer code) {
this.setCode(code);
return this;
}
// 自定义消息
// R.ok.message("自定义消息")
public R message(String message) {
this.setMessage(message);
return this;
}
// R.ok().data(k,v) 传入键值对
public R data(String key, Object value) {
this.data.put(key, value);
return this;
}
// R.ok().data(map) 传入map
public R data(Map<String, Object> map) {
this.setData(map);
return this;
}
}
10.3、使用
1、在service模块中添加依赖
<dependency>
<groupId>com.laptoygroupId>
<artifactId>common_utilsartifactId>
<version>0.0.1-SNAPSHOTversion>
dependency>
2、修改Controller中的返回结果
@Api(tags = "讲师管理模块")
@RestController
@CrossOrigin //解决跨域问题
@RequestMapping("/eduservice/teacher")
public class EduTeacherController {
@Autowired
private EduTeacherService eduTeacherService;
/**
* 查询所有讲师
*/
@ApiOperation("查询所有讲师")
@GetMapping("/findAll")
public R list() {
List<EduTeacher> list = eduTeacherService.list(null);
return R.ok().data("data", list);
}
/**
* 逻辑删除讲师
*/
@ApiOperation("逻辑删除讲师")
@DeleteMapping("/deleteTeacherById/{id}")
public R deleteTeacherById(@ApiParam(name = "id", value = "讲师ID", required = true) @PathVariable String id) {
boolean flag = eduTeacherService.removeById(id);
if (flag) {
return R.ok();
} else {
return R.error();
}
}
}
十一、分页和多条件查询接口开发
11.1、分页开发
1、MyBatisPlusConfig中配置分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
2、分页查询方法
/**
* 分页查询
* page:当前页
* limit:每页显示记录数
*/
@ApiOperation(value = "分页讲师列表")
@GetMapping("/pageList/{page}/{limit}")
public R pageList(@ApiParam(name = "page", value = "当前页码", required = true) @PathVariable Long page,
@ApiParam(name = "limit", value = "每页记录数", required = true) @PathVariable Long limit) {
Page<EduTeacher> pageParam = new Page<>(page, limit);
//分页查询,查完后,会将数据封装在pageParam中
eduTeacherService.page(pageParam, null);
//获取总记录数 和 具体数据
long total = pageParam.getTotal();
List<EduTeacher> records = pageParam.getRecords();
return R.ok().data("total", total).data("data", records);
}
11.2、多条件组合查询带分页
模拟前端传参进行条件查询
1、创建实体类
@ApiModel(value = "Teacher查询对象", description = "讲师查询对象封装")
@Data
public class TeacherQuery implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "教师名称,模糊查询")
private String name;
@ApiModelProperty(value = "头衔 1高级讲师 2首席讲师")
private Integer level;
@ApiModelProperty(value = "查询开始时间", example = "2019-01-01 10:10:10")
private String begin;//注意,这里使用的是String类型,前端传过来的数据无需进行类型转换
@ApiModelProperty(value = "查询结束时间", example = "2019-12-01 10:10:10")
private String end;
}
2、控制层
//多条件查询讲师带分页
@ApiOperation(value = "多条件查询讲师带分页")
@PostMapping("/pageTeacherCondition/{page}/{limit}")
public R pageTeacherCondition(@ApiParam(name = "page", value = "当前页码", required = true)@PathVariable Long page,
@ApiParam(name = "limit", value = "每页记录数", required = true)@PathVariable Long limit,
@RequestBody(required = false) TeacherQuery teacherQuery){
//创建分页page对象
Page<EduTeacher> pageParam = new Page<>(page, limit);
//调用方法实现多条件分页查询
eduTeacherService.pageQuery(pageParam,teacherQuery);
//获取查询到的数据
List<EduTeacher> data = pageParam.getRecords();
//获取总记录数
long total = pageParam.getTotal();
return R.ok().data("total",total).data("data",records);
}
3、业务层
@Service
public class EduTeacherServiceImpl extends ServiceImpl<EduTeacherMapper, EduTeacher> implements EduTeacherService {
@Override
public void pageQuery(Page<EduTeacher> pageParam, TeacherQuery teacherQuery) {
QueryWrapper<EduTeacher> wrapper = new QueryWrapper<>();
//取出值,判断他们是否有值
String name = teacherQuery.getName();
Integer level = teacherQuery.getLevel();
String begin = teacherQuery.getBegin();
String end = teacherQuery.getEnd();
if (!StringUtils.isEmpty(name)) {
wrapper.like("name", name);
}
if (!StringUtils.isEmpty(level)) {
wrapper.eq("level", level);
}
if (!StringUtils.isEmpty(begin)) {
wrapper.ge("gmt_create", begin);
}
if (!StringUtils.isEmpty(begin)) {
wrapper.le("gmt_modified", end);
}
// 按照创建时间倒序排序
wrapper.orderByDesc("gmt_create");
baseMapper.selectPage(pageParam, wrapper);
}
}
4、通过Swagger进行测试
十二、新增和修改讲师接口开发
12.1、自动填充封装
给新增数据和修改数据,添加新建时间和修改时间的自动填充封装功能
1、service_base
模块中新建包 com.laptoy.servicebase.handler
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
//参数1:对应类中的属性名称
this.setFieldValByName("gmtCreate", new Date(), metaObject);
this.setFieldValByName("gmtModified", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("gmtModified", new Date(), metaObject);
}
}
2、实体类 EduTeacher 属性添加注解指定何时进行填充
@TableField(fill = FieldFill.INSERT)
@ApiModelProperty(value = "创建时间")
private Date gmtCreate;
@TableField(fill = FieldFill.INSERT_UPDATE)
@ApiModelProperty(value = "更新时间")
private Date gmtModified;
12.2、控制层
// 新增讲师
@ApiOperation(value = "新增讲师")
@PostMapping("/save")
public R save(@RequestBody EduTeacher eduTeacher) {
boolean flag = eduTeacherService.save(eduTeacher);
if (flag) {
return R.ok();
} else {
return R.error();
}
}
// 根据id查询,用于信息回显
@ApiOperation(value = "根据id查询")
@GetMapping("/getById/{id}")
public R getById(@PathVariable String id) {
EduTeacher teacher = eduTeacherService.getById(id);
return R.ok().data("data", teacher);
}
// 修改讲师
@ApiOperation(value = "修改讲师")
@PostMapping("/updateById")
public R updateById(@RequestBody EduTeacher teacher) {
boolean flag = eduTeacherService.updateById(teacher);
if (flag) {
return R.ok();
} else {
return R.error();
}
}
十三、统一异常处理
13.1、统一异常处理器
1、service_base 模块 引入 common_utils 模块,因为需要使用到 R类
<dependency>
<groupId>com.laptoygroupId>
<artifactId>common_utilsartifactId>
<version>0.0.1-SNAPSHOTversion>
dependency>
2、建包 com.laptoy.servicebase.exceptionhandler
package com.laptoy.servicebase.exceptionhandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public R error(Exception e) {
e.printStackTrace();
return R.error().message("全局异常处理器:系统未知异常");
}
}
3、测试(可以直接用save方法进行测试,传入错误的数据就会出异常)
13.2、处理特定异常
1、异常处理器
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public R error(ArithmeticException e) {
e.printStackTrace();
return R.error().message("发生异常算数异常,请确定输入是否符合规范");
}
2、测试
@ApiOperation(value = "测试异常")
@GetMapping("/test")
public void test() {
int a = 10 / 0;
}
13.3、自定义异常
建议开发过程多多使用自定义异常进行抛出,可以解决很多麻烦
1、创建自定义异常类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LaptoyException extends RuntimeException {
@ApiModelProperty(value = "状态码")
private Integer code;
@ApiModelProperty(value = "错误消息")
private String msg;
}
2、异常处理器
@ExceptionHandler(LaptoyException.class)
@ResponseBody
public R error(LaptoyException e) {
e.printStackTrace();
return R.error().message(e.getMsg()).code(e.getCode());
}
3、业务中需要的位置抛出异常
@ApiOperation(value = "测试异常")
@GetMapping("/test")
public void test() {
throw new LaptoyException(666,"自定义异常");
}
十四、统一日志处理
14.1、日志
日志记录器(Logger)的行为是分等级的。如下表所示:
分为:OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL
默认情况下,spring boot从控制台打印出来的日志级别只有INFO及以上级别,可以配置日志级别
# 设置日志级别
logging:
level:
root: WARN
这种方式只能将日志打印在控制台上
14.2、Logback日志
SpringBoot内部使用 Logback 作为日志实现的框架。
1、删除 application.properties 中的日志配置
# logging.level.root=WARN
# mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
2、resources 中创建 logback-spring.xml
(在最顶部的资料里)
14.3、将错误日志输出到文件
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public R error(Exception e) {
e.printStackTrace();
log.error(e.getMessage());
return R.error().message("全局异常处理器:系统未知异常");
}
@ExceptionHandler(ArithmeticException.class)
public R error(ArithmeticException e) {
e.printStackTrace();
log.error(e.getMessage());
return R.error().message("发生算数异常,请确定输入是否符合规范");
}
@ExceptionHandler(LaptoyException.class)
public R error(LaptoyException e) {
e.printStackTrace();
log.error(e.getMessage());
return R.error().message(e.getMsg()).code(e.getCode());
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)