第一章:简介
- 这是一个真实的企业项目
- 技术架构:
- springCloudAlibaba
- VUE实现了前后端分离开发(解决跨域的问题)
- 数据库:mysql
- ORM:mybatisPlus
- 把我们开发的模块都分为不同的微服务部分
- 把需要上传的图片及视频都存储在阿里云中
1、技术选型
查看SpringCloud 和SpringBoot版本兼容性
查看SpringCloud 对其余各个技术版本的兼容性 需要转换成JSON进行查看
2、学习版本定稿
学习时必须和定稿版本一致
技术 | 版本 |
---|---|
java | 1.8 |
Spring Cloud | Greenwich.RELEASE |
Spring Boot | 2.1.3.RELEASE |
Spring Cloud Alibaba | 2.1.0.RELEASE |
mybatisPlus | 3.0.5 |
Maven | 3.3.3 |
MySQL | 5.7 |
第二章:搭建项目环境
2.1 创建一个maven项目,作为父工程
2.2 pom.xml依赖
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!-- 模型版本。maven2.0必须是这样写,现在是maven2唯一支持的版本 -->
<modelVersion>4.0.0</modelVersion>
<!-- 公司或者组织的唯一标志,并且配置时生成的路径也是由此生成, 如 com.example,maven 会将该项目打成的 jar 包放本地路径:/com/example -->
<groupId>com.example</groupId>
<!-- 本项目的唯一ID,一个groupId下面可能多个项目,就是靠artifactId来区分的 -->
<artifactId>movies</artifactId>
<!-- 本项目目前所处的版本号 -->
<version>1.0-SNAPSHOT</version>
<!-- 打包的机制,如 pom、jar、maven-plugin、ejb、war、ear、rar和par,默认为jar -->
<packaging>pom</packaging>
<!-- Spring Boot 的父级依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<!-- 帮助定义构件输出的一些附属构件,附属构件与主构件对应,有时候需要加上classifier才能唯一的确定该构件 不能直接定义项目的classifer,因为附属构件不是项目直接默认生成的,而是由附加的插件帮助生成的 -->
<!--<classifier></classifier>-->
<!-- 统一管理jar包版本 -->
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
<spring-cloud-alibaba.version>2.1.0.RELEASE</spring-cloud-alibaba.version>
<mybatis-plus.version>3.0.5</mybatis-plus.version>
<velocity.version>2.0</velocity.version>
<swagger.version>2.7.0</swagger.version>
<aliyun.oss.version>2.8.3</aliyun.oss.version>
<jodatime.version>2.10.1</jodatime.version>
<poi.version>3.17</poi.version>
<commons-fileupload.version>1.3.1</commons-fileupload.version>
<commons-io.version>2.6</commons-io.version>
<httpclient.version>4.5.1</httpclient.version>
<jwt.version>0.7.0</jwt.version>
<aliyun-java-sdk-core.version>4.3.3</aliyun-java-sdk-core.version>
<aliyun-sdk-oss.version>3.1.0</aliyun-sdk-oss.version>
<aliyun-java-sdk-vod.version>2.15.2</aliyun-java-sdk-vod.version>
<aliyun-java-vod-upload.version>1.4.11</aliyun-java-vod-upload.version>
<aliyun-sdk-vod-upload.version>1.4.11</aliyun-sdk-vod-upload.version>
<fastjson.version>1.2.28</fastjson.version>
<gson.version>2.8.2</gson.version>
<json.version>20170516</json.version>
<commons-dbutils.version>1.7</commons-dbutils.version>
<canal.client.version>1.1.0</canal.client.version>
<docker.image.prefix>zx</docker.image.prefix>
<cloud-alibaba.version>0.2.2.RELEASE</cloud-alibaba.version>
</properties>
<!--子模块继承之后,提供作用:锁定版本+子module不用写groupId和version -->
<dependencyManagement>
<!-- 定义本项目的依赖关系 -->
<dependencies>
<!--spring cloud-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--spring cloud alibaba-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--mybatis-plus 持久层-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!-- velocity 模板引擎, Mybatis Plus 代码生成器需要 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>${velocity.version}</version>
</dependency>
<!--Swagger 用于生成、描述、调用和可视化RESTful 风格的Web服务-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--springfox-swagger-ui 是一个webjar, 方便进行maven集成-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--aliyunOSS 是一种海量、安全、低成本、高可靠的云存储服务-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>${aliyun.oss.version}</version>
</dependency>
<!--日期时间工具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime.version}</version>
</dependency>
<!--提供API给Java程序对Microsoft Office格式档案读和写的功能-->
<!--xls-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<!--xlsx-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<!--commons-io 可以挺提高 IO 功能开发的效率-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!--httpclient 可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<!--将Java对象序列化为JSON,反之亦然-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<!-- JWT 用于在JVM和Android上创建和验证JSON Web令牌 -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jwt.version}</version>
</dependency>
<!--aliyun-->
<!--阿里云的核心SDK-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>${aliyun-java-sdk-core.version}</version>
</dependency>
<!--提供基于网络的数据存取服务-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>${aliyun-sdk-oss.version}</version>
</dependency>
<!-- 阿里云SDK点播服务包重构,支持composer方式使用-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-vod</artifactId>
<version>${aliyun-java-sdk-vod.version}</version>
</dependency>
<!--阿里云视频点播上传客户端-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-vod-upload</artifactId>
<version>${aliyun-java-vod-upload.version}</version>
</dependency>
<!--文件上传的方式和基本流程-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-sdk-vod-upload</artifactId>
<version>${aliyun-sdk-vod-upload.version}</version>
</dependency>
<!--fastjson 提供服务器端、安卓客户端两种解析工具-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!--json 轻量级的数据交换格式-->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${json.version}</version>
</dependency>
<!--用于操作数据库的工具包-->
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>${commons-dbutils.version}</version>
</dependency>
<!--实现数据同步-->
<dependency>
<groupId>com.alibaba.otter</groupId>
<artifactId>canal.client</artifactId>
<version>${canal.client.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
<addResources>true</addResources>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.3 创建子工程
2.3.1 subproject_service服务的子工程
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>movies</artifactId>
<groupId>com.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>subproject_service</artifactId>
<packaging>pom</packaging>
<dependencies>
<!--nacos客户端-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--mybatisplus-代码生成器的模板-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--xls-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
<!--httpCilents-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<!--gson-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
</dependencies>
</project>
2.3.2 public_common公共工程
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>movies</artifactId>
<groupId>com.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>public_common</artifactId>
<packaging>pom</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>provided</scope>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<scope>provided</scope>
</dependency>
<!--为了简化实体类,配置lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--为了测试前后端分离项目 swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<!--二级缓存配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
</project>
2.3.3 在public_common下创建子模块common_util和service_base
在创建模块时,注意路径是否在public_common模块下
2.3.3.1 创建service_base模块
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>public_common</artifactId>
<groupId>com.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>service_base</artifactId>
<dependencies>
<!--添加工具模块-->
<dependency>
<groupId>com.example</groupId>
<artifactId>common_util</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
2.3.3.2 创建common_util模块
2.3.4 在service_base中编写配置swagger类
package com.example.movies.config;
import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* 配置类.
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/**
* 构建api文档的详细信息函数
* @return
*/
private ApiInfo webApiInfo() {
return new ApiInfoBuilder()
// 页面标题
.title("Api文档")
// 描述
.description("描述微服务接口定义")
// 版本号
.version("1.0")
// 创建人
.contact(new Contact("java", "http://zmxdata.com", "hksupports@163.com"))
.build();
}
/**
* 构建接口文档
* @return
*/
@Bean
public Docket webApiConfig() {
return new Docket(DocumentationType.SWAGGER_2)
// 分组名
.groupName("webApi")
// 设置描述文件
.apiInfo(webApiInfo())
// 用来等待文件描述词状态的改变
.select()
// 只显示api路径下的页面
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
}
2.4 在subproject_service模块中创建子模块service_actor
- 演员模块
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>xiudun_service</artifactId>
<groupId>com.xiudun</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>service_actor</artifactId>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>
</project>
2.4.1 配置公共部分
- 主配置类
package com.example.movies;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* 主配置类.
*/
@SpringBootApplication
@EnableSwagger2
@EnableDiscoveryClient
@MapperScan("com.example.movies.mapper")
public class ActorApplication {
public static void main(String[] args) {
SpringApplication.run(ActorApplication.class, args);
}
}
- 配置文件:application.yml,注意:冒号后必须有空格,这是编写格式
server:
# 端口
port: 8081
spring:
application:
# 服务名
name: service-actor
profiles:
# 开发环境
active: dev
# mysql 配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/movies?useUnicode=true&characterEncoding=utf8$serverTimezone=GMT%2B8ame
username: root
password: 123456
# json 的时间格式
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
# 注册中心
cloud:
nacos:
discovery:
server-addr: localhost:8848
- 先创建数据库
- 再启动nacos
- swagger的测试页面
第三章:编写演员模块
3.1 生成数据库
#
# 影视图片表
#
CREATE TABLE `crm_banner` (
`id` char(19) NOT NULL DEFAULT '' COMMENT 'ID',
`title` varchar(20) DEFAULT '' COMMENT '标题',
`image_url` varchar(500) NOT NULL DEFAULT '' COMMENT '图片地址',
`link_url` varchar(500) DEFAULT '' COMMENT '链接地址',
`sort` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '排序',
`is_deleted` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '逻辑删除 1(true)已删除, 0(false)未删除',
`gmt_create` datetime NOT NULL COMMENT '创建时间',
`gmt_modified` datetime NOT NULL COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_name` (`title`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='首页banner表';
#
# Data for table "crm_banner"
#
INSERT INTO `crm_banner` VALUES ('1194556896025845762','test1',
'https://xxx.jpg',
'/course',1,0,'2019-11-13 18:05:32','2019-11-18 10:28:22'),('1194607458461216769','test2',
'https://xxxx.jpg',
'/teacher',2,0,'2019-11-13 21:26:27','2019-11-14 09:12:15');
#
# 影视片段表
#
CREATE TABLE `edu_chapter` (
`id` char(19) NOT NULL COMMENT '片段ID',
`movies_id` char(19) NOT NULL COMMENT '影视ID',
`title` varchar(50) NOT NULL COMMENT '片段名称',
`sort` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '显示排序',
`gmt_create` datetime NOT NULL COMMENT '创建时间',
`gmt_modified` datetime NOT NULL COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_movies_id` (`movies_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT COMMENT='影视';
#
# Data for table "edu_chapter"
#
INSERT INTO `edu_chapter` VALUES ('1','14','第一片段:剧情介绍',0,'2019-01-01 12:27:40','2019-01-01 12:55:30'),
('1181729226915577857','18','故事发生的时间',70,'2019-10-09 08:32:58','2019-10-09 08:33:20'),
('1192252428399751169','1192252213659774977','第一段',0,'2019-11-07 09:28:25','2019-11-07 09:28:25'),
('15','18','第一片段:演员入戏',0,'2019-01-01 12:27:40','2019-10-09 09:13:19'),
('3','14','第二片段:演员公司入职',0,'2019-01-01 12:55:35','2019-01-01 12:27:40'),
('44','18','第三片段:演员学习',0,'2019-01-01 12:27:40','2019-01-01 12:27:40');
#
# 影片表
#
CREATE TABLE `edu_movies` (
`id` char(19) NOT NULL COMMENT '影视ID',
`actor_id` char(19) NOT NULL COMMENT '影视演员ID',
`subject_id` char(19) NOT NULL COMMENT '影视专业ID',
`subject_parent_id` char(19) NOT NULL COMMENT '影视专业父级ID',
`title` varchar(50) NOT NULL COMMENT '影视标题',
`price` decimal(10,2) unsigned NOT NULL DEFAULT '0.00' COMMENT '影视销售价格,设置为0则可免费观看',
`video_num` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '总段数',
`cover` varchar(255) CHARACTER SET utf8 NOT NULL COMMENT '影视封面图片路径',
`buy_count` bigint(10) unsigned NOT NULL DEFAULT '0' COMMENT '销售数量',
`view_count` bigint(10) unsigned NOT NULL DEFAULT '0' COMMENT '浏览数量',
`version` bigint(20) unsigned NOT NULL DEFAULT '1' COMMENT '乐观锁',
`status` varchar(10) NOT NULL DEFAULT 'Draft' COMMENT '影视状态 Draft未发布 Normal已发布',
`is_deleted` tinyint(3) DEFAULT NULL COMMENT '逻辑删除 1(true)已删除, 0(false)未删除',
`gmt_create` datetime NOT NULL COMMENT '创建时间',
`gmt_modified` datetime NOT NULL COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_title` (`title`),
KEY `idx_subject_id` (`subject_id`),
KEY `idx_actor_id` (`actor_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT COMMENT='影视';
#
# Data for table "edu_movies"
#
INSERT INTO `edu_movies` VALUES ('1192252213659774977','1189389726308478977','1178214681139539969',
'1178214681118568449','基础影视:test',0.01,2,
'https://xxx.gif',4,387,1,'Normal',0,'2019-11-07 09:27:33','2019-11-18 13:35:03'),
('14','1189389726308478977','1101348944971091969','1101348944920760321','我的祖国',0.00,3,
'http://xxxx.jpg',3,44,15,'Normal',0,'2018-04-02 18:33:34','2019-11-16 21:21:45'),
('15','1189389726308478977','1101348944971091969','1101348944920760321','冠军',0.00,23,
'http://xxx.jpg',0,51,17,'Normal',0,'2018-04-02 18:34:32','2019-11-12 10:19:20'),
('18','1189389726308478977','1178214681139539969','1178214681118568449','战狼2',0.01,20,
'http://xxx.jpg',151,737,6,'Normal',0,'2018-04-02 21:28:46','2019-11-18 11:14:52');
#
# 影视收藏表
#
CREATE TABLE `edu_movies_collect` (
`id` char(19) NOT NULL COMMENT '收藏ID',
`movies_id` char(19) NOT NULL COMMENT '影视演员ID',
`member_id` char(19) NOT NULL DEFAULT '' COMMENT '影视专业ID',
`is_deleted` tinyint(3) NOT NULL DEFAULT '0' COMMENT '逻辑删除 1(true)已删除, 0(false)未删除',
`gmt_create` datetime NOT NULL COMMENT '创建时间',
`gmt_modified` datetime NOT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT COMMENT='影视收藏';
#
# Data for table "edu_movies_collect"
#
INSERT INTO `edu_movies_collect` VALUES ('1196269345666019330','1192252213659774977','1',1,'2019-11-18 11:30:12','2019-11-18 11:30:12');
#
# 影视简介表
#
CREATE TABLE `edu_movies_description` (
`id` char(19) NOT NULL COMMENT '影视ID',
`description` text COMMENT '影视简介',
`gmt_create` datetime NOT NULL COMMENT '创建时间',
`gmt_modified` datetime NOT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='影视简介';
#
# Data for table "edu_movies_description"
#
INSERT INTO `edu_movies_description` VALUES ('1104870479077879809','<p>11</p>','2019-03-11 06:23:44',
'2019-03-11 06:23:44'),('1192252213659774977','<p>影片</p>','2019-11-07 09:27:33','2019-11-13 16:21:28'),
('14','','2019-03-13 06:04:43','2019-03-13 06:05:33'),('15','','2019-03-13 06:03:33','2019-03-13 06:04:22'),
('18','<p>本影片介绍了中国的历史</p>','2019-03-06 18:06:36','2019-10-30 19:58:36');
#
# 影视类别表
#
CREATE TABLE `edu_subject` (
`id` char(19) NOT NULL COMMENT '影视类别ID',
`title` varchar(10) NOT NULL COMMENT '类别名称',
`parent_id` char(19) NOT NULL DEFAULT '0' COMMENT '父ID',
`sort` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '排序字段',
`gmt_create` datetime NOT NULL COMMENT '创建时间',
`gmt_modified` datetime NOT NULL COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_parent_id` (`parent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT COMMENT='影视科目';
#
# Data for table "edu_subject"
#
INSERT INTO `edu_subject` VALUES ('1178214681118568449','战争','0',1,'2019-09-29 15:47:25','2019-09-29 15:47:25'),
('1178214681139539969','爱情','1178214681118568449',1,'2019-09-29 15:47:25','2019-09-29 15:47:25'),
('1178214681181483010','城市剧','0',3,'2019-09-29 15:47:25','2019-09-29 15:47:25'),
('1178214681210843137','伦理剧','1178214681181483010',4,'2019-09-29 15:47:25','2019-09-29 15:47:25'),
('1178214681231814658','喜剧','0',5,'2019-09-29 15:47:25','2019-09-29 15:47:25'),
('1178214681252786178','武打片','1178214681231814658',5,'2019-09-29 15:47:25','2019-09-29 15:47:25'),
('1178214681294729217','纪录片','1178214681231814658',6,'2019-09-29 15:47:25','2019-09-29 15:47:25'),
('1178214681324089345','连续剧','0',7,'2019-09-29 15:47:25','2019-09-29 15:47:25'),
('1178214681353449473','战争1','1178214681324089345',7,'2019-09-29 15:47:25','2019-09-29 15:47:25'),
('1178214681382809602','言情剧','1178214681324089345',8,'2019-09-29 15:47:25','2019-09-29 15:47:25');
#
# 演员(主演)表
#
CREATE TABLE `edu_actor` (
`id` char(19) NOT NULL COMMENT '演员ID',
`name` varchar(20) NOT NULL COMMENT '演员姓名',
`intro` varchar(500) NOT NULL DEFAULT '' COMMENT '演员简介',
`career` varchar(500) DEFAULT NULL COMMENT '演员资历,一句话说明演员',
`level` int(10) unsigned NOT NULL COMMENT '头衔 1高级演员 2首席演员',
`avatar` varchar(255) DEFAULT NULL COMMENT '演员头像',
`sort` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '排序',
`is_deleted` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '逻辑删除 1(true)已删除, 0(false)未删除',
`gmt_create` datetime NOT NULL COMMENT '创建时间',
`gmt_modified` datetime NOT NULL COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='演员';
#
# Data for table "edu_actor"
#
INSERT INTO `edu_actor` VALUES ('1','张三','一级演员','一线',1,'https://xx/avatar/default.jpg',0,0,
'2019-10-30 14:18:46','2019-11-12 13:36:36'),
('1189389726308478977','李四','一级演员','一线',2,'https://xxx/actor/11.png',1,0,'2019-10-30 11:53:03',
'2019-10-30 11:53:03'),('1189390295668469762','李刚','高级演员简介','高级演员',2,
'https://xxx.png',2,0,'2019-10-30 11:55:19','2019-11-12 13:37:52'),
('1189426437876985857','王二','高级演员简介','高级演员',1,'https://2ec96ef88.png',0,0,'2019-10-30 14:18:56',
'2019-11-12 13:37:35'),('1189426464967995393','王五','高级演员简介','高级演员',1,
'https://xxxx.png',0,0,'2019-10-30 14:19:02','2019-11-12 13:37:18'),
('1192249914833055746','李四1','高级演员简介','高级演员',1,'https://d825d.png',0,0,
'2019-11-07 09:18:25','2019-11-12 13:37:01'),
('1192327476087115778','1222-12-12','1111','11',1,'https://fd8a4.png',0,1,
'2019-11-07 14:26:37','2019-11-11 16:26:26'),
('1195337453429129218','test','sdfsdf','sdfdf',1,'https://default.jpg',0,1,
'2019-11-15 21:47:12','2019-11-15 21:47:27');
#
# 电影视频表
#
CREATE TABLE `edu_video` (
`id` char(19) NOT NULL COMMENT '视频ID',
`movies_id` char(19) NOT NULL COMMENT '影视ID',
`chapter_id` char(19) NOT NULL COMMENT '章节ID',
`title` varchar(50) NOT NULL COMMENT '节点名称',
`video_source_id` varchar(100) DEFAULT NULL COMMENT '云端视频资源',
`video_original_name` varchar(100) DEFAULT NULL COMMENT '原始文件名称',
`sort` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '排序字段',
`play_count` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '播放次数',
`is_free` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '是否可以试听:0收费 1免费',
`duration` float NOT NULL DEFAULT '0' COMMENT '视频时长(秒)',
`status` varchar(20) NOT NULL DEFAULT 'Empty' COMMENT 'Empty未上传 Transcoding转码中 Normal正常',
`size` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '视频源文件大小(字节)',
`version` bigint(20) unsigned NOT NULL DEFAULT '1' COMMENT '乐观锁',
`gmt_create` datetime NOT NULL COMMENT '创建时间',
`gmt_modified` datetime NOT NULL COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_movies_id` (`movies_id`),
KEY `idx_chapter_id` (`chapter_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT COMMENT='影视视频';
#
# Data for table "edu_video"
#
INSERT INTO `edu_video` VALUES ('1182499307429339137','18','32','第一节','','',0,0,0,0,'',0,1,
'2019-10-11 11:32:59','2019-10-11 11:57:38'),('1185312444399071234','14','1','12','','',0,0,0,0,
'Empty',0,1,'2019-10-19 05:51:23','2019-10-19 05:51:33'),('1189434737808990210','18','44','测试','','',
1,0,0,0,'Empty',0,1,'2019-10-30 14:51:55','2019-10-30 14:51:55'),
('1189471423678939138','18','1181729226915577857','test','2b887dc9584d4dc68908780ec57cd3b9',
'视频',1,0,0,0,'Empty',0,1,'2019-10-30 17:17:41','2019-10-30 17:17:41'),
('1189476403626409986','18','1181729226915577857','22','5155c73dc112475cbbddccf4723f7cef',
'视频.mp4',0,0,0,0,'Empty',0,1,'2019-10-30 17:37:29','2019-10-30 17:37:29'),
('1192252824606289921','1192252213659774977','1192252428399751169','第一段落',
'756cf06db9cb4f30be85a9758b19c645','eae2b847ef8503b81f5d5593d769dde2.mp4',0,0,0,0,
'Empty',0,1,'2019-11-07 09:29:59','2019-11-07 09:29:59'),
('1192628092797730818','1192252213659774977','1192252428399751169','第二段落',
'2a02d726622f4c7089d44cb993c531e1','eae2b847ef8503b81f5d5593d769dde2.mp4',0,0,1,0,
'Empty',0,1,'2019-11-08 10:21:10','2019-11-08 10:21:22'),
('1192632495013380097','1192252213659774977','1192252428399751169','第三段落',
'4e560c892fdf4fa2b42e0671aa42fa9d','eae2b847ef8503b81f5d5593d769dde2.mp4',0,0,1,0,'Empty',0,1,
'2019-11-08 10:38:40','2019-11-08 10:38:40'),('1194117638832111617','1192252213659774977','1192252428399751169',
'第四段落','4e560c892fdf4fa2b42e0671aa42fa9d','eae2b847ef8503b81f5d5593d769dde2.mp4',0,0,0,0,'Empty',0
,1,'2019-11-12 13:00:05','2019-11-12 13:00:05'),('1196263770832023554','1192252213659774977',
'1192252428399751169','第五段落','27d21158b0834cb5a8d50710937de330','eae2b847ef8503b81f5d5593d769dde2.mp4',
5,0,0,0,'Empty',0,1,'2019-11-18 11:08:03','2019-11-18 11:08:03'),
('17','18','15','第一节:喜剧','196116a6fee742e1ba9f6c18f65bd8c1','1',1,1000,1,100,'喜剧1',
0,1,'2019-01-01 13:08:57','2019-10-11 11:26:39'),('18','18','15','第二节:爱情剧',
'2d99b08ca0214909899910c9ba042d47','爱情剧',2,999,1,100,'爱情剧',0,1,'2019-01-01 13:09:02','2019-03-08 03:30:27'),
('19','18','15','第三节:爱情剧','51120d59ddfd424cb5ab08b44fc8b23a',
'eae2b847ef8503b81f5d5593d769dde2.mp4',3,888,0,100,'Draft',0,1,'2019-01-01 13:09:05','2019-11-12 12:50:45'),
('20','18','15','第四节:爱情剧','2a38988892d84df598752226c50f3fa3','爱情剧总结.avi',4,666,0,100,
'Draft',0,1,'2019-01-01 13:09:05','2019-10-11 09:20:09');
3.2 代码生成器
package com.example.movies;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.Test;
/**
* 自动生成代码.
* 记得修改配置信息.
*/
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(projectPath + "/src/main/java");
gc.setAuthor("yourName");
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://localhost:3306/movies?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 4、包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("movies"); //模块名
pc.setParent("com.example");
pc.setController("controller");
pc.setEntity("entity");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 5、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("edu_actor", "edu_movies"); // 表名称
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();
}
}
3.3 编写演员的功能实现
3.3.1 dao数据访问层
package com.example.movies.mapper;
import com.example.movies.entity.EduActor;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 演员 Mapper 接口
* </p>
*/
public interface EduActorMapper extends BaseMapper<EduActor> {
}
3.3.2 service业务层
- 接口
package com.example.movies.service;
import com.example.movies.entity.EduActor;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 演员 服务类
* </p>
*/
public interface EduActorService extends IService<EduActor> {
}
- 实现类
package com.example.movies.service.impl;
import com.example.movies.entity.EduActor;
import com.example.movies.mapper.EduActorMapper;
import com.example.movies.service.EduActorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 演员 服务实现类
* </p>
*/
@Service
public class EduActorServiceImpl extends ServiceImpl<EduActorMapper, EduActor> implements EduActorService {
}
3.3.3 controller控制层
package com.example.movies.controller;
import com.example.movies.service.EduActorService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* <p>
* 演员 前端控制器
* </p>
*/
@RestController
@RequestMapping("/movies/edu-actor")
public class EduActorController {
/**
* 依赖注册service
*/
@Autowired
private EduActorService actorService;
@ApiOperation("显示演员信息")
@GetMapping("/list")
public List list(){
return actorService.list(null);
}
}
3.4 编写逻辑删除(假删除)拦截器、编写分页的拦截器
- service_base模块中编写
package com.example.movies.config;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* 配置拦截器.
*/
@Configuration
@EnableTransactionManagement
public class MoviesConfig {
/**
* 逻辑删除插件
* @return
*/
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
/**
* 分页插件
* @return
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
3.5 在service_base模块中完成自动填充
就是自动完成数据添加的时间和修改的时间及逻辑删除的默认值填写
编写实现
package com.example.movies.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) { // 添加数据
// 添加日期到指定的字段中
setFieldValByName("gmtCreate", new Date(), metaObject);
setFieldValByName("gmtModified", new Date(), metaObject);
// 逻辑删除的默认值
setFieldValByName("isDeleted", 0, metaObject);
}
@Override
public void updateFill(MetaObject metaObject) { // 修改数据
setFieldValByName("gmtModified", new Date(), metaObject);
}
}
- 添加一个日志输出,方便代码的调试
#配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
- 在对应的实体Bean中添加
package com.example.movies.controller;
import com.example.movies.entity.EduActor;
import com.example.movies.service.EduActorService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 演员 前端控制器
* </p>
*/
@RestController
@RequestMapping("/movies/edu-actor")
public class EduActorController {
/**
* 依赖注册service
*/
@Autowired
private EduActorService actorService;
@ApiOperation("显示演员信息")
@GetMapping("/list")
public List list(){
return actorService.list(null);
}
@ApiOperation("保存演员数据")
@PostMapping("/save")
public void saveActor(EduActor actor) {
actorService.save(actor);
}
@ApiOperation("逻辑删除演员")
@DeleteMapping("del/{id}")
public void delect(@ApiParam(name = "id", value = "演员的主键", required = true) @PathVariable String id) {
actorService.removeById(id);
}
}
3.6 在subProject_service模块中添加依赖
<!--添加依赖-->
<dependency>
<groupId>com.example</groupId>
<artifactId>service_base</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
第四章:配置公共设置
4.1 公共的返回数据格式
- 在我们的项目中要求都是封装成json返回,一般我们会将所有接口的数据格式统一。
- 列表格式:
{
"success":true,
"code":20000,
"message":"成功",
"data":{
"items":[
{
"id":"1001",
"name":"刘德华",
"intro":"香港的著名演员"
}
]
}
}
- 分页格式:
{
"success":true,
"code":20000,
"message":"成功",
"data":{
"total":20,
"rows":[
{
"id":"1001",
"name":"刘德华",
"intro":"香港的著名演员"
}
]
}
}
- 无返回数据格式
{
"success":true,
"code":20000,
"message":"成功",
"data":{}
}
- 失败数据格式
{
"success":false,
"code":20001,
"message":"失败",
"data":{}
}
- 统一格式:
{
"success":布尔,//响应是否成功
"code":数字,//响应码
"message":字符串,//返回信息
"data":HashMap//返回数据
}
4.2 在子模块public_common/common_util中创建
- 创建返回码的接口
package com.example.util;
/**
* 返回码接口.
*/
public interface ResultCode {
/**
* 成功
*/
int SUCCESS = 20000;
/**
* 失败
*/
int ERROR = 20001;
}
- 创建结果类
package com.example.util;
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<>();
public 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;
}
public R success(boolean success) {
this.setSuccess(success);
return this;
}
public R message(String message) {
this.setMessage(message);
return this;
}
public R code(int code) {
this.setCode(code);
return this;
}
public R data(String key, Object value) {
this.data.put(key, value);
return this;
}
public R data(Map<String, Object> map) {
this.data(map);
return this;
}
}
4.2.1 在使用的模块中引入即可
<!--添加工具模块-->
<dependency>
<groupId>com.example</groupId>
<artifactId>common_util</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
- 修改演员的controller
package com.example.movies.controller;
import com.example.movies.entity.EduActor;
import com.example.movies.service.EduActorService;
import com.example.util.R;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 演员 前端控制器
* </p>
*/
@RestController
@RequestMapping("/movies/edu-actor")
public class EduActorController {
/**
* 依赖注册service
*/
@Autowired
private EduActorService actorService;
@ApiOperation("显示演员信息")
@GetMapping("/list")
public R list(){
return R.ok().data("items",actorService.list(null));
}
@ApiOperation("保存演员数据")
@PostMapping("/save")
public R saveActor(EduActor actor){
actorService.save(actor);
return R.ok();
}
@ApiOperation("逻辑删除演员")
@DeleteMapping("del/{id}")
public R delete(@ApiParam(name = "id",value = "演员的主键",required = true)
@PathVariable String id){
actorService.removeById(id);
return R.ok();
}
}
4.2.2 数据的分页
- service
package com.example.movies.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.movies.entity.EduActor;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.Map;
/**
* <p>
* 演员 服务类
* </p>
*/
public interface EduActorService extends IService<EduActor> {
/**
* 分页
* @param page
* @return
*/
Map<String,Object> getActorList(Page<EduActor> page);
}
- serviceImpl
package com.example.movies.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.movies.entity.EduActor;
import com.example.movies.mapper.EduActorMapper;
import com.example.movies.service.EduActorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* 演员 服务实现类
* </p>
*/
@Service
public class EduActorServiceImpl extends ServiceImpl<EduActorMapper, EduActor> implements EduActorService {
@Override
public Map<String, Object> getActorList(Page<EduActor> page) {
// 分页条件
QueryWrapper<EduActor> wrapper = new QueryWrapper<>();
wrapper.orderByDesc("id");
baseMapper.selectPage(page,wrapper);
// 当前页、总的页数、每页记录数、总的记录数
long current = page.getCurrent();
long pages = page.getPages();
long size = page.getSize();
long total = page.getTotal();
// 记录
List<EduActor> records = page.getRecords();
// 上一页、下一页
boolean hasPrevious = page.hasPrevious();
boolean hasNext = page.hasNext();
// 添加分页条件
Map<String, Object> map = new HashMap<>();
map.put("current", current);
map.put("pages", pages);
map.put("size", size);
map.put("total", total);
map.put("records", records);
map.put("hasPrevious", hasPrevious);
map.put("hasNext", hasNext);
return map;
}
}
- controller
package com.example.movies.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.movies.entity.EduActor;
import com.example.movies.service.EduActorService;
import com.example.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 演员 前端控制器
* </p>
*/
@RestController
@RequestMapping("/movies/edu-actor")
public class EduActorController {
/**
* 依赖注册service
*/
@Autowired
private EduActorService actorService;
@ApiOperation("显示演员信息")
@GetMapping("/list")
public R list(){
return R.ok().data("items",actorService.list(null));
}
@ApiOperation("保存演员数据")
@PostMapping("/save")
public R saveActor(EduActor actor){
actorService.save(actor);
return R.ok();
}
@ApiOperation("逻辑删除演员")
@DeleteMapping("del/{id}")
public R delete(@ApiParam(name = "id",value = "演员的主键",required = true)
@PathVariable String id){
actorService.removeById(id);
return R.ok();
}
@ApiOperation("演员分页")
@GetMapping("{page}/{limit}")
public R listPage(@ApiParam(name = "page",value = "当前页码",required = true)
@PathVariable long page,
@ApiParam(name = "limit",value = "每页显示的记录数",required = true)
@PathVariable long limit){
// 添加分页参数
Page<EduActor> actorPage = new Page<>(page, limit);
actorService.getActorList(actorPage);
List<EduActor> records = actorPage.getRecords();
long total = actorPage.getTotal();
//返回
return R.ok().data("total", total).data("rows", records);
}
}
4.2.3 演员完成条件查询
- 根据演员的名称、头衔level、演员的演戏时间
4.2.3.1 创建一个查询类
package com.example.movies.query;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 演员的查询条件类.
*/
@Data
@ApiModel(value = "actor查询对象", description = "把演员的查询条件封装")
public class ActorQuery {
@ApiModelProperty(value = "演员的名称,模糊查询")
private String name;
@ApiModelProperty(value = "头衔,1表示一线")
private Integer level;
@ApiModelProperty(value = "开始查询时间", example = "2020-02-25 14:19:02")
private String begin;
@ApiModelProperty(value = "结束查询时间", example = "2020-02-25 14:19:02")
private String end;
}
4.2.3.2 业务编写
- service
package com.example.movies.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.movies.entity.EduActor;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.movies.query.ActorQuery;
import java.util.Map;
/**
* <p>
* 演员 服务类
* </p>
*/
public interface EduActorService extends IService<EduActor> {
/**
* 演员分页
* @param page 分页条件
* @return
*/
Map<String,Object> getActorList(Page<EduActor> page);
/**
* 演员条件分页
* @param page 分页条件
* @param actorQuery 查询条件
*/
void pageQuery(Page<EduActor> page, ActorQuery actorQuery);
}
- serviceImpl
package com.example.movies.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.movies.entity.EduActor;
import com.example.movies.mapper.EduActorMapper;
import com.example.movies.query.ActorQuery;
import com.example.movies.service.EduActorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* 演员 服务实现类
* </p>
*/
@Service
public class EduActorServiceImpl extends ServiceImpl<EduActorMapper, EduActor> implements EduActorService {
@Override
public Map<String, Object> getActorList(Page<EduActor> page) {
// 分页条件
QueryWrapper<EduActor> wrapper = new QueryWrapper<>();
wrapper.orderByDesc("id");
baseMapper.selectPage(page,wrapper);
// 当前页、总的页数、每页记录数、总的记录数
long current = page.getCurrent();
long pages = page.getPages();
long size = page.getSize();
long total = page.getTotal();
// 记录
List<EduActor> records = page.getRecords();
// 上一页、下一页
boolean hasPrevious = page.hasPrevious();
boolean hasNext = page.hasNext();
// 添加分页条件
Map<String, Object> map = new HashMap<>();
map.put("current", current);
map.put("pages", pages);
map.put("size", size);
map.put("total", total);
map.put("records", records);
map.put("hasPrevious", hasPrevious);
map.put("hasNext", hasNext);
return map;
}
@Override
public void pageQuery(Page<EduActor> page, ActorQuery actorQuery) {
// 查询对象
QueryWrapper<EduActor> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("sort");
// 添加查询的条件
if (actorQuery == null) {
baseMapper.selectPage(page, queryWrapper);
return ;
}
// 演员的名称
String name = actorQuery.getName();
// 演员的等级
Integer level = actorQuery.getLevel();
// 演员的时间段
String begin = actorQuery.getBegin();
String end = actorQuery.getEnd();
// 判断
if (name != null && !name.isEmpty()) {
// 模糊
queryWrapper.like("name", name);
}
if (level != null && !StringUtils.isEmpty(level + "")) {
// 等于
queryWrapper.eq("level", level);
}
if (begin != null && !begin.isEmpty()) {
// 大于
queryWrapper.ge("begin", begin);
}
if (end != null && !end.isEmpty()) {
// 小于
queryWrapper.le("end", end);
}
// 添加条件到mapper
baseMapper.selectPage(page, queryWrapper);
}
}
- controller
package com.example.movies.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.movies.entity.EduActor;
import com.example.movies.query.ActorQuery;
import com.example.movies.service.EduActorService;
import com.example.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 演员 前端控制器
* </p>
*/
@RestController
@RequestMapping("/movies/edu-actor")
public class EduActorController {
/**
* 依赖注册service
*/
@Autowired
private EduActorService actorService;
@ApiOperation("显示演员信息")
@GetMapping("/list")
public R list(){
return R.ok().data("items", actorService.list(null));
}
@ApiOperation("保存演员数据")
@PostMapping("/save")
public R saveActor(EduActor actor){
actorService.save(actor);
return R.ok();
}
@ApiOperation("逻辑删除演员")
@DeleteMapping("del/{id}")
public R delete(@ApiParam(name = "id", value = "演员的主键", required = true)
@PathVariable String id){
actorService.removeById(id);
return R.ok();
}
@ApiOperation("演员条件分页")
@GetMapping("{page}/{limit}")
public R listPage(@ApiParam(name = "page", value = "当前页码", required = true)
@PathVariable long page,
@ApiParam(name = "limit", value = "每页显示的记录数", required = true)
@PathVariable long limit,
@ApiParam(name = "actorQuery",value = "查询对象",required = false) ActorQuery actorQuery){
// 添加分页参数
Page<EduActor> actorPage = new Page<>(page, limit);
// actorService.getActorList(actorPage);
// 添加查询条件
actorService.pageQuery(actorPage, actorQuery);
List<EduActor> records = actorPage.getRecords();
long total = actorPage.getTotal();
//返回
return R.ok().data("total", total).data("rows", records);
}
}
4.3 编写统一异常处理
- 自定义异常类
package com.example.exceptionhandler;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 自定义异常类.
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class customException extends RuntimeException{
/**
* 异常码
*/
private Integer code;
/**
* 异常信息
*/
private String msg;
}
- 全局统一异常信息类
package com.example.exceptionhandler;
import com.example.util.R;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 全局统一异常信息类.
* @ResponseBody // 返回的数据格式(json)
*/
@ControllerAdvice
public class GlobalExceptionHandler {
@ApiOperation(value = "指定出现异常调用的方法")
@ExceptionHandler(Exception.class)
@ResponseBody
public R error(Exception e) {
e.printStackTrace();
return R.error().message("这是一个全局的异常...");
}
@ApiOperation(value = "自定义异常")
@ExceptionHandler(customException.class)
@ResponseBody
public R error(customException e) {
e.printStackTrace();
return R.error().code(e.getCode()).message(e.getMessage());
}
@ApiOperation(value = "特定异常")
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public R error(ArithmeticException e) {
e.printStackTrace();
return R.error().message("执行了ArithmeticException异常...");
}
}
第五章:演员前端开发
- 使用vue的脚手架(vue-admin-template-master)+elementUI完成前端展现
- ide: Visual Studio Code
- 前端模板:https://gitee.com/panjiachen/vue-admin-template.git
5.1 解压vue-admin-template-master模板到指定的目录中
- 需要在线安装依赖的软件
npm install
- 下载后的依赖都在node_modules目录中
- 启动模块
npm run dev
- 浏览器地址:http://localhost:9528
- 去掉代码检查
5.2 模板的目录结构
- src
- 国际化配置
5.3 调试登录的错误
- 查看登录代码
- 把连接的地址修改为自己项目的连接
- 编写登录方法
package com.example.movies.controller;
import com.example.util.R;
import org.springframework.web.bind.annotation.*;
/**
* 自己编写一个登录.
* @CrossOrigin 跨域
*/
@RestController
@RequestMapping("/user")
@CrossOrigin
public class ActorLoginController {
@PostMapping("/login")
public R login() { // 登录
return R.ok().data("token", "admin");
}
@GetMapping("/info")
public R info() { // 登录返回信息
return R.ok()
.data("roles", "admin")
.data("name", "admin")
.data("avatar", "xxx");
}
}
5.4 编写演员页面
5.4.1 编写路由
- src/router/index.js添加演员路由
{
path: '/actor',
component: Layout,
redirect: '/actor/list',
name: 'Example',
meta: { title: '演员信息', icon: 'example' },
children: [
{
path: 'list',
name: 'Table',
component: () => import('@/views/actor/list'),
meta: { title: '演员列表', icon: 'table' }
},
{
path: 'save',
name: 'Tree',
component: () => import('@/views/actor/saveActor'),
meta: { title: '添加演员', icon: 'tree' }
},
{
path: 'edit/:id',
name: 'Tree',
component: () => import('@/views/actor/saveActor'),
meta: { title: '修改演员', icon: 'tree' },
hidden: true
}
]
},
- 编写可以访问后台代码的js脚本,src/api/movies/actor.js
import request from '@/utils/request'
export default {
//显示分页演员列表
getPageList(page, limit, searchObj){
return request({
url: `/edu-actor/${page}/${limit}`,
method: 'post',
data: searchObj
})
},
//显示所有演员列表
getActorAll(){
return request({
url: `/edu-actor/list`,
method: 'get'
})
},
//根据id删除演员
deleteActor(id){
return request({
url: `/edu-actor/del/${id}`,
method: 'delete'
})
},
//保存演员信息
saveActor(actor){
return request({
url: `/edu-actor/save`,
method: 'post',
data: actor
})
},
//获取更新对象
findById(id){
return request({
url: `/edu-actor/data/${id}`,
method: 'get'
})
},
//更新对象
updateActor(actor){
return request({
url: `/edu-actor/update`,
method: 'put',
data: actor
})
}
}
5.4.2 编写vue页面
- 编写list.vue页面显示演员信息
- 编写saveActor.vue页面保存演员信息
5.4.2.1 编写演员的列表页面list.vue
<template>
<div class="app-container">
<!-- 演员查询表单 -->
<el-form :inline="true" class="demo-form-inline">
<el-form-item label="演员名称">
<el-input v-model="actorQuery.name" placeholder="演员名称"></el-input>
</el-form-item>
<el-form-item label="演员头衔">
<el-select v-model="actorQuery.level" placeholder="演员头衔">
<el-option label="一线演员" value="1"></el-option>
<el-option label="二线演员" value="2"></el-option>
</el-select>
</el-form-item>
<el-form-item label="添加时间">
<el-date-picker
v-model="actorQuery.begin"
type="datetime"
placeholder="选择开始日期时间"
value-format="yyyy-MM-dd HH:mm:ss"
default-time="00:00:00"
/>
</el-form-item>
<el-form-item label="添加时间">
<el-date-picker
v-model="actorQuery.end"
type="datetime"
placeholder="选择结束日期时间"
value-format="yyyy-MM-dd HH:mm:ss"
default-time="00:00:00"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="getList()">查 询</el-button>
<el-button type="default" @click="resetData()">清 空</el-button>
</el-form-item>
</el-form>
<!-- 演员列表的表格 -->
<el-table :data="list" style="width: 100%">
<el-table-column label="序号">
<template slot-scope="scope">
{{(page-1)*limit+scope.$index+1}}
</template>
</el-table-column>
<el-table-column label="演员名称" prop="name"> </el-table-column>
<el-table-column label="演员头衔">
<template slot-scope="scope">
{{scope.row.level===1?'一线演员':'二线演员'}}
</template>
</el-table-column>
<el-table-column label="演员介绍" prop="intro"> </el-table-column>
<el-table-column label="演员入职日期" prop="gmtCreate"> </el-table-column>
<el-table-column>
<template slot-scope="scope">
<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">更 新</el-button >
<el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">刪 除</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页按钮 -->
<el-pagination
@size-change="handleSizeChange"
@current-change="getList"
:current-page="page"
:page-sizes="[3,5,7]"
:page-size="limit"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
</template>
<script>
//引入调用演员的js
import actor from "@/api/movies/actor.js";
export default {
//编写核心代码
data() {
return {
list: null,
page: 1,
limit: 3,
total: 0,
actorQuery: {},
};
},
created() {},
methods: {
//查询方法
getList() {},
//清空方法
resetData() {
this.actorQuery = {};
},
//删除
handleDelete(){}
},
};
</script>
<style>
</style>
5.4.2.2 实现前端的功能
- list列表
<template>
<div class="app-container">
<!-- 演员查询表单 -->
<el-form :inline="true" class="demo-form-inline">
<el-form-item label="演员名称">
<el-input v-model="actorQuery.name" placeholder="演员名称"></el-input>
</el-form-item>
<el-form-item label="演员头衔">
<el-select v-model="actorQuery.level" placeholder="演员头衔">
<el-option label="一线演员" :value="1"></el-option>
<el-option label="二线演员" :value="2"></el-option>
</el-select>
</el-form-item>
<el-form-item label="添加时间">
<el-date-picker
v-model="actorQuery.begin"
type="datetime"
placeholder="选择开始日期时间"
value-format="yyyy-MM-dd HH:mm:ss"
default-time="00:00:00"
/>
</el-form-item>
<el-form-item label="添加时间">
<el-date-picker
v-model="actorQuery.end"
type="datetime"
placeholder="选择结束日期时间"
value-format="yyyy-MM-dd HH:mm:ss"
default-time="00:00:00"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="getList()">查 询</el-button>
<el-button type="default" @click="resetData()">清 空</el-button>
</el-form-item>
</el-form>
<!-- 演员列表的表格 -->
<el-table :data="list" style="width: 100%">
<el-table-column label="序号">
<template slot-scope="scope">
{{(page-1)*limit+scope.$index+1}}
</template>
</el-table-column>
<el-table-column label="演员名称" prop="name"> </el-table-column>
<el-table-column label="演员头衔">
<template slot-scope="scope">
{{scope.row.level===1?'一线演员':'二线演员'}}
</template>
</el-table-column>
<el-table-column label="演员介绍" prop="intro"> </el-table-column>
<el-table-column label="演员入职日期" prop="gmtCreate"> </el-table-column>
<el-table-column>
<template slot-scope="scope">
<router-link :to="'/actor/edit/'+scope.row.id">
<el-button size="mini">更 新</el-button >
</router-link>
<el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">刪 除</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页按钮 -->
<el-pagination
@size-change="handleSizeChange"
@current-change="getList"
:current-page="page"
:page-sizes="[3,5,7]"
:page-size="limit"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
</template>
<script>
//引入调用演员的js
import actor from "@/api/movies/actor.js";
export default {
//编写核心代码
data() {
return {
list: null,
page: 1,
limit: 3,
total: 0,
actorQuery: {
},
};
},
created() {
this.getList()
},
methods: {
//查询方法
getList(page=1) {
this.page = page
//调用自定义函数
actor.getPageList(this.page,this.limit,this.actorQuery).then((result) => {//请求成功
this.list = result.data.items
this.total = result.data.total
}).catch((err) => {
});
// actor.getActorAll().then((result) => {//请求成功
// this.list = result.data.items
// this.total = result.data.total
// });
},
handleSizeChange(size){
this.limit = size
this.getList()
},
//清空方法
resetData() {
this.actorQuery = {};
},
//删除
handleDelete(id){
this.$confirm('是否删除?','提示',{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(res=>{
actor.deleteActor(id).then(res=>{
this.$message({
type: 'success',
message: '删除成功'
})
//调用演员的列表方法
this.getList()
})
})
}
},
};
</script>
<style>
</style>
- saveActor.vue保存
<template>
<div class="app-container">
<!-- 演员表单 -->
<el-form label-width="80px">
<el-form-item label="演员名称">
<el-input v-model="actor.name"></el-input>
</el-form-item>
<el-form-item label="演员排序">
<el-input v-model="actor.sort"></el-input>
</el-form-item>
<el-form-item label="演员头衔">
<el-input v-model="actor.level"></el-input>
</el-form-item>
<el-form-item label="演员简介">
<el-input v-model="actor.intro"></el-input>
</el-form-item>
<el-form-item label="演员资历">
<el-input v-model="actor.career"></el-input>
</el-form-item>
<el-form-item >
<el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保 存</el-button>
<el-button :disabled="saveBtnDisabled" type="default" @click="resetActor">清 空</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
//需要导入控件
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'
//引入调用演员的js
import actorFun from "@/api/movies/actor.js";
export default {
//注册控件
components:{ImageCropper,PanThumb},
data(){
return{
actor:{},
saveBtnDisabled: false,
imageCropperShow: false,
imagecropperKey: 0
}
},
created(){
this.init()
},
watch:{//监听路由的变化
$route(to,from){
this.init()
}
},
methods:{
//初始化方法
init(){
if(this.$route.params && this.$route.params.id){
const id = this.$route.params.id
//调用获取演员的方法
this.getInfo(id)
}
},
//保存或更新
saveOrUpdate(){
//根据演员的id判断是否为保存或更新
if(this.actor.id){
this.update()
}else{
this.save()
}
},
//保存
save(){
actorFun.saveActor(this.actor).then((result) => {
this.$message({
type: 'success',
message: '保存成功'
})
//显示列表,通过路由的路径显示演员列表
this.$router.push({path:'/actor/list'})
}).catch((err) => {
});
},
//更新
update(){
actorFun.updateActor(this.actor).then(res=>{
this.$message({
type: 'success',
message: '更新成功'
})
//返回到演员列表
this.$router.push({path:'/actor/list'})
})
},
getInfo(id){
actorFun.findById(id).then(res=>{
this.actor = res.data.actor
})
},
//清空
resetActor(){
this.actor = {}
}
}
}
</script>
5.4.3 编写java代码
- 处理跨域,在 EduActorController 上添加@CrossOrigin
- 添加更新方法
- 实现演员条件查询
package com.example.movies.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.movies.entity.EduActor;
import com.example.movies.query.ActorQuery;
import com.example.movies.service.EduActorService;
import com.example.util.R;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 演员 前端控制器
* </p>
* @CrossOrigin 解决跨域问题
*/
@RestController
@RequestMapping("/edu-actor")
@CrossOrigin
public class EduActorController {
/**
* 依赖注册service
*/
@Autowired
private EduActorService actorService;
@ApiOperation("显示演员信息")
@GetMapping("/list")
public R list(){
return R.ok().data("items", actorService.list(null));
}
@ApiOperation("保存演员数据")
@PostMapping("/save")
public R saveActor(@RequestBody EduActor actor){
actorService.save(actor);
return R.ok();
}
@ApiOperation("逻辑删除演员")
@DeleteMapping("del/{id}")
public R delete(@ApiParam(name = "id", value = "演员的主键", required = true)
@PathVariable String id){
actorService.removeById(id);
return R.ok();
}
@ApiOperation("演员条件分页")
@PostMapping("/{page}/{limit}")
public R listPage(@ApiParam(name = "page", value = "当前页码", required = true)
@PathVariable long page,
@ApiParam(name = "limit", value = "每页显示的记录数", required = true)
@PathVariable long limit,
@ApiParam(name = "actorQuery",value = "查询对象",required = false) @RequestBody(required = false) ActorQuery actorQuery){
// 创建分页对象
Page<EduActor> actorPage = new Page<>(page, limit);
// 构造分页条件
QueryWrapper<EduActor> wrapper = new QueryWrapper<>();
if (actorQuery != null) {
String name = actorQuery.getName();
Integer level = actorQuery.getLevel();
String begin = actorQuery.getBegin();
String end = actorQuery.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(end)) {
wrapper.le("gmt_create", end);
}
}
// 排序
wrapper.orderByDesc("gmt_create");
// 分页
actorService.page(actorPage, wrapper);
// 总记录数
long total = actorPage.getTotal();
// 没有显示的记录
List<EduActor> records = actorPage.getRecords();
// 返回
return R.ok().data("total", total).data("items", records);
}
@ApiOperation("获取需要更新的对象")
@GetMapping("/data/{id}")
public R getData(@PathVariable String id) {
EduActor actor = actorService.getById(id);
return R.ok().data("actor", actor);
}
@ApiOperation("更新演员信息")
@PutMapping("/update")
public R update(@RequestBody EduActor actor) {
actorService.updateById(actor);
return R.ok();
}
}
注意:如果前端提示跨域:
- 后端代码是否已经处理跨域了
- 查看提交的方式是否正确
5.5 上传的图片存储在阿里云OSS
5.5.1 开通阿里云oss服务
- 价格明细
- 创建bucket
- 选择:添加名称、标准存储、公共读、不开通
- 查看生成的id和秘钥
- 通过手机认证后可以获取到:id和秘钥,这是我们开发上传图片必须的条件。
5.5.2 查看sdk的使用
- 添加依赖配置
5.5.3 创建一个子项目完成oss
subproject_service/service_oss
pom
<?xml version="1.0" encoding="UTF-8"?>
<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>subproject_service</artifactId>
<groupId>com.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>service_oss</artifactId>
<dependencies>
<!--阿里云-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<!--日期工具栏-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<!--添加工具模块-->
<dependency>
<groupId>com.example</groupId>
<artifactId>common_util</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
- 配置application.properties
# 端口号
server.port=8082
# 服务名称
spring.application.name=server-oss
# 开发环境
spring.profiles.active=dev
# oss的网址、id、密钥
aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com
aliyun.oss.file.keyid=LTAI5tLdYSRZLG7QcX
aliyun.oss.file.keysecret=ggSt3VGWrniYKyjtZGVf8M
# buket名称
aliyun.oss.file.bucketname=oss-movies
# nacos地址
spring.cloud.nacos.discovery.server-addr=localhost:8848
- 主配置类
package com.example.movies;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* oss 启动类.
* 不需要加载项目的数据源.
*/
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableDiscoveryClient
public class OssApplication {
public static void main(String[] args) {
SpringApplication.run(OssApplication.class, args);
}
}
- 创建一个工具类读取application.properties中的配置信息
package com.example.movies.util;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 启动时自动读取.
*/
@Component
public class ConstantPropertiesUtils implements InitializingBean {
/**
* 读取配置文件application.properties
* oss的网址、id、密钥、Bucket名称
*/
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.keyid}")
private String keyId;
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Value("${aliyun.oss.file.bucketname}")
private String buckerName;
/**
* 创建常量
*/
public static String END_POINT;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
@Override
public void afterPropertiesSet() throws Exception {
END_POINT = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = buckerName;
}
}
- 业务层实现上传图片
package com.example.movies.server;
import org.springframework.web.multipart.MultipartFile;
/**
* 业务层 实现上传图片.
*/
public interface OssService {
String uploadFileAvatar(MultipartFile file);
}
- 实现类:完成图片上传,且返回地址
package com.example.movies.server.impl;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.example.movies.server.OssService;
import com.example.movies.util.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
/**
* 实现类 完成图片上传,且返回地址.
*/
@Component
public class OssServiceImpl implements OssService {
/**
* 演员的头像或影像的海报上传
* @param file
* @return
*/
@Override
public String uploadFileAvatar(MultipartFile file) {
// 通过工具类获取配置数据
// 获取oss的网址
String endPoint = ConstantPropertiesUtils.END_POINT;
// 获取访问凭证的ID
String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
// 获取访问凭证的秘钥
String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
// 获取 bucker 名称
String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
// 完成上传
try {
// 获取上传的输入流
InputStream inputStream = file.getInputStream();
// 获取文件名
String filename = file.getOriginalFilename();
// 为文件起一个唯一的名称
filename = UUID.randomUUID().toString().replaceAll("-", "") + filename;
// 按照年月日创建上传的目录存放图片:yyyy/MM/dd
String datePath = new DateTime().toString("yyyy/MM/dd");
// 拼接
filename = datePath + "/" + filename;
// 调用oss实现上传
OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
// 参数: bucker名称、文件名称、输入流
ossClient.putObject(bucketName, filename, inputStream);
// 关闭ossClient
ossClient.shutdown();
// 上传文件后需要获取文件的路径
String url = "http://" + bucketName + "." + endPoint + "/" + filename;
return url;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
- controller
package com.example.movies.controller;
import com.example.movies.server.OssService;
import com.example.util.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* 控制器 对象存储.
*/
@RestController
@RequestMapping("/oss")
@CrossOrigin
public class OssController {
@Autowired
private OssService ossService;
@ApiOperation("图片上传")
@PostMapping("/fileoss")
public R uploadOssFile(MultipartFile file) {
String url = ossService.uploadFileAvatar(file);
return R.ok().data("url", url);
}
}
5.6 配置网关
5.6.1 创建一个独立的项目完成网关配置
[
](https://cn.bing.com/dict/search?q=configuration&FORM=BDVSP6&cc=cn)
- 注意:网关配置中不允许有spring-boot-start-web,因为冲突
- pom
<?xml version="1.0" encoding="UTF-8"?>
<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>movies</artifactId>
<groupId>com.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<!--网关配置-->
<artifactId>Gateway_configuration</artifactId>
<dependencies>
<!--网关依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--nacos依赖-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
</project>
- 主配置类
package com.example.movies;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* 网关 主配置类.
*/
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
- 配置文件
server:
port: 7000
spring:
application:
name: service-gateway
cloud:
gateway:
discovery:
locator:
enabled: true
#跨域
routes:
- id: gateway-user
uri: lb://service-actor
predicates:
- Path=/user/**
- id: gateway-actor
uri: lb://service-actor
predicates:
- Path=/edu-actor/**
- id: gateway-movies
uri: lb://service-actor
predicates:
- Path=/edu-movies/**
- id: gateway-oss
uri: lb://service-oss
predicates:
- Path=/oss/**
nacos:
discovery:
server-addr: localhost:8848
- 编写一个配置类完成跨域设置
package com.xiudun.util;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
//跨域配置类
@Configuration
public class XiudunCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//跨域设置
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
5.6.2 配置前端
- 要把原来在controller中的跨域注解@CrossOrigin都去掉,否则会出现多次跨域错误
- 在前端使用网关的地址和端口
- 可以通过网关正常访问我们的vue
5.6.3 添加一个第三方的图片上传控件
- 把组件复制到前端的项目中;src/components/
- 在vue页面中使用组件
- 上传组件
<!-- 演员头像 -->
<el-form-item label="演员头像">
<!-- 头像的缩略图 -->
<pan-thumb :image="actor.avatar"/>
<!-- 图片的上传按钮 -->
<el-button type="primary" icon="el-icon-upload" @click="imageCropperShow=true">演员头像</el-button>
<!-- 使用导入后的组件 -->
<image-cropper
v-show="imageCropperShow"
:width="300"
:height="300"
:key="imagecropperKey"
:url="'http://localhost:8082/oss/fileoss'"
field="file"
@colse="close"
@crop-upload-success="cropSuccess"/>
</el-form-item>
- 图片上传方法
methods:{
//演员头像图片的上传
cropSuccess(data){
//上传成功
this.imageCropperShow = false
this.actor.avatar = data.url
this.imagecropperKey = this.imagecropperKey+1
},
close(){//关闭上传的window
this.imageCropperShow = false
this.imagecropperKey = this.imagecropperKey+1
},
}
- 上传后需要到阿里云中查看是否添加了图片
- 完整的上传vue代码
<template>
<div class="app-container">
<!-- 演员表单 -->
<el-form label-width="80px">
<el-form-item label="演员名称">
<el-input v-model="actor.name"></el-input>
</el-form-item>
<el-form-item label="演员排序">
<el-input v-model="actor.sort"></el-input>
</el-form-item>
<el-form-item label="演员头衔">
<el-input v-model="actor.level"></el-input>
</el-form-item>
<el-form-item label="演员简介">
<el-input v-model="actor.intro"></el-input>
</el-form-item>
<el-form-item label="演员资历">
<el-input v-model="actor.career"></el-input>
</el-form-item>
<!-- 演员头像 -->
<el-form-item label="演员头像">
<!-- 头像的缩略图 -->
<pan-thumb :image="actor.avatar"/>
<!-- 图片的上传按钮 -->
<el-button type="primary" icon="el-icon-upload" @click="imageCropperShow=true">演员头像</el-button>
<!-- 使用导入后的组件 -->
<image-cropper
v-show="imageCropperShow"
:width="300"
:height="300"
:key="imagecropperKey"
:url="'http://localhost:8082/oss/fileoss'"
field="file"
@colse="close"
@crop-upload-success="cropSuccess"/>
</el-form-item>
<el-form-item >
<el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保 存</el-button>
<el-button :disabled="saveBtnDisabled" type="default" @click="resetActor">清 空</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
//需要导入控件
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'
//引入调用演员的js
import actorFun from "@/api/movies/actor.js";
export default {
//注册控件
components:{ImageCropper,PanThumb},
data(){
return{
actor:{},
saveBtnDisabled: false,
imageCropperShow: false,
imagecropperKey: 0
}
},
created(){
this.init()
},
watch:{//监听路由的变化
$route(to,from){
this.init()
}
},
methods:{
//演员头像图片的上传
cropSuccess(data){
//上传成功
this.imageCropperShow = false
this.actor.avatar = data.url
this.imagecropperKey = this.imagecropperKey+1
},
close(){//关闭上传的window
this.imageCropperShow = false
this.imagecropperKey = this.imagecropperKey+1
},
//初始化方法
init(){
if(this.$route.params && this.$route.params.id){
const id = this.$route.params.id
//调用获取演员的方法
this.getInfo(id)
}
},
//保存或更新
saveOrUpdate(){
//根据演员的id判断是否为保存或更新
if(this.actor.id){
this.update()
}else{
this.save()
}
},
//保存
save(){
actorFun.saveActor(this.actor).then((result) => {
this.$message({
type: 'success',
message: '保存成功'
})
//显示列表,通过路由的路径显示演员列表
this.$router.push({path:'/actor/list'})
}).catch((err) => {
});
},
//更新
update(){
actorFun.updateActor(this.actor).then(res=>{
this.$message({
type: 'success',
message: '更新成功'
})
//返回到演员列表
this.$router.push({path:'/actor/list'})
})
},
getInfo(id){
actorFun.findById(id).then(res=>{
this.actor = res.data.actor
})
},
//清空
resetActor(){
this.actor = {}
}
}
}
</script>
<style>
</style>
第六章:影片分类
- 对应的数据表:edu_subject
6.1 Excel导入导出
- 数据的导入:减少输入的工作量
- 数据的导出:统计信息归档
- 数据的传输:异构系统间数据传输
6.2 EasyExcel完成导入导出
特点:Java领域解析,生成Excel比较有名的框架有Apache poi,jxl等,但他们都存在一个严重的问题就是非常的耗内存,如果你的系统并发量不大的话可能还行,但是一旦并发上来后一定会OOM或者JVM频繁的full gc.
EasyExcel是阿里巴巴开源的一个excel处理框架,以使用简单,节省内存著称,EasyExcel能大大减少占用内存的主要原因是在解析Excel时没有将文件数据一次性全部加载到内存中,而是从磁盘上一行行读取数据,逐个解析。
EasyExcel采用一行一行的解析模式,并将一行的解析结果以观察者的模式通知处理(AnalysisEventListener)。
6.3 使用EasyExcel
- domain:可能有数据表对应或没有
- vo:表示数据载体(没有数据表对应)
- entity: 一定有对应的数据表
- beans:等同vo
6.3.1 编写execl读写操作测试类
- 创建VO ```java package com.example.movies.vo;
import com.alibaba.excel.annotation.ExcelProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;
/**
- 学生的测试bean. */ @Data @NoArgsConstructor @AllArgsConstructor public class StudentVo { @ExcelProperty(“学号”) private Integer sno; @ExcelProperty(“姓名”) private String sname; }
- 创建读取监听器
```java
package com.example.movies.vo;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* execl监听器.
*/
public class ExcelLisener extends AnalysisEventListener<StudentVo> {
// 创建集合
private List<StudentVo> list = new ArrayList<>();
// 读取execl数据
@Override
public void invoke(StudentVo studentVo, AnalysisContext analysisContext) {
System.out.println(studentVo);
list.add(studentVo);
}
// 读取头信息
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
System.out.println("表头:" + headMap);
}
// 读取后
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
}
- 创建execl读写测试类 ```java package com.example.movies;
import com.alibaba.excel.EasyExcel; import com.alibaba.excel.ExcelReader; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.read.metadata.ReadSheet; import com.alibaba.excel.write.metadata.WriteSheet; import com.example.movies.vo.ExcelLisener; import com.example.movies.vo.StudentVo; import org.junit.Test;
import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList;
/**
execl的读写. / public class DemoExcelTexts { /*
自动关闭写入流 */ @Test public void testExeclWriteA() { ArrayList
vos = new ArrayList<>(); for (int i = 0; i < 10; i++) { vos.add(new StudentVo(1001+i,"张三"+i));
} // 创建文件 String file = “F:/JAVA/aa.xlsx”; // 写入execl EasyExcel.write(file, StudentVo.class).sheet(“写入”).doWrite(vos); }
/**
- 把数据写入excel方法2
必须手动关闭写入流 */ @Test public void testExeclWriteB() { ArrayList
vos = new ArrayList<>(); for (int i = 0; i < 10; i++) { vos.add(new StudentVo(1001+i, "张三"+i));
} // 创建文件 String file = “F:/JAVA/bb.xlsx”; // 写入execl ExcelWriter excelWriter = EasyExcel.write(file, StudentVo.class).build(); WriteSheet writeSheet = EasyExcel.writerSheet(“写入2”).build(); excelWriter.write(vos, writeSheet); // 关闭流 excelWriter.finish(); }
/**
读取方式1 */ @Test public void testExeclReadA() { // 文件的路径 String file = “F:/JAVA/aa.xlsx”; // 读取数据 EasyExcel.read(file, StudentVo.class, new ExcelLisener()).sheet().doRead(); }
/**
- 读取方式2
*/
@Test
public void testExeclReadB() {
// 文件的路径
String file = “F:/JAVA/aa.xlsx”;
try {
} catch (Exception e) {// 缓冲流
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
ExcelReader excelReader = EasyExcel.read(inputStream, StudentVo.class, new ExcelLisener()).build();
ReadSheet readSheet = EasyExcel.readSheet(0).build();
excelReader.read(readSheet);
// 关闭流
excelReader.finish();
} } } ```e.printStackTrace();
6.4 通过EasyExcel完成影片分类导入
- excel的数据模板
6.4.1 在演员服务中实现excel
- 创建实体
package com.xiudun.vo;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class ReadData {
@ExcelProperty(value = "一级分类",index = 0)
private String oneSubjectName;
@ExcelProperty(value = "二级分类",index = 1)
private String twoSubjectName;
}
- 编写主配置类
package com.xiudun;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SubjectApplication {
public static void main(String[] args) {
SpringApplication.run(SubjectApplication.class,args);
}
}
- 使用代码生成器生成对应的不同层的代码
package com.xiudun.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* 影视科目
* </p>
*
* @author xiudun
* @since 2021-02-28
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="EduSubject对象", description="影视科目")
public class EduSubject implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "影视类别ID")
@TableId(value = "id", type = IdType.ID_WORKER_STR)
private String id;
@ApiModelProperty(value = "类别名称")
private String title;
@ApiModelProperty(value = "父ID")
private String parentId;
@ApiModelProperty(value = "排序字段")
private Integer sort;
@ApiModelProperty(value = "创建时间")
@TableField(fill = FieldFill.INSERT)
private Date gmtCreate;
@ApiModelProperty(value = "更新时间")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date gmtModified;
}
- 编写监听器类
package com.xiudun.util;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiudun.entity.EduSubject;
import com.xiudun.service.EduSubjectService;
import com.xiudun.vo.ReadData;
import java.util.Map;
//excel监听器
public class ExcelLisener extends AnalysisEventListener<ReadData> {
//注入业务
private EduSubjectService subjectService;
//构造方法
public ExcelLisener() {}
public ExcelLisener(EduSubjectService subjectService) {
this.subjectService = subjectService;
}
//判断一级分类是否重复
private EduSubject existOneSubject(EduSubjectService subjectService,String name){
//查询条件
QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
wrapper.eq("title",name);
wrapper.eq("parent_id","0");
//添加判断条件
EduSubject subject = subjectService.getOne(wrapper);
return subject;
}
//判断二级分类是否重复
private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String pid){
//创建条件对象
QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
//添加添加条件
wrapper.eq("title",name);
wrapper.eq("parent_id",pid);
//获取二级的对象
EduSubject subject = subjectService.getOne(wrapper);
return subject;
}
//读取excel数据
public void invoke(ReadData readData, AnalysisContext analysisContext) {
//判断
if (readData==null) {
throw new RuntimeException("添加数据失败");
}
//添加一级分类
EduSubject existOneSubject = existOneSubject(subjectService, readData.getOneSubjectName());
if (existOneSubject==null) {//没有相同的
existOneSubject = new EduSubject();
existOneSubject.setTitle(readData.getOneSubjectName());
existOneSubject.setParentId("0");
subjectService.save(existOneSubject);
}
//获取一级分类的id
String pid = existOneSubject.getId();
//添加二级分类
EduSubject existTwoSubject = existTwoSubject(subjectService, readData.getTwoSubjectName(), pid);
if (existTwoSubject==null) {
existTwoSubject = new EduSubject();
existTwoSubject.setTitle(readData.getTwoSubjectName());
existTwoSubject.setParentId(pid);
subjectService.save(existTwoSubject);
}
}
@Override//读取头信息
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
System.out.println("表头:"+headMap);
}
//读取后
public void doAfterAllAnalysed(AnalysisContext analysisContext) { }
}
- 编写一个业务实现:通过文件上传的方式把影片的分类(Excel)添加到数据表中
package com.xiudun.service;
import com.xiudun.entity.EduSubject;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.web.multipart.MultipartFile;
/**
* <p>
* 影视科目 服务类
* </p>
*
* @author xiudun
* @since 2021-02-28
*/
public interface EduSubjectService extends IService<EduSubject> {
//上传excel
void batchImport(MultipartFile file,EduSubjectService subjectService);
}
- 业务实现类
package com.xiudun.service.impl;
import com.alibaba.excel.EasyExcel;
import com.xiudun.entity.EduSubject;
import com.xiudun.mapper.EduSubjectMapper;
import com.xiudun.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiudun.util.ExcelLisener;
import com.xiudun.vo.ReadData;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
/**
* <p>
* 影视科目 服务实现类
* </p>
*
* @author xiudun
* @since 2021-02-28
*/
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {
@Override
public void batchImport(MultipartFile file, EduSubjectService subjectService) {
try {
//文件输入流
InputStream inputStream = file.getInputStream();
//需要指定读取那个Class,读取默认sheet,文件流自动关闭
EasyExcel.read(inputStream, ReadData.class,new ExcelLisener(subjectService)).sheet().doRead();
}catch (Exception e){
e.printStackTrace();
}
}
}
- 编写controller
package com.xiudun.controller;
import com.xiudun.service.EduSubjectService;
import com.xiudun.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* <p>
* 影视科目 前端控制器
* </p>
*
* @author xiudun
* @since 2021-02-28
*/
@Api("影片分类管理")
@RestController
@RequestMapping("/edu-subject")
public class EduSubjectController {
//注入业务
@Autowired
private EduSubjectService subjectService;
@ApiOperation("excel批量导入数据")
@PostMapping("addSubject")
public R addSubject(MultipartFile file){
//上传文件
subjectService.batchImport(file,subjectService);
return R.ok();
}
}
- 使用swagger测试
- 添加网关配置
server:
port: 7000
spring:
application:
name: service-gateway
cloud:
gateway:
discovery:
locator:
enabled: true
#跨域
routes:
- id: gateway-user
uri: lb://service-actor
predicates:
- Path=/user/**
- id: gateway-actor
uri: lb://service-actor
predicates:
- Path=/edu-actor/**
- id: gateway-movies
uri: lb://service-actor
predicates:
- Path=/edu-movies/**
- id: gateway-oss
uri: lb://service-oss
predicates:
- Path=/oss/**
- id: gateway-oss
uri: lb://service-subject
predicates:
- Path=/edu-subject/**
nacos:
discovery:
server-addr: localhost:8848
- 前端使用树形表示数据展现,所以,需要在实体中添加一个外来属性
package com.xiudun.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import java.util.List;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* 影视科目
* </p>
*
* @author xiudun
* @since 2021-02-28
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="EduSubject对象", description="影视科目")
public class EduSubject implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "影视类别ID")
@TableId(value = "id", type = IdType.ID_WORKER_STR)
private String id;
@ApiModelProperty(value = "类别名称")
private String title;
@ApiModelProperty(value = "父ID")
private String parentId;
@ApiModelProperty(value = "排序字段")
private Integer sort;
@ApiModelProperty(value = "创建时间")
@TableField(fill = FieldFill.INSERT)
private Date gmtCreate;
@ApiModelProperty(value = "更新时间")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date gmtModified;
@ApiModelProperty("添加一个子菜单属性")
@TableField(exist = false)
private List<EduSubject> children;
}
- 在service中添加树形方法
public interface EduSubjectService extends IService<EduSubject> {
//上传excel
void batchImport(MultipartFile file,EduSubjectService subjectService);
//树形
List<EduSubject> listTree();
}
- 实现类
package com.xiudun.service.impl;
import com.alibaba.excel.EasyExcel;
import com.xiudun.entity.EduSubject;
import com.xiudun.mapper.EduSubjectMapper;
import com.xiudun.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiudun.util.ExcelLisener;
import com.xiudun.vo.ReadData;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;
/**
* <p>
* 影视科目 服务实现类
* </p>
*
* @author xiudun
* @since 2021-02-28
*/
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {
@Override
public void batchImport(MultipartFile file, EduSubjectService subjectService) {
try {
//文件输入流
InputStream inputStream = file.getInputStream();
//需要指定读取那个Class,读取默认sheet,文件流自动关闭
EasyExcel.read(inputStream, ReadData.class,new ExcelLisener(subjectService)).sheet().doRead();
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public List<EduSubject> listTree() {
//获取所有分类数据
List<EduSubject> entities = baseMapper.selectList(null);
//找到一级分类
return entities.stream().filter(categoryEntity->categoryEntity.getParentId().equals("0"))
.map(menu-> menu.setChildren(getChildrens(menu,entities)))
.sorted((m1,m2)->(m1.getSort()==null?0:m1.getSort())-(m2.getSort()==null?0:m2.getSort()))
.collect(Collectors.toList());
}
//编写一个读取树形的递归方法
private List<EduSubject> getChildrens(EduSubject root,List<EduSubject> all){
//递归查找
List<EduSubject> list = all.stream().filter(categoryEntity -> {
return categoryEntity.getParentId().equals(root.getId());//找子节点
}).map(categoryEntity -> {//子节点
categoryEntity.setChildren(getChildrens(categoryEntity, all));
return categoryEntity;
}).sorted((m1, m2) -> {
return (m1.getSort() == null ? 0 : m1.getSort()) - (m2.getSort() == null ? 0 : m2.getSort());
}).collect(Collectors.toList());
//返回子节点集合
return list;
}
}
- 编写controller
package com.xiudun.controller;
import com.xiudun.service.EduSubjectService;
import com.xiudun.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* <p>
* 影视科目 前端控制器
* </p>
*
* @author xiudun
* @since 2021-02-28
*/
@Api("影片分类管理")
@RestController
@RequestMapping("/edu-subject")
public class EduSubjectController {
//注入业务
@Autowired
private EduSubjectService subjectService;
@ApiOperation("excel批量导入数据")
@PostMapping("addSubject")
public R addSubject(MultipartFile file){
//上传文件
subjectService.batchImport(file,subjectService);
return R.ok();
}
@ApiOperation("分类数据Tree")
@GetMapping("getListTree")
public R listTree(){
return R.ok().data("items", subjectService.listTree());
}
}
- 使用swagger测试代码
6.5 完成前端编写
6.5.1 配置路由数据
{
path: '/edu-subject',
component: Layout,
redirect:'/getListTree',
name:'subject',
meta:{title:'影片分类',icon:'form'},
children: [
{
path: 'list',
component: () => import('@/views/actor/subjectList'),
name: 'subjectList',
meta: { title: '影片分类列表',icon:'form' }
},
{
path: 'import',
component: () => import('@/views/actor/importExcel'),
name: 'subjectImport',
meta: { title: '导入影片分类数据',icon:'form' }
}
]
},
6.5.2 在api中编写js脚本
import request from '@/utils/request'
export default {
//影片分类列表
getSubjectList(){
return request({
url: '/edu-subject/getListTree',
method: 'get'
})
}
}
6.5.3 编写vue页面:list.vue
<template>
<div class="app-container">
<!-- 添加树形控件 -->
<el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
<el-tree
class="filter-tree"
:data="data2"
:props="defaultProps"
default-expand-all
:filter-node-method="filterNode"
ref="tree2">
</el-tree>
</div>
</template>
<script>
// 导入js
import subject from '@/api/movies/subject'
export default {
data(){
return{
filterText: '',
data2: [],
defaultProps:{
children: 'children',
label: 'title'
}
}
},
created(){
this.getAllSubjectList()
},
watch:{
filterText(val){
this.$refs.tree2.filter(val)
}
},
methods:{
//获取影片分类数据
getAllSubjectList(){
subject.getSubjectList().then((result) => {
this.data2 = result.data.items
}).catch((err) => {
console.log("数据失败")
});
},
//过滤节点数据
filterNode(value,data){
if(!value) return true
return data.title.toLowerCase().indexOf(value.toLowerCase())!==-1
}
}
}
</script>
<style>
</style>
6.5.4 完成“影片分类”导入
<template>
<div class="app-container">
<!-- 添加表单 -->
<el-form>
<el-form-item label="信息描述">
<el-tag type="info">excel模板样例</el-tag>
<el-tag>
<i class="el-icon-download"/>
<a :href="'/static/影片分类.xlsx'">模板下载</a>
</el-tag>
</el-form-item>
<!-- excel文件上传 -->
<el-form-item label="上传Excel文件">
<el-upload
class="upload-demo"
ref="upload"
:on-success="fileUploadSuccess"
:on-error="fileUploadError"
:disabled="importBtnDisabled"
:limit="1"
:action="BASE_API+'edu-subject/addSubject'"
:auto-upload="false"
name="file"
accept="application/vnd.ms-excel">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
</el-upload>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
data(){
return{
BASE_API: process.env.BASE_API,
importBtnDisabled: false,
loading: false
}
},
created(){},
methods:{
submitUpload(){//上传
this.importBtnDisabled = true
this.loading = true
this.$refs.upload.submit()
},
fileUploadSuccess(){//上传成功
this.loading = false
this.$message({
type:'success',
message: '影片分类数据添加成功'
})
},
fileUploadError(){//上传失败
this.loading = false
this.$message({
type:'error',
message: '影片分类数据添加失败'
})
}
}
}
</script>
<style>
</style>
第七章:影片视频管理
7.1 创建一个子模块
- xiudun_service/service_movies模块
- pom
<?xml version="1.0" encoding="UTF-8"?>
<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>xiudun_service</artifactId>
<groupId>com.xiudun</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>service_movies</artifactId>
<dependencies>
<!--阿里云视频点播-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<!--日期工具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
</dependencies>
</project>
- application.yml
server:
port: 8084
spring:
application:
name: service-movies
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/movies?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
username: root
password: root
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
cloud:
nacos:
discovery:
server-addr: localhost:8848
- 主配置类
package com.xiudun;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
@EnableDiscoveryClient
@MapperScan("com.xiudun.mapper")
public class MoviesApplication {
public static void main(String[] args) {
SpringApplication.run(MoviesApplication.class,args);
}
}
7.2 编写java功能实现
7.2.1 数据表
- edu_movies影片表
- edu_movies_description影片简介表
- edu_chapter影片章节表
- edu_video视频表
- edu_actor主角
- edu_subject影片分类表
7.2.2 通过代码生成器生成表及对应的层代码
7.2.3 创建需要的数据载体VO
- 影片描述实体
package com.xiudun.vo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.math.BigDecimal;
@Api("影片描述信息")
@Data
public class CourseInfoVo {
@ApiModelProperty("影片id")
private String id;
@ApiModelProperty("演员的id")
private String actorId;
@ApiModelProperty("影片分类id")
private String subjectId;
@ApiModelProperty("影片一级分类id")
private String subjectParentId;
@ApiModelProperty("影片名称")
private String title;
@ApiModelProperty("影片价格,设置0表示免费")
private BigDecimal price;
@ApiModelProperty("影片的总段数")
private Integer videoNum;
@ApiModelProperty("影片封面海报")
private String cover;
@ApiModelProperty("影片简介")
private String description;
}
- 影片发布信息
package com.xiudun.vo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Api("影片发布信息")
@Data
public class CoursePublishVo {
@ApiModelProperty("影片id")
private String id;
@ApiModelProperty("影片名称")
private String title;
@ApiModelProperty("影片的总段数")
private Integer videoNum;
@ApiModelProperty("影片封面海报")
private String cover;
@ApiModelProperty("演员一级头衔")
private String subjectLevelOne;
@ApiModelProperty("演员二级头衔")
private String subjectLevelTwo;
@ApiModelProperty("主演名称")
private String actorName;
@ApiModelProperty("影片价格,用于显示")
private String price;
}
- 按照主演查询的vo
package com.xiudun.vo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Api("用于查询")
@Data
public class ActorQuery {
@ApiModelProperty("演员名称,用于like查询")
private String name;
@ApiModelProperty("演员的头衔,1表示一线演员,2表示二线演员")
private Integer level;
@ApiModelProperty(value = "上映时间",example = "2020-12-25 10:10:00")
private String begin;
@ApiModelProperty(value = "上映时间",example = "2021-02-25 10:10:00")
private String end;
}
7.2.4 编写dao(data access object)
package com.xiudun.mapper;
import com.xiudun.entity.EduMovies;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiudun.vo.CoursePublishVo;
/**
* <p>
* 影视 Mapper 接口
* </p>
*
* @author xiudun
* @since 2021-03-01
*/
public interface EduMoviesMapper extends BaseMapper<EduMovies> {
//发布的影片
CoursePublishVo getPulishCourseInfo(String courseId);
}
7.2.5 编写service业务层
package com.xiudun.service;
import com.xiudun.entity.EduMovies;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xiudun.vo.CourseInfoVo;
/**
* <p>
* 影视 服务类
* </p>
*
* @author xiudun
* @since 2021-03-01
*/
public interface EduMoviesService extends IService<EduMovies> {
//添加影片基本信息
String saveCourseInfo(CourseInfoVo courseInfoVo);
//根据影片id获取影片基本信息
CourseInfoVo getCourseInfo(String courseId);
//修改影片基本信息
void updateCourseInfo(CourseInfoVo courseInfoVo);
//根据影片id发布
CourseInfoVo puslishCourseInfo(String id);
}
- 实现类
package com.xiudun.service.impl;
import com.xiudun.entity.EduMovies;
import com.xiudun.entity.EduMoviesDescription;
import com.xiudun.exceptionhandler.XiudunException;
import com.xiudun.mapper.EduMoviesMapper;
import com.xiudun.service.EduMoviesDescriptionService;
import com.xiudun.service.EduMoviesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiudun.vo.CourseInfoVo;
import com.xiudun.vo.CoursePublishVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* <p>
* 影视 服务实现类
* </p>
*
* @author xiudun
* @since 2021-03-01
*/
@Service
public class EduMoviesServiceImpl extends ServiceImpl<EduMoviesMapper, EduMovies> implements EduMoviesService {
//注入影片描述
private EduMoviesDescriptionService eduMoviesDescriptionService;
@Override
public String saveCourseInfo(CourseInfoVo courseInfoVo) {
//1.添加影片基本信息 2.需要把vo的数据转换影片的bean:CouseInfoVo--EduMovies(entity)
EduMovies eduMovies = new EduMovies();
BeanUtils.copyProperties(courseInfoVo,eduMovies);//按照相同的属性名称对拷
int insert = baseMapper.insert(eduMovies);
//判断是否保存成功
if (insert==0) {
throw new XiudunException(20001,"影片添加失败");
}
//获取添加后的影片id
String moviesId = eduMovies.getId();
//添加影片简介(edu_movies_description)
EduMoviesDescription eduMoviesDescription = new EduMoviesDescription();
eduMoviesDescription.setDescription(courseInfoVo.getDescription());
//影片和影片简介是one-to-one关系
eduMoviesDescription.setId(moviesId);
eduMoviesDescriptionService.save(eduMoviesDescription);
//返回影片的id
return moviesId;
}
@Override//根据影片的id获取影片信息
public CourseInfoVo getCourseInfo(String courseId) {
EduMovies eduMovies = baseMapper.selectById(courseId);
//影片信息的vo
CourseInfoVo courseInfoVo = new CourseInfoVo();
//完成对拷
BeanUtils.copyProperties(eduMovies,courseInfoVo);
//获取影片的简介信息
EduMoviesDescription moviesDescription = eduMoviesDescriptionService.getById(courseId);
courseInfoVo.setDescription(moviesDescription.getDescription());
return courseInfoVo;
}
@Override//更新影片信息
public void updateCourseInfo(CourseInfoVo courseInfoVo) {
//创建影片的实体
EduMovies eduMovies = new EduMovies();
BeanUtils.copyProperties(courseInfoVo,eduMovies);//对拷
//添加一个修改日期
eduMovies.setGmtModified(new Date());
int update = baseMapper.updateById(eduMovies);
//判断更新是否成功
if (update==0) {
throw new XiudunException(20001,"影片信息更新失败");
}
//修改影片简介信息
EduMoviesDescription moviesDescription = new EduMoviesDescription();
moviesDescription.setId(courseInfoVo.getId());
moviesDescription.setDescription(courseInfoVo.getDescription());
moviesDescription.setGmtModified(new Date());
eduMoviesDescriptionService.updateById(moviesDescription);
}
@Override//影片发布信息
public CoursePublishVo puslishCourseInfo(String id) {
//CoursePublishVo pulishCourseInfo = baseMapper.getPulishCourseInfo(id);
return baseMapper.getPulishCourseInfo(id);
}
}
7.2.6 编写controller控制层
package com.xiudun.controller;
import com.xiudun.service.EduMoviesService;
import com.xiudun.util.R;
import com.xiudun.vo.CourseInfoVo;
import com.xiudun.vo.CoursePublishVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* <p>
* 影视 前端控制器
* </p>
*
* @author xiudun
* @since 2021-03-01
*/
@RestController
@RequestMapping("/edu-movies")
public class EduMoviesController {
//依赖
@Autowired
private EduMoviesService moviesService;
@ApiOperation("添加影片基本信息")
@PostMapping("addMoviesInfo")//只要post对@RequestBody有效
public R addMoviesInfo(@RequestBody CourseInfoVo courseInfoVo){
//添加后返回影片id
String id = moviesService.saveCourseInfo(courseInfoVo);
return R.ok().data("moviesId", id);
}
@ApiOperation("根据影片id获取基本信息")
@GetMapping("getMoviesInfo/{moviesId}")
public R getMoviesInfo(@PathVariable String moviesId){
CourseInfoVo courseInfo = moviesService.getCourseInfo(moviesId);
return R.ok().data("courseInfoVo", courseInfo);
}
@ApiOperation("更新影片信息")
@PutMapping("updateMoviesInfo")
public R updateMoviesInfo(@RequestBody CourseInfoVo courseInfoVo){
moviesService.updateCourseInfo(courseInfoVo);
return R.ok();
}
@ApiOperation("根据影片id获取发布影片信息")
@GetMapping("getPublishMoviesInfo/{id}")
public R getPublishMoviesInfo(@PathVariable("id") String id){
CoursePublishVo publishVo = moviesService.puslishCourseInfo(id);
return R.ok().data("publishVo", publishVo);
}
}
- 添加网关配置
- id: gateway-oss3
uri: lb://service-movies
predicates:
- Path=/edu-movies/**
7.3 编写影片管理的前端
7.3.1 编写js完成前后端的操作
import request from '@/utils/request'
export default {
//添加影片信息
addMoviesInfo(moviesInfo){
return request({
url: `/edu-movies/addMoviesInfo`,
method: 'post',
data: moviesInfo
})
},
//影片id获取信息
getMoviesInfoId(id){
return request({
url: `/edu-movies/getMoviesInfo/${id}`,
method: 'get'
})
},
//更新影片信息
updateMovies(moviesInfo){
return request({
url: `/edu-movies/updateMoviesInfo`,
method: 'put',
data: moviesInfo
})
}
}
7.3.2 添加一个路由路径调用vue页面
- src/router/index.js
{
path: '/edu-movies',
component: Layout,
redirect: '/nested/menu1',
name: 'Nested',
meta: {
title: '影片管理',
icon: 'nested'
},
children: [
{
path: 'list',
component: () => import('@/views/actor/movies'),
name: 'moviesName',
meta: { title: '影片信息',icon:'form' }
},
{
path: 'import',
component: () => import('@/views/actor/'),
name: 'subjectImport',
meta: { title: '导入影片分类数据',icon:'form' }
}
]
},
7.3.3 编写movies.vue
- 在页面中添加”步骤条”控件
<template>
<div class="app-container">
<h2 style="text-align:center">发布新影片</h2>
<!-- 步骤条 -->
<el-steps :active="active" finish-status="success">
<el-step title="填写影片基本信息"></el-step>
<el-step title="创建影片视频章节"></el-step>
<el-step title="发布影片"></el-step>
</el-steps>
<!-- 添加影片表单 -->
<el-form label-width="120px">
<el-form-item label="影片标题">
<el-input v-model="courseInfoVo.title" placeholder="例如:战争片:战狼"/>
</el-form-item>
<el-form-item label="影片分类">
<el-select v-model="courseInfoVo.subjectParentId" placeholder="请选择一级分类" @change="subjectLevelOneChanged">
<el-option
v-for="subject in sujectOneList"
:key="subject.id"
:label="subject.title"
:value="subject.id">
</el-option>
</el-select>
<el-select v-model="courseInfoVo.subjectId" placeholder="请选择二级分类" >
<el-option
v-for="subject in sujectTwoList"
:key="subject.id"
:label="subject.title"
:value="subject.id">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="影片主演">
<el-select v-model="courseInfoVo.actorId" placeholder="请选择" >
<el-option
v-for="actor in actorList"
:key="actor.id"
:label="actor.name"
:value="actor.id">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="总视频数">
<el-input-number :min="0" v-model="courseInfoVo.videoNum" controls-position="right" label="请填写总视频数"/>
</el-form-item>
<el-form-item label="影片简介">
<!-- 第三方控件 -->
</el-form-item>
<el-form-item label="影片海报">
<el-upload
class="upload-demo"
action="BASE_API+'/oss/fileoss'"
:show-file-list="false"
:on-success="handleAvatarUpload"
:before-upload="beforeAvatarUpload"
>
<img :src="courseInfoVo.cover">
</el-upload>
</el-form-item>
<el-form-item label="影片价格">
<el-input-number :min="0" v-model="courseInfoVo.price" controls-position="right" label="0表示免费影片"/>
</el-form-item>
<el-form-item>
<el-button type="primary" :disabled="saveBtnDisbled" @click="saveOrUpdate">保存并下一步</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
- 实现基本功能
<template>
<div class="app-container">
<h2 style="text-align:center">发布新影片</h2>
<!-- 步骤条 -->
<el-steps :active="1" process-status="wait" align-center>
<el-step title="填写影片基本信息"></el-step>
<el-step title="创建影片视频章节"></el-step>
<el-step title="发布影片"></el-step>
</el-steps>
<!-- 添加影片表单 -->
<el-form label-width="120px">
<el-form-item label="影片标题">
<el-input v-model="courseInfoVo.title" placeholder="例如:战争片:战狼"/>
</el-form-item>
<el-form-item label="影片分类">
<el-select v-model="courseInfoVo.subjectParentId" placeholder="请选择一级分类" @change="subjectLevelOneChanged">
<el-option
v-for="subject in subjectOneList"
:key="subject.id"
:label="subject.title"
:value="subject.id">
</el-option>
</el-select>
<el-select v-model="courseInfoVo.subjectId" placeholder="请选择二级分类" >
<el-option
v-for="subject in subjectTwoList"
:key="subject.id"
:label="subject.title"
:value="subject.id">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="影片主演">
<el-select v-model="courseInfoVo.actorId" placeholder="请选择" >
<el-option
v-for="actor in actorList"
:key="actor.id"
:label="actor.name"
:value="actor.id">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="总视频数">
<el-input-number :min="0" v-model="courseInfoVo.videoNum" controls-position="right" label="请填写总视频数"/>
</el-form-item>
<el-form-item label="影片简介">
<!-- 第三方控件 -->
</el-form-item>
<el-form-item label="影片海报">
<el-upload
class="upload-demo"
action="BASE_API+'/oss/fileoss'"
:show-file-list="false"
:on-success="handleAvatarUpload"
:before-upload="beforeAvatarUpload"
>
<img :src="courseInfoVo.cover">
</el-upload>
</el-form-item>
<el-form-item label="影片价格">
<el-input-number :min="0" v-model="courseInfoVo.price" controls-position="right" label="0表示免费影片"/>
</el-form-item>
<el-form-item>
<el-button type="primary" :disabled="saveBtnDisbled" @click="saveOrUpdate">保存并下一步</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
//导入js
import movies from '@/api/movies/movies'
import actor from '@/api/movies/actor'
import subject from '@/api/movies/subject'
export default {
data(){
return{
courseInfoVo: {
videoNum: 0,
price: 0,
cover: '/static/001.jpeg'
},
saveBtnDisbled: false,
subjectOneList:[],
subjectTwoList: [],
actorList: []
}
},
created(){
//加载演员信息
this.getListActor()
//加载一级分类
this.getOneSubject()
},
watch(){},
methods:{
saveOrUpdate(){},
handleAvatarUpload(){},
beforeAvatarUpload(){} ,
//获取演员的列表
getListActor(){
actor.getActorAll().then((result) => {
this.actorList = result.data.items
}).catch((err) => {
console.log('演员数据失败')
});
} ,
//获取一级分类列表数据
getOneSubject(){
subject.getSubjectList().then(res=>{
this.subjectOneList = res.data.items
})
} ,
//当一级分类内容变化时影响二级分类数据
subjectLevelOneChanged(value){
//console.log('变化的值='+value)
//value是一级分类的id值
//循环分类数据
for(var i=0;i<this.subjectOneList.length;i++){
//每一级分类
var oneSubject = this.subjectOneList[i]
//根据一级id获取对应的children
if(value===oneSubject.id){
this.subjectTwoList = oneSubject.children
//如果没有那么把二级id清空
this.courseInfoVo.subjectId = ''
}
}
}
}
}
</script>
<style>
</style>
7.3.3.1 模块优化:添加可视化编辑器
- Tinymce复制到components和static中
- 添加到html的配置中
templateParameters:{
BASE_URL: config.dev.assetsPublicPath + config.dev.assetsSubDirectory
}
- 在总的index.html中引入
<script src=<%=BASE_URL%>/tinymce4.7.5/tinymce.min.js></script>
<script src=<%=BASE_URL%>/tinymce4.7.5/langs/zh_CN.js></script>
7.3.3.2 在vue引入
<template>
<div class="app-container">
<h2 style="text-align:center">发布新影片</h2>
<!-- 步骤条 -->
<el-steps :active="1" process-status="wait" align-center>
<el-step title="填写影片基本信息"></el-step>
<el-step title="创建影片视频章节"></el-step>
<el-step title="发布影片"></el-step>
</el-steps>
<!-- 添加影片表单 -->
<el-form label-width="120px">
<el-form-item label="影片标题">
<el-input v-model="courseInfoVo.title" placeholder="例如:战争片:战狼"/>
</el-form-item>
<el-form-item label="影片分类">
<el-select v-model="courseInfoVo.subjectParentId" placeholder="请选择一级分类" @change="subjectLevelOneChanged">
<el-option
v-for="subject in subjectOneList"
:key="subject.id"
:label="subject.title"
:value="subject.id">
</el-option>
</el-select>
<el-select v-model="courseInfoVo.subjectId" placeholder="请选择二级分类" >
<el-option
v-for="subject in subjectTwoList"
:key="subject.id"
:label="subject.title"
:value="subject.id">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="影片主演">
<el-select v-model="courseInfoVo.actorId" placeholder="请选择" >
<el-option
v-for="actor in actorList"
:key="actor.id"
:label="actor.name"
:value="actor.id">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="总视频数">
<el-input-number :min="0" v-model="courseInfoVo.videoNum" controls-position="right" label="请填写总视频数"/>
</el-form-item>
<el-form-item label="影片简介">
<!-- 第三方控件 -->
<tinymce :height="300" v-model="courseInfoVo.description"/>
</el-form-item>
<el-form-item label="影片海报">
<el-upload
class="upload-demo"
:action="BASE_API+'oss/fileoss'"
:show-file-list="false"
:on-success="handleAvatarUpload"
:before-upload="beforeAvatarUpload"
>
<img :src="courseInfoVo.cover">
</el-upload>
</el-form-item>
<el-form-item label="影片价格">
<el-input-number :min="0" v-model="courseInfoVo.price" controls-position="right" label="0表示免费影片"/>
</el-form-item>
<el-form-item>
<el-button type="primary" :disabled="saveBtnDisbled" @click="saveOrUpdate">保存并下一步</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
//导入js
import movies from '@/api/movies/movies'
import actor from '@/api/movies/actor'
import subject from '@/api/movies/subject'
//引入组件
import Tinymce from '@/components/Tinymce'
export default {
//需要声明
components: {Tinymce},
data(){
return{
courseInfoVo: {
videoNum: 0,
price: 0,
cover: '/static/001.jpeg'
},
saveBtnDisbled: false,
subjectOneList:[],
subjectTwoList: [],
actorList: [],
BASE_API: process.env.BASE_API
}
},
created(){
//加载演员信息
this.getListActor()
//加载一级分类
this.getOneSubject()
},
watch(){},
methods:{
saveOrUpdate(){},
handleAvatarUpload(res,file){//上传海报
this.courseInfoVo.cover = res.data.url//获取上传后的地址
},
beforeAvatarUpload(file){//上传前检查
const isJPG = file.type==='image/jpeg'
const is2M = file.size /1024 /1024 <2
//判断
if(!isJPG) this.$message.error('图片的格式必须是jpeg')
if(!is2M) this.$message.error('图片的大小不能超过2MB')
return isJPG && is2M
} ,
//获取演员的列表
getListActor(){
actor.getActorAll().then((result) => {
this.actorList = result.data.items
}).catch((err) => {
console.log('演员数据失败')
});
} ,
//获取一级分类列表数据
getOneSubject(){
subject.getSubjectList().then(res=>{
this.subjectOneList = res.data.items
})
} ,
//当一级分类内容变化时影响二级分类数据
subjectLevelOneChanged(value){
//console.log('变化的值='+value)
//value是一级分类的id值
//循环分类数据
for(var i=0;i<this.subjectOneList.length;i++){
//每一级分类
var oneSubject = this.subjectOneList[i]
//根据一级id获取对应的children
if(value===oneSubject.id){
this.subjectTwoList = oneSubject.children
//如果没有那么把二级id清空
this.courseInfoVo.subjectId = ''
}
}
}
}
}
</script>
<style>
</style>
7.3.3.3 完成影片信息的添加并下一步
<template>
<div class="app-container">
<h2 style="text-align:center">发布新影片</h2>
<!-- 步骤条 -->
<el-steps :active="1" process-status="wait" align-center>
<el-step title="填写影片基本信息"></el-step>
<el-step title="创建影片视频章节"></el-step>
<el-step title="发布影片"></el-step>
</el-steps>
<!-- 添加影片表单 -->
<el-form label-width="120px">
<el-form-item label="影片标题">
<el-input v-model="courseInfoVo.title" placeholder="例如:战争片:战狼"/>
</el-form-item>
<el-form-item label="影片分类">
<el-select v-model="courseInfoVo.subjectParentId" placeholder="请选择一级分类" @change="subjectLevelOneChanged">
<el-option
v-for="subject in subjectOneList"
:key="subject.id"
:label="subject.title"
:value="subject.id">
</el-option>
</el-select>
<el-select v-model="courseInfoVo.subjectId" placeholder="请选择二级分类" >
<el-option
v-for="subject in subjectTwoList"
:key="subject.id"
:label="subject.title"
:value="subject.id">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="影片主演">
<el-select v-model="courseInfoVo.actorId" placeholder="请选择" >
<el-option
v-for="actor in actorList"
:key="actor.id"
:label="actor.name"
:value="actor.id">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="总视频数">
<el-input-number :min="0" v-model="courseInfoVo.videoNum" controls-position="right" label="请填写总视频数"/>
</el-form-item>
<el-form-item label="影片简介">
<!-- 第三方控件 -->
<tinymce :height="300" v-model="courseInfoVo.description"/>
</el-form-item>
<el-form-item label="影片海报">
<el-upload
class="upload-demo"
:action="BASE_API+'oss/fileoss'"
:show-file-list="false"
:on-success="handleAvatarUpload"
:before-upload="beforeAvatarUpload"
>
<img :src="courseInfoVo.cover">
</el-upload>
</el-form-item>
<el-form-item label="影片价格">
<el-input-number :min="0" v-model="courseInfoVo.price" controls-position="right" label="0表示免费影片"/>
</el-form-item>
<el-form-item>
<el-button type="primary" :disabled="saveBtnDisbled" @click="saveOrUpdate">保存并下一步</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
//导入js
import movies from '@/api/movies/movies'
import actor from '@/api/movies/actor'
import subject from '@/api/movies/subject'
//引入组件
import Tinymce from '@/components/Tinymce'
export default {
//需要声明
components: {Tinymce},
data(){
return{
courseInfoVo: {
videoNum: 0,
price: 0,
cover: '/static/001.jpeg'
},
saveBtnDisbled: false,
subjectOneList:[],
subjectTwoList: [],
actorList: [],
BASE_API: process.env.BASE_API,
moviesId: ''
}
},
created(){
//判断路由的参数:id如果在就更新否则添加
if(this.$route.params && this.$route.params.id){
this.moviesId = this.$route.params.id
//调用查询方法把数据添加到页面
this.getInfo()
} else{
//加载演员信息
this.getListActor()
//加载一级分类
this.getOneSubject()
}
},
watch(){},
methods:{
saveOrUpdate(){
//判断
if(this.moviesId!=''){
this.updateCourse()
}else{
this.addCourse()
}
},
//根据id获取影片信息
getInfo(){},
//保存影片信息
addCourse(){
movies.addMoviesInfo(this.courseInfoVo).then(res=>{
//提示
this.$message({
type: 'success',
message: '影片信息添加成功'
})
//跳到第二步:视频章节
this.$router.push({path:'/edu-movies/chapter/'+res.data.moviesId})
})
},
//更新影片信息
updateCourse(){
movies.updateMovies(this.courseInfoVo).then(res=>{
//提示
this.$message({
type: 'success',
message: '影片信息更新成功'
})
//跳到第二步:视频章节
this.$router.push({path:'/edu-movies/chapter/'+this.moviesId})
})
},
handleAvatarUpload(res,file){//上传海报
this.courseInfoVo.cover = res.data.url//获取上传后的地址
},
beforeAvatarUpload(file){//上传前检查
const isJPG = file.type==='image/jpeg'
const is2M = file.size /1024 /1024 <2
//判断
if(!isJPG) this.$message.error('图片的格式必须是jpeg')
if(!is2M) this.$message.error('图片的大小不能超过2MB')
return isJPG && is2M
} ,
//获取演员的列表
getListActor(){
actor.getActorAll().then((result) => {
this.actorList = result.data.items
}).catch((err) => {
console.log('演员数据失败')
});
} ,
//获取一级分类列表数据
getOneSubject(){
subject.getSubjectList().then(res=>{
this.subjectOneList = res.data.items
})
} ,
//当一级分类内容变化时影响二级分类数据
subjectLevelOneChanged(value){
//console.log('变化的值='+value)
//value是一级分类的id值
//循环分类数据
for(var i=0;i<this.subjectOneList.length;i++){
//每一级分类
var oneSubject = this.subjectOneList[i]
//根据一级id获取对应的children
if(value===oneSubject.id){
this.subjectTwoList = oneSubject.children
//如果没有那么把二级id清空
//this.courseInfoVo.subjectId = ''
}
}
},
getInfo(){//获取更新的数据回填到控件中
movies.getMoviesInfoId(this.moviesId).then(response=>{
//获取影片的基本信息、获取一级二级分类的信息
this.courseInfoVo = response.data.courseInfoVo
//根据id获取 一级二级分类的信息
subject.getSubjectList().then(res=>{
//获取一级分类
this.subjectOneList = res.data.items
//遍历一级分类
for(var i=0;i<this.subjectOneList.length;i++){
//获取每个一级分类
var oneSubject = this.subjectOneList[i]
//根据id获取对应的二级分类
if(this.courseInfoVo.subjectParentId==oneSubject.id){
this.subjectTwoList = oneSubject.children
}
}
})
//所有的演员
this.getListActor()
})
}
}
}
</script>
<style>
</style>
7.3.3.4 编写视频章节vue
<template>
<div class="app-container">
<h2 style="text-align:center">发布新影片</h2>
<!-- 步骤条 -->
<el-steps :active="2" process-status="wait" align-center>
<el-step title="填写影片基本信息"></el-step>
<el-step title="创建影片视频章节"></el-step>
<el-step title="发布影片"></el-step>
</el-steps>
<el-button type="text" @click="openChapterDialog()">添加片段</el-button>
<div>
<el-button @click="prevous">上一步</el-button>
<el-button :disabled="saveBtnDisbled" type="primary" @click="next">下一步</el-button>
</div>
</div>
</template>
<script>
export default {
data(){
return{
saveBtnDisbled: false,
courseId: ''//影片id
}
},
created(){
//获取路由id
if(this.$route.params && this.$route.params.id){
//获取影片的id
this.courseId = this.$route.params.id
}
console.log('id='+this.courseId)
},
methods:{
prevous(){//上一步:更新影片信息
this.$router.push({path:'/edu-movies/info/'+this.courseId})
},
next(){}
}
}
</script>
<style>
</style>
7.4 影片视频章节
7.4.1 后端编写
- 创建视频节数vo
package com.xiudun.vo;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class ChapterVo {
private String id;
private String title ;
//视频节数
private List<VideoVo> children = new ArrayList<>();
}
- 视频的描述
package com.xiudun.vo;
import lombok.Data;
@Data
public class VideoVo {
private String id;
private String title;
}
- 视频节数的业务层
package com.xiudun.service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.xiudun.entity.EduChapter;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xiudun.vo.ChapterVo;
import java.util.List;
/**
* <p>
* 影视 服务类
* </p>
*
* @author xiudun
* @since 2021-03-01
*/
public interface EduChapterService extends IService<EduChapter> {
//根据影片id查询视频的列表
List<ChapterVo> getChapterVideoByCourseId(String courseId);
//根据视频id删除
boolean deleteChapter(String chapterId);
}
- 业务层实现
package com.xiudun.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiudun.entity.EduChapter;
import com.xiudun.entity.EduVideo;
import com.xiudun.exceptionhandler.XiudunException;
import com.xiudun.mapper.EduChapterMapper;
import com.xiudun.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiudun.service.EduVideoService;
import com.xiudun.vo.ChapterVo;
import com.xiudun.vo.VideoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* 影视 服务实现类
* </p>
*
* @author xiudun
* @since 2021-03-01
*/
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
//注入
@Autowired
private EduVideoService videoService;
@Override//根据id获取视频列表
public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
//根据影片id,获取视频的片段数
QueryWrapper<EduChapter> wrapperChapter = new QueryWrapper<>();
wrapperChapter.eq("movies_id",courseId);
List<EduChapter> eduChapterList = baseMapper.selectList(wrapperChapter);
//获取影视视频
QueryWrapper<EduVideo> wrapperVideo = new QueryWrapper<>();
wrapperVideo.eq("movies_id",courseId);
List<EduVideo> eduVideoList = videoService.list(wrapperVideo);
//封装视频片段数据
List<ChapterVo> finalList = new ArrayList<>();
//遍历片段
for (int i = 0; i < eduChapterList.size(); i++) {
//每个片段
EduChapter eduChapter = eduChapterList.get(i);
//对拷到VO中
ChapterVo chapterVo = new ChapterVo();
BeanUtils.copyProperties(eduChapter,chapterVo);
//添加到集合中
finalList.add(chapterVo);
//创建一个存储视频信息的集合
ArrayList<VideoVo> videoList = new ArrayList<>();
//封装视频
for (int n = 0; n < eduVideoList.size(); n++) {
//获取每个视频信息
EduVideo eduVideo = eduVideoList.get(n);
//判断视频和片段的外键是否一致
if (eduVideo.getChapterId().equals(eduChapter.getId())) {
//封装到集合中
VideoVo videoVo = new VideoVo();
//对拷
BeanUtils.copyProperties(eduVideo,videoVo);
videoList.add(videoVo);
}
}
//把视频的信息列表添加到片段中
chapterVo.setChildren(videoList);
}
return finalList;
}
@Override//删除片段
public boolean deleteChapter(String chapterId) {
//需要判断:因为如果含有视频了,那么就不能删除了
QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
wrapper.eq("chapter_id",chapterId);
int count = videoService.count(wrapper);
//判断
if (count>0) {
throw new XiudunException(20001,"不能删除含有视频的片段");
}
return baseMapper.deleteById(chapterId)>0;
}
}
- controller控制层
package com.xiudun.controller;
import com.xiudun.entity.EduChapter;
import com.xiudun.service.EduChapterService;
import com.xiudun.util.R;
import com.xiudun.vo.ChapterVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 影视 前端控制器
* </p>
*
* @author xiudun
* @since 2021-03-01
*/
@RestController
@RequestMapping("/edu-chapter")
public class EduChapterController {
@Autowired
private EduChapterService chapterService;
@ApiOperation("根据id获取片段信息")
@GetMapping("getChapterVideo/{courseId}")
public R getChapterVideo(@PathVariable String courseId){
List<ChapterVo> list = chapterService.getChapterVideoByCourseId(courseId);
return R.ok().data("allChapterVideo", list);
}
@ApiOperation("添加影片片段信息")
@PostMapping("addChapter")
public R addChapter(@RequestBody EduChapter eduChapter){
chapterService.save(eduChapter);
return R.ok();
}
@ApiOperation("根据id获取视频信息")
@GetMapping("getChapterInfo/{chapterId}")
public R getChapterInfo(@PathVariable String chapterId){
EduChapter eduChapter = chapterService.getById(chapterId);
return R.ok().data("chapter", eduChapter);
}
@ApiOperation("修改视频片段信息")
@PutMapping("updateChapter")
public R updateChapter(@RequestBody EduChapter eduChapter){
chapterService.updateById(eduChapter);
return R.ok();
}
@ApiOperation("删除视频片段信息")
@DeleteMapping("deleteChapter/{chapterId}")
public R deleteChapter(@PathVariable String chapterId){
return chapterService.deleteChapter(chapterId) ? R.ok() : R.error();
}
}
- 测试后端
7.4.2 编写前端
7.4.2.1 vue基础编写
- 编写api/chapter.js
import request from '@/utils/request'
export default {
//根据id获取视频列表
getAllChapterVideo(courseId){
return request({
url: `/edu-chapter/getChapterVideo/${courseId}`,
method: 'get'
})
},
//添加视频节数
addChapter(chapter){
return request({
url: `/edu-chapter/addChapter`,
method: 'post',
data: chapter
})
},
//根据id获取视频描述内容
getChapter(courseId){
return request({
url: `/edu-chapter/getChapterInfo/${courseId}`,
method: 'get'
})
},
//修改视频片段描述内容
updateChapter(chapter){
return request({
url: `/edu-chapter/updateChapter`,
method: 'put',
data: chapter
})
},
//删除视频片段描述内容
deleteChapter(courseId){
return request({
url: `/edu-chapter/deleteChapter/${courseId}`,
method: 'delete'
})
}
}
- 在index.js完成路由路径
{
path: '/edu-movies',
component: Layout,
redirect: '/nested/menu1',
name: 'Nested',
meta: {
title: '影片管理',
icon: 'nested'
},
children: [
{
path: 'info',
component: () => import('@/views/actor/movies'),
name: 'moviesName',
meta: { title: '影片信息',icon:'form' }
},
{
path: 'list',
component: () => import('@/views/actor/list'),
name: 'subjectImport',
meta: { title: '影片列表',icon:'form' }
},
{
path: `info/:id`,
component: () => import('@/views/actor/movies'),
name: 'moviesName1',
meta: { title: '影片信息',icon:'form' },
hidden: true
},
{
path: 'chapter/:id',
component: () => import('@/views/actor/chapter'),
name: 'chapterName',
meta: { title: '影片章节视频',icon:'form' },
hidden: true
},
{
path: 'publish/:id',
component: () => import('@/views/actor/publish'),
name: 'chapterName',
meta: { title: '影片发布',icon:'form' },
hidden: true
}
]
}
7.4.2.2 编写chapter.vue页面
<template>
<div class="app-container">
<h2 style="text-align:center">发布新影片</h2>
<!-- 步骤条 -->
<el-steps :active="2" process-status="wait" align-center>
<el-step title="填写影片基本信息"></el-step>
<el-step title="创建影片视频章节"></el-step>
<el-step title="发布影片"></el-step>
</el-steps>
<el-button type="text" @click="openChapterDialog()">添加片段</el-button>
<!-- 影片片段 -->
<ul class="chanpterList">
<li
v-for="chapter in chapterVideoList"
:key="chapter.id">
<p>
{{chapter.title}}
<span class="acts">
<el-button type="text" @click="openVideo(chapter.id)">添加视频</el-button>
<el-button type="text" @click="openEditChapter(chapter.id)">编辑视频</el-button>
<el-button type="text" @click="removeChapter(chapter.id)">删除视频</el-button>
</span>
</p>
<!-- 视频 -->
<ul class="chanpterList videoList">
<li
v-for="video in chapter.children"
:key="video.id">
<p>
{{video.title}}
<span class="acts">
<el-button type="text">编辑</el-button>
<el-button type="text" @click="removeVideo(video.id)">删除</el-button>
</span>
</p>
</li>
</ul>
</li>
</ul>
<div>
<el-button @click="prevous">上一步</el-button>
<el-button :disabled="saveBtnDisbled" type="primary" @click="next">下一步</el-button>
</div>
<!-- 弹出窗体:添加或修改片段 -->
<el-dialog title="添加影片片段" :visible.sync="dialogChapterFormVisible">
<el-form :model="chapter">
<el-form-item label="片段名称" >
<el-input v-model="chapter.title" />
</el-form-item>
<el-form-item label="片段排序" >
<el-input-number v-model="chapter.sort" :min="0" controls-position="right"/>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogChapterFormVisible = false">取 消</el-button>
<el-button type="primary" @click="saveOrUpdate">确 定</el-button>
</div>
</el-dialog>
<!-- 添加和修改视频表单 -->
</div>
</template>
<script>
//导入js
import chapter from '@/api/movies/chapter'
export default {
data(){
return{
saveBtnDisbled: false,
courseId: '',//影片id
chapterVideoList: [],
chapter:{
sort: 0
},
dialogChapterFormVisible: false
}
},
created(){
//获取路由id
if(this.$route.params && this.$route.params.id){
//获取影片的id
this.courseId = this.$route.params.id
//根据影片的id获取片段
this.getChapterVideo()
}
console.log('id='+this.courseId)
},
methods:{
prevous(){//上一步:更新影片信息
this.$router.push({path:'/edu-movies/info/'+this.courseId})
},
//根据影片的id获取片段
getChapterVideo(){
chapter.getAllChapterVideo(this.courseId).then((result) => {
this.chapterVideoList = result.data.allChapterVideo
}).catch((err) => {
});
},
openChapterDialog(){//弹出窗体
this.dialogChapterFormVisible = true
},
openVideo(){},
openEditChapter(){},
removeChapter(){},
removeVideo(){},
saveOrUpdate(){//保存或更新
//判断
if(this.chapter.id){
this.updateChapter()
}else{
this.addChapter()
}
},
//添加片段
addChapter(){
//影片的id为外键
this.chapter.moviesId = this.courseId
chapter.addChapter(this.chapter).then(res=>{
//关闭弹出窗体
this.dialogChapterFormVisible =false
//提示
this.$message({
type: 'success',
message: '片段保存成功'
})
})
//刷新页面
this.getChapterVideo()
},
//更新片段
updateChapter(){
chapter.updateChapter(this.chapter).then(res=>{
//关闭弹出窗体
this.dialogChapterFormVisible =false
//提示
this.$message({
type: 'success',
message: '片段更新成功'
})
})
//刷新页面
this.getChapterVideo()
},
next(){}
}
}
</script>
<style>
</style>
7.5 阿里云的[视频点播]
- 注意:数据库中存储视频的id,不能存储地址,因为视频地址加密后就不能播放了。
7.5.1 编写后端
- 创建一个微服务子模块:xiudun_service/service_video
- pom依赖
<?xml version="1.0" encoding="UTF-8"?>
<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>xiudun_service</artifactId>
<groupId>com.xiudun</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>service_video</artifactId>
<dependencies>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!-- 阿里云上传的依赖-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-sdk-vod-upload</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-vod</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<configuration>
<classpathScope>test</classpathScope>
</configuration>
</plugin>
</plugins>
</build>
</project>
- 复制:aliyun-java-vod-upload-1.4.11.jar到项目中
- 编写配置文件application.properties
server.port=8085
#服务名称
spring.application.name=service-video
#开发
spring.profiles.active=dev
#oss的网址、id、秘钥
aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com
aliyun.oss.file.keyid=LTAI4GEJWzPRvp1mSdaJ
aliyun.oss.file.keysecret=TtBQk0jzh7nABMGwlGtsG
#buket名称
aliyun.oss.file.bucketname=xiudun
#最大上传大小
spring.servlet.multipart.max-file-size=1024MB
spring.servlet.multipart.max-request-size=1024MB
#nacos地址
spring.cloud.nacos.discovery.server-addr=localhost:8848
**特别注意:因为aliyun-java-vod-upload-1.4.11.jar暂时没有开源,所以,需要1.添加到项目中 2.需要maven编译后引入项目中
mvn install:install-file -DgroupId=com.aliyun -DartifactId=aliyun-sdk-vod-upload -Dversion=1.4.11 -Dpackaging=jar -Dfile=aliyun-java-vod-upload-1.4.11.jar
7.5.1.1 编写一个测试
- 编写一个初始化阿里云的类:获取客户端对象
package com.xiudun;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
public class InitObject {
public static DefaultAcsClient initCodClient(String accessKeyId,String accessKeySecret){
//客户端
DefaultAcsClient client = null;
try {
String regionId = "cn-shanghai";
DefaultProfile profile = DefaultProfile.getProfile(regionId,accessKeyId,accessKeySecret);
client = new DefaultAcsClient(profile);
}catch (Exception e){
e.printStackTrace();
}
return client;
}
}
- 测试
package com.xiudun;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadVideoRequest;
import com.aliyun.vod.upload.resp.UploadVideoResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import java.util.List;
//测试代码
public class TestVod {
//阿里云的id
static String id ="LTAI4GEJWzPRvp1mSXQ9hdaJ";
//阿里云秘钥
static String key ="TtBQk0jzh7nAB7kkhGQ3cJMGwlGtsG";
//阿里云的视频id
static String videoId = "a9842a69471743bda507734e238f8655";
//根据视频id获取播放凭证
public static void getPlayAuth(){
try {
//获取客户端
DefaultAcsClient client = InitObject.initCodClient(id, key);
//创建请求和相应对象
GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
//把视频的id添加到请求对象中
request.setVideoId(videoId);
response = client.getAcsResponse(request);
System.out.println("PlayAuth="+response.getPlayAuth());
}catch (Exception e){
e.printStackTrace();
}
}
//根据id获取视频的播放地址
public static void getPlayUrl(){
try {
//获取客户端
DefaultAcsClient client = InitObject.initCodClient(id, key);
//创建请求和相应对象
GetPlayInfoRequest request = new GetPlayInfoRequest();
GetPlayInfoResponse response = new GetPlayInfoResponse();
//把视频的id添加到请求对象中
request.setVideoId(videoId);
response = client.getAcsResponse(request);
List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
//获取视频的播放地址
for (GetPlayInfoResponse.PlayInfo playInfo : playInfoList) {
System.out.println("url="+playInfo.getPlayURL()+"\n");
}
//获取基本信息
System.out.println("title="+response.getVideoBase().getTitle()+"\n");
}catch (Exception e){
e.printStackTrace();
}
}
//视频上传
public static void uploadVideo(){
//视频上传后的名称
String title = "zmx";
//上传视频的地址
String fileName = "d:/xiudun/123.mp4";
//上传
UploadVideoRequest request = new UploadVideoRequest(id, key, title, fileName);
//如果视频大可以分片上传
request.setPartSize(2*1024*1024L);//2MB
//指定并发线程数
request.setTaskNum(1);
UploadVideoImpl uploadVideo = new UploadVideoImpl();
UploadVideoResponse response = uploadVideo.uploadVideo(request);
//判断
if (response.isSuccess()) {
System.out.println("videoId="+response.getVideoId());
}else{
//返回错误码和错误信息
System.out.println("errorCode="+response.getCode()+response.getMessage());
}
}
public static void main(String[] args) {
uploadVideo();
}
}
7.5.1.2 主配置类
package com.xiudun;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableDiscoveryClient
@EnableSwagger2
public class VideoApp {
public static void main(String[] args) {
SpringApplication.run(VideoApp.class,args);
}
}
7.5.1.3 编写工具类
package com.xiudun.util;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
public class InitObject {
public static DefaultAcsClient initCodClient(String accessKeyId,String accessKeySecret){
//客户端
DefaultAcsClient client = null;
try {
String regionId = "cn-shanghai";
DefaultProfile profile = DefaultProfile.getProfile(regionId,accessKeyId,accessKeySecret);
client = new DefaultAcsClient(profile);
}catch (Exception e){
e.printStackTrace();
}
return client;
}
}
- 工具:读取properties文件
package com.xiudun.util;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ConstantPropertiesUtils implements InitializingBean {
//读取配置文件中的信息
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.keyid}")
private String keyId;
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;
//定义常量
public static String END_POINT;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
@Override //读取属性文件后设置
public void afterPropertiesSet() throws Exception {
END_POINT = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = bucketName;
}
}
7.5.1.4 编写业务service
package com.xiudun.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xiudun.entity.EduVideo;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* <p>
* 影视视频 服务类
* </p>
*
* @author xiudun
* @since 2021-03-01
*/
public interface EduVideoService extends IService<EduVideo> {
//视频上传到阿里云:视频点播
String uploadVideoAly(MultipartFile file);
//删除阿里云中的视频文件
void removeMoreAlyVideo(List videoList);
//按照id删除视频文件
public void deleteById(String videoId)
}
- 实现类
package com.xiudun.service;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiudun.entity.EduVideo;
import com.xiudun.exceptionhandler.XiudunException;
import com.xiudun.mapper.EduVideoMapper;
import com.xiudun.util.ConstantPropertiesUtils;
import com.xiudun.util.InitObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.List;
/**
* <p>
* 影视视频 服务实现类
* </p>
*
* @author xiudun
* @since 2021-03-01
*/
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {
@Override//视频上传
public String uploadVideoAly(MultipartFile file) {
//获取视频名称
String filename = file.getOriginalFilename();
//视频上传后的名称
String title = filename.substring(0, filename.lastIndexOf("."));
//上传后的视频id
String videoId = null;
//完成上传
try {
//获取输入流
InputStream inputStream = file.getInputStream();
//阿里云请求对象
UploadStreamRequest request = new UploadStreamRequest(ConstantPropertiesUtils.ACCESS_KEY_ID,
ConstantPropertiesUtils.ACCESS_KEY_SECRET, title, filename, inputStream);
//阿里云响应对象
UploadVideoImpl uploadVideo = new UploadVideoImpl();
UploadStreamResponse response = uploadVideo.uploadStream(request);
//判断上传是否成功
if (response.isSuccess()) {
videoId = response.getVideoId();
}else{
videoId = response.getVideoId();
}
}catch (Exception e){
e.printStackTrace();
}
return videoId;
}
@Override
public void removeMoreAlyVideo(List videoList) {
//获取阿里云对象客户端
DefaultAcsClient client = InitObject.initCodClient(ConstantPropertiesUtils.ACCESS_KEY_ID,
ConstantPropertiesUtils.ACCESS_KEY_SECRET);
//创建阿里云请求对象
DeleteVideoRequest request = new DeleteVideoRequest();
//按照视频的id删除,需要把数据转为指定格式:1,2,3
String videoIds = StringUtils.join(videoList.toArray(), ",");
//向请求删除对象添加
request.setVideoIds(videoIds);
//删除
try {
client.getAcsResponse(request);
} catch (ClientException e) {
e.printStackTrace();
throw new XiudunException(20001,"视频删除失败");
}
}
@Override
public void deleteById(String videoId) {
//获取阿里云对象客户端
DefaultAcsClient client = InitObject.initCodClient(ConstantPropertiesUtils.ACCESS_KEY_ID,
ConstantPropertiesUtils.ACCESS_KEY_SECRET);
//创建阿里云请求对象
DeleteVideoRequest request = new DeleteVideoRequest();
//向请求删除对象添加
request.setVideoIds(videoId);
//删除
try {
client.getAcsResponse(request);
} catch (ClientException e) {
e.printStackTrace();
throw new XiudunException(20001,"视频删除失败");
}
}
}
7.5.1.5 控制层controller
package com.xiudun.controller;
import com.xiudun.exceptionhandler.XiudunException;
import com.xiudun.service.EduVideoService;
import com.xiudun.util.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* <p>
* 影视视频 前端控制器
* </p>
*
* @author xiudun
* @since 2021-03-01
*/
@RestController
@RequestMapping("/edu-video")
public class EduVideoController {
@Autowired
private EduVideoService videoService;
@ApiOperation("视频上传")
@PostMapping("uploadAlyVideo")
public R uploadAlyVideo(MultipartFile file){
//视频id
String id = videoService.uploadVideoAly(file);
return R.ok().data("videoId", id);
}
@ApiOperation("根据id删除视频")
@DeleteMapping("deleteVideo/{id}")
public R deleteVideo(@PathVariable String id){
videoService.deleteById(id);
return R.ok();
}
@ApiOperation("批量删除视频")
@DeleteMapping("deleteBatchVideo")
public R deleteBatchVideo(@RequestParam("videoList")List<String> videoList){
videoService.removeMoreAlyVideo(videoList);
return R.ok();
}
}
- 配置网关
7.5.2 编写前端实现
- 影片显示列表页
<template>
<div class="app-container">
<!-- 影片查询 -->
<el-form :inline="true" class="demo-form-inline">
<el-form-item>
<el-input v-model="moviesQuery.title" placeholder="影片名称"></el-input>
</el-form-item>
<el-form-item>
<el-select v-model="moviesQuery.status" placeholder="影片状态">
<el-option label="已发布" value="Normal"></el-option>
<el-option label="未发布" value="Draft"></el-option>
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="getList()">查 询</el-button>
<el-button type="default" @click="resetData()">清 空</el-button>
</el-form-item>
</el-form>
<!-- 影片列表 -->
<el-table :data="list" style="width: 100%">
<el-table-column label="序号" width="180">
<template slot-scope="scope">
{{ (current-1)*limit+scope.$index+1 }}
</template>
</el-table-column>
<el-table-column prop="title" label="影片名称" width="180"/>
<el-table-column label="影片状态">
<template slot-scope="scope">
{{ scope.row.status==='Normal'?'已发布':'未发布'}}
</template>
</el-table-column>
<el-table-column prop="videoNum" label="视频数" width="180"/>
<el-table-column prop="gmtCreate" label="影片添加时间" width="180"/>
<el-table-column prop="viewCount" label="浏览量" width="180"/>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="mini">编辑影片基本信息</el-button>
<el-button size="mini">编辑影片片段信息</el-button>
<el-button size="mini" type="danger" @click="removeDataById(scope.row.id)">删除影片</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页插件 -->
<el-pagination
@current-change="getList"
:current-page.sync="current"
:page-size="limit"
layout="prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
moviesQuery: {},
list: [],
current: 1,
limit: 3,
total: 0
};
},
created() {},
methods: {
getlist() {
//查询
},
resetData() {
//清空查询条件
this.moviesQuery = {};
},
removeDataById(){//删除影片
}
},
};
</script>
<style>
</style>
7.5.3 完善影片信息的功能
- 创建一个查询的vo:MoviesQuery.java
package com.xiudun.vo;
import lombok.Data;
//查询影片使用的
@Data
public class MoviesQuery {
private String title;
private String status;
}
- 完善控制层:EduMoviesController.java
package com.xiudun.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiudun.entity.EduMovies;
import com.xiudun.service.EduMoviesService;
import com.xiudun.util.R;
import com.xiudun.vo.CourseInfoVo;
import com.xiudun.vo.CoursePublishVo;
import com.xiudun.vo.MoviesQuery;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 影视 前端控制器
* </p>
*
* @author xiudun
* @since 2021-03-01
*/
@RestController
@RequestMapping("/edu-movies")
public class EduMoviesController {
//依赖
@Autowired
private EduMoviesService moviesService;
//------------------------完善--------------------------------------------------
@ApiOperation("影片信息分页")
@PostMapping("getMoviesList/{current}/{limit}")
public R getMoviesList(@PathVariable long current, @PathVariable long limit,
@RequestBody(required = false) MoviesQuery moviesQuery){
//分页
Page<EduMovies> moviesPage = new Page<>(current,limit);
//查询条件
QueryWrapper<EduMovies> wrapper = new QueryWrapper<>();
if (moviesQuery.getTitle()!=null) {
wrapper.like("title",moviesQuery.getTitle());
}
if (moviesQuery.getStatus()!=null) {
wrapper.like("status",moviesQuery.getStatus());
}
//添加查询条件
moviesService.page(moviesPage,wrapper);
//记录数
long total = moviesPage.getTotal();
//分页数据
List<EduMovies> list = moviesPage.getRecords();
return R.ok().data("total", total).data("list", list);
}
@ApiOperation("根据id删除影片")
@DeleteMapping("deleteMovies/{id}")
public R deleteMovies(@PathVariable String id){
moviesService.removeById(id);
return R.ok();
}
//-----------------------------------------------------------------------------
@ApiOperation("添加影片基本信息")
@PostMapping("addMoviesInfo")//只要post对@RequestBody有效
public R addMoviesInfo(@RequestBody CourseInfoVo courseInfoVo){
System.out.println("---------------->>"+courseInfoVo);
//添加后返回影片id
String id = moviesService.saveCourseInfo(courseInfoVo);
return R.ok().data("moviesId", id);
}
@ApiOperation("根据影片id获取基本信息")
@GetMapping("getMoviesInfo/{moviesId}")
public R getMoviesInfo(@PathVariable String moviesId){
CourseInfoVo courseInfo = moviesService.getCourseInfo(moviesId);
return R.ok().data("courseInfoVo", courseInfo);
}
@ApiOperation("更新影片信息")
@PutMapping("updateMoviesInfo")
public R updateMoviesInfo(@RequestBody CourseInfoVo courseInfoVo){
moviesService.updateCourseInfo(courseInfoVo);
return R.ok();
}
@ApiOperation("根据影片id获取发布影片信息")
@GetMapping("getPublishMoviesInfo/{id}")
public R getPublishMoviesInfo(@PathVariable("id") String id){
CoursePublishVo publishVo = moviesService.puslishCourseInfo(id);
return R.ok().data("publishVo", publishVo);
}
}
7.5.4 编写前端,影片列表
<template>
<div class="app-container">
<!-- 影片查询 -->
<el-form :inline="true" class="demo-form-inline">
<el-form-item>
<el-input v-model="moviesQuery.title" placeholder="影片名称"></el-input>
</el-form-item>
<el-form-item>
<el-select v-model="moviesQuery.status" placeholder="影片状态">
<el-option label="已发布" value="Normal"></el-option>
<el-option label="未发布" value="Draft"></el-option>
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="getList()">查 询</el-button>
<el-button type="default" @click="resetData()">清 空</el-button>
</el-form-item>
</el-form>
<!-- 影片列表 -->
<el-table :data="list" style="width: 100%">
<el-table-column label="序号" width="180">
<template slot-scope="scope">
{{ (current-1)*limit+scope.$index+1 }}
</template>
</el-table-column>
<el-table-column prop="title" label="影片名称" width="180"/>
<el-table-column label="影片状态">
<template slot-scope="scope">
{{ scope.row.status==='Normal'?'已发布':'未发布'}}
</template>
</el-table-column>
<el-table-column prop="videoNum" label="视频数" width="180"/>
<el-table-column prop="gmtCreate" label="影片添加时间" width="180"/>
<el-table-column prop="viewCount" label="浏览量" width="180"/>
<el-table-column label="操作" align="center" width="200">
<template slot-scope="scope">
<router-link :to="'/edu-movies/info/'+scope.row.id" >
<el-button size="mini" type="primary">编辑影片基本信息</el-button>
</router-link>
<router-link :to="'/edu-movies/chapter/'+scope.row.id" >
<el-button size="mini" type="primary">编辑影片片段信息</el-button>
</router-link>
<el-button size="mini" type="danger" @click="removeDataById(scope.row.id)">删除影片</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页插件 -->
<el-pagination
@current-change="pageChange"
:current-page.sync="current"
:page-size="limit"
layout="prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
</template>
<script>
//导入js
import movies from '@/api/movies/movies'
export default {
data() {
return {
moviesQuery: {},
list: [],
current: 1,
limit: 3,
total: 0
};
},
created() {
this.getlist()
},
methods: {
getlist(page=1) {
//查询
this.current = page
movies.getListMovies(this.moviesQuery,this.current,this.limit).then((result) => {
this.list = result.data.list
this.total = result.data.total
}).catch((err) => {
});
},
pageChange(page){
this.current = page
movies.getListMovies(this.moviesQuery,this.current,this.limit).then((result) => {
this.list = result.data.list
this.total = result.data.total
}).catch((err) => {
});
},
resetData() {
//清空查询条件
this.moviesQuery = {};
},
removeDataById(id){//删除影片
this.$confirm('是否删除','提示',{
confirmButtonText:'确定',
cancelButtonText:'取消',
type:'warning'
}).then(res=>{
movies.deleteMovies(id).then(res=>{
this.$message({
type: 'success',
message: '删除成功'
})
//显示数据
this.getlist()
})
})
}
},
};
</script>
<style>
</style>
7.5.5 视频上传
- 在video后端添加更新和保存描述方法
@RestController
@RequestMapping("/edu-video")
public class EduVideoController {
@ApiOperation("保存视频描述信息")
@PostMapping("addVideo")
public R addVideo(@RequestBody EduVideo eduVideo){
videoService.save(eduVideo);
return R.ok();
}
@ApiOperation("更新视频描述信息")
@PutMapping("updateVideo")
public R updateVideo(@RequestBody EduVideo eduVideo){
videoService.updateById(eduVideo);
return R.ok();
}
}
- chapter.vue页面
<template>
<div class="app-container">
<h2 style="text-align:center">发布新影片</h2>
<!-- 步骤条 -->
<el-steps :active="2" process-status="wait" align-center>
<el-step title="填写影片基本信息"></el-step>
<el-step title="创建影片视频章节"></el-step>
<el-step title="发布影片"></el-step>
</el-steps>
<el-button type="text" @click="openChapterDialog()">添加片段</el-button>
<!-- 影片片段 -->
<ul class="chanpterList">
<li
v-for="chapter in chapterVideoList"
:key="chapter.id">
<p>
{{chapter.title}}
<span class="acts">
<el-button type="text" @click="openVideo(chapter.id,video.id)">添加视频</el-button>
<el-button type="text" @click="openEditChapter(chapter.id)">编辑片段</el-button>
<el-button type="text" @click="removeChapter(chapter.id)">删除片段</el-button>
</span>
</p>
<!-- 视频 -->
<ul class="chanpterList videoList">
<li
v-for="video in chapter.children"
:key="video.id">
<p>
{{video.title}}
<span class="acts">
<el-button type="text" @click="openVideo(chapter.id,video.id)">编辑</el-button>
<el-button type="text" @click="removeVideo(video.id)">删除</el-button>
</span>
</p>
</li>
</ul>
</li>
</ul>
<div>
<el-button @click="prevous">上一步</el-button>
<el-button :disabled="saveBtnDisbled" type="primary" @click="next">下一步</el-button>
</div>
<!-- 弹出窗体:添加或修改片段 -->
<el-dialog title="添加影片片段" :visible.sync="dialogChapterFormVisible">
<el-form :model="chapter">
<el-form-item label="片段名称" >
<el-input v-model="chapter.title" />
</el-form-item>
<el-form-item label="片段排序" >
<el-input-number v-model="chapter.sort" :min="0" controls-position="right"/>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogChapterFormVisible = false">取 消</el-button>
<el-button type="primary" @click="saveOrUpdate">确 定</el-button>
</div>
</el-dialog>
<!-- 添加和修改视频表单 -->
<el-dialog title="添加视频" :visible.sync="dialogVideoFormVisible">
<el-form :model="video" label-width="120">
<el-form-item label="视频题目">
<el-input v-model="video.title"/>
</el-form-item>
<el-form-item label="视频排序">
<el-input-number v-model="video.sort" :min="0"/>
</el-form-item>
<el-form-item label="是否免费">
<el-radio-group v-model="video.isFree">
<el-radio :label="true" >免费</el-radio>
<el-radio :label="false">默认</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="上传视频">
<el-upload
:on-success="handleVodUploadSuccess"
class="upload-demo"
:action="BASE_API+'edu-video/uploadAlyVideo'"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
:limit="1"
:on-exceed="handleExceed"
:file-list="fileList">
<el-button size="small" type="primary">上传视频</el-button>
<div slot="tip" class="el-upload__tip">最大支持1G</div>
</el-upload>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogVideoFormVisible=false">取 消</el-button>
<el-button :disabled="saveVideoBtnDisabled=false" type="primary" @click="saveOrUpdateVideo">确 定</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
//导入js
import chapter from '@/api/movies/chapter'
import video from '@/api/movies/video'
export default {
data(){
return{
saveBtnDisbled: false,
courseId: '',//影片id
chapterVideoList: [],
chapter:{
sort: 0
},
dialogChapterFormVisible: false,
dialogVideoFormVisible: false,
video: {
sort: 0,
isFree: true
},
fileList: [],
saveVideoBtnDisabled: false,
BASE_API: process.env.BASE_API,
vsid:''
}
},
created(){
//获取路由id
if(this.$route.params && this.$route.params.id){
//获取影片的id
this.courseId = this.$route.params.id
//根据影片的id获取片段
this.getChapterVideo()
}
console.log('id='+this.courseId)
},
methods:{
handleVodUploadSuccess(respones,file,fileList){//视频上传成功
//获取上传的id
this.video.videoSourceId = respones.data.videoId
//视频名称
this.video.VideoOriginalName = file.name
this.size = file.length
},
handlePreview(){},
handleRemove(){//删除视频
video.deleteAlyVod(this.video.videoSourceId).then(res=>{
//提示
this.$message({
type: 'success',
message: '删除成功'
})
//视频的列表清空
this.fileList = []
this.video.videoSourceId = ''
this.video.VideoOriginalName = ''
})
},
beforeRemove(){//删除视频前
return this.$confirm(`确定删除${file.name}?`)
},
handleExceed(){
this.$message.warning('请删除已经上传的视频后,再重新上传');
},
//-------------------------------------------------------------
saveOrUpdateVideo(){//保存视频的描述信息
if(this.video.id){
this.updateByVideo()
}else{
this.addVideo()
}
},
//保存视频描述
addVideo(){
//关联id
this.video.moviesId = this.courseId
video.addVideo(this.video).then(res=>{
this.dialogVideoFormVisible = false
this.$message({
type: 'success',
message: '保存成功'
})
this.getChapterVideo()
})
},
//更新视频描述
updateByVideo(){
video.updateVideo(this.video).then(res=>{
this.dialogVideoFormVisible = false
this.$message({
type: 'success',
message: '保存成功'
})
this.getChapterVideo()
})
},
//------------------------------------------------------------
prevous(){//上一步:更新影片信息
this.$router.push({path:'/edu-movies/info/'+this.courseId})
},
//根据影片的id获取片段
getChapterVideo(){
chapter.getAllChapterVideo(this.courseId).then((result) => {
this.chapterVideoList = result.data.allChapterVideo
}).catch((err) => {
});
},
openChapterDialog(){//弹出窗体
this.dialogChapterFormVisible = true
},
openVideo(chapterId,videoId){//添加片段
if(chapterId){//添加
this.dialogVideoFormVisible = true
this.video = {}
this.fileList = []
this.video.chapterId = chapterId
}
if(chapterId && videoId){//更新
video.updateVideo(videoId).then(res=>{
})
}
},
openEditChapter(chapterId){//编辑片段
//弹出窗体
this.dialogChapterFormVisible = true
//回填数据
chapter.getChapter(chapterId).then(res=>{
this.chapter = res.data.chapter
})
},
removeChapter(chapterId){//删除片段
this.$confirm('删除片段信息?','提示',{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(res=>{
chapter.deleteChapter(chapterId).then(res=>{
this.$message({
type: 'success',
message: '删除成功'
})
this.getChapterVideo()
})
})
},
removeVideo(videoId,videoSourceId){//删除视频
video.videoById(videoId).then(res=>{
this.vsid = res.data.vsid
})
this.$confirm('删除片段信息?','提示',{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(res=>{
//删除视频
video.deleteAlyVod(this.vsid).then(res=>{
this.$message({
type: 'success',
message: '删除成功'
})
})
//删除视频描述
video.deleteVideo(videoId).then(res=>{
this.$message({
type: 'success',
message: '删除成功'
})
this.getChapterVideo()
})
})
},
saveOrUpdate(){//保存或更新
//判断
if(this.chapter.id){
this.updateChapter()
}else{
this.addChapter()
}
},
//添加片段
addChapter(){
//影片的id为外键
this.chapter.moviesId = this.courseId
chapter.addChapter(this.chapter).then(res=>{
//关闭弹出窗体
this.dialogChapterFormVisible =false
//提示
this.$message({
type: 'success',
message: '片段保存成功'
})
//根据影片的id获取片段
this.getChapterVideo()
})
},
//更新片段
updateChapter(){
chapter.updateChapter(this.chapter).then(res=>{
//关闭弹出窗体
this.dialogChapterFormVisible =false
//提示
this.$message({
type: 'success',
message: '片段更新成功'
})
//刷新页面
this.getChapterVideo()
})
},
next(){}
}
}
</script>
<style>
</style>
7.6 影片发布
7.6.1 编写后端
@ApiOperation("发布影片,修改status的状态")
@PostMapping("publisMovies/{moviesId}")
public R publisMovies(@PathVariable String moviesId){
EduMovies eduMovies = new EduMovies();
eduMovies.setId(moviesId);
eduMovies.setStatus("Normal");
moviesService.updateById(eduMovies);
return R.ok();
}
- 影片发布涉及的sql查询语句
public interface EduMoviesMapper extends BaseMapper<EduMovies> {
//发布的影片
String sql = "SELECT ec.id,ec.title,ec.price,ec.video_num AS videoNum,ec.cover,\n" +
" et.name AS actorName,\n" +
" es1.title AS subjectLevelOne,\n" +
" es2.title AS subjectLevelTwo\n" +
" FROM edu_movies ec LEFT OUTER JOIN edu_movies_description ecd ON ec.id=ecd.id\n" +
" LEFT OUTER JOIN edu_actor et ON ec.actor_id=et.id\n" +
" LEFT OUTER JOIN edu_subject es1 ON ec.subject_parent_id=es1.id\n" +
" LEFT OUTER JOIN edu_subject es2 ON ec.subject_id=es2.id\n" +
" WHERE ec.id=#{courseId}";
@Select(sql)
CoursePublishVo getPulishCourseInfo(String courseId);
}
7.6.2 编写前端影片发布
- 编写api/movies.js文件
import request from '@/utils/request'
export default {
//添加影片信息
addMoviesInfo(moviesInfo){
return request({
url: `/edu-movies/addMoviesInfo`,
method: 'post',
data: moviesInfo
})
},
//影片id获取信息
getMoviesInfoId(id){
return request({
url: `/edu-movies/getMoviesInfo/${id}`,
method: 'get'
})
},
//更新影片信息
updateMovies(moviesInfo){
return request({
url: `/edu-movies/updateMoviesInfo`,
method: 'put',
data: moviesInfo
})
},
//分页显示
getListMovies(moviesQuery,current,limit){
return request({
url: `/edu-movies/getMoviesList/${current}/${limit}`,
method: 'post',
data: moviesQuery
})
},
//删除影片信息
deleteMovies(id){
return request({
url: `/edu-movies/deleteMovies/${id}`,
method: 'delete'
})
},
//发布影片
publisMovies(id){
return request({
url: `/edu-movies/publisMovies/${id}`,
method: 'post'
})
},
//获取发布影片的列表信息
getPublishMoviesInfo(id){
return request({
url: `/edu-movies/getPublishMoviesInfo/${id}`,
method: 'get'
})
}
}
- 发布信息的publish.vue
<template>
<div class="app-container">
<h2 style="text-align:center">发布新影片</h2>
<!-- 步骤条 -->
<el-steps :active="3" process-status="wait" align-center>
<el-step title="填写影片基本信息"></el-step>
<el-step title="创建影片视频章节"></el-step>
<el-step title="发布影片"></el-step>
</el-steps>
<div class="ccinfo">
<img :src="coursePublish.cover">
<div class="main">
<h2>{{coursePublish.title}}</h2>
<p class="gray"><span>共{{coursePublish.videoNum}}视频数</span> </p>
<p><span>所属分类{{coursePublish.subjectLevelOne}}-{{coursePublish.subjectLevelTwo}}</span></p>
<p>主演:{{coursePublish.actorName}}</p>
<h3 class="red">¥{{coursePublish.price}}</h3>
</div>
</div>
<el-button @click="previous">返 回</el-button>
<el-button @click="publish" :disabled="saveBtnDisbled" type="primary">发布影片</el-button>
</div>
</template>
<script>
//导入js
import movies from '@/api/movies/movies'
export default {
data(){
return{
coursePublish: {},
saveBtnDisbled: false,
courseId: ''
}
},
created(){
//获取路由的id值
if(this.$route.params && this.$route.params.id){
this.courseId = this.$route.params.id
//调用函数
this.getMoviesPublistId()
}
},
methods:{
getMoviesPublistId(){
movies.getPublishMoviesInfo(this.courseId).then((result) => {
this.coursePublish = result.data.publishVo
}).catch((err) => {
console.log('error')
});
},
previous(){//返回上一级
this.$router.push({path:'/edu-movies/info/'+this.courseId})
},
publish(){//发布影片
movies.publisMovies(this.courseId).then(res=>{
//提示
this.$message({
type: 'success',
message: '发布成功'
})
//跳转到影片列表页面
this.$router.push({path:'/edu-movies/list'})
})
}
}
}
</script>
<style scoped>
.ccInfo {
background: #f5f5f5;
padding: 20px;
overflow: hidden;
border: 1px dashed #DDD;
margin-bottom: 40px;
position: relative;
}
.ccInfo img {
background: #d6d6d6;
width: 500px;
height: 278px;
display: block;
float: left;
border: none;
}
.ccInfo .main {
margin-left: 520px;
}
.ccInfo .main h2 {
font-size: 28px;
margin-bottom: 30px;
line-height: 1;
font-weight: normal;
}
.ccInfo .main p {
margin-bottom: 10px;
word-wrap: break-word;
line-height: 24px;
max-height: 48px;
overflow: hidden;
}
.ccInfo .main p {
margin-bottom: 10px;
word-wrap: break-word;
line-height: 24px;
max-height: 48px;
overflow: hidden;
}
.ccInfo .main h3 {
left: 540px;
bottom: 20px;
line-height: 1;
font-size: 28px;
color: #d32f24;
font-weight: normal;
position: absolute;
}
</style>
第八章:播放视频
8.1 添加视频列表
- src/router/index.js添加播放列表
8.2 编写播放列表vue
<template>
<div class="app-container">
<!-- 视频播放列表 -->
<el-form :inline="true" class="demo-form-inline">
<el-form-item>
<el-input v-model="moviesQuery.title" placeholder="影片名称" />
</el-form-item>
<el-button type="primary" @click="getList()">查 询</el-button>
<el-button type="default" @click="resetData()">清 空</el-button>
</el-form>
<!-- 表格 -->
<el-table :data="list" style="width: 100%">
<el-table-column label="序号">
<template slot-scope="scope">
{{scope.$index+1}}
</template>
</el-table-column>
<el-table-column label="影片名称" prop="title"> </el-table-column>
<el-table-column label="视频数量" prop="videoNum"> </el-table-column>
<el-table-column label="添加时间" prop="gmtCreate"> </el-table-column>
<el-table-column label="浏览数量" prop="viewCount"> </el-table-column>
<el-table-column align="right" label="操作" header-align="left">
<template slot-scope="scope">
<router-link :to="'/movies/chapterVideo/'+scope.row.id">
<el-button size="mini" type="primary">播放视频</el-button>
</router-link>
</template>
</el-table-column>
</el-table>
<!-- 分页插件 -->
<el-pagination
:current-page="current"
:page-size="limit"
:total="total"
layout="total, prev, pager, next, jumper"
@current-change="getList"/>
</div>
</template>
<script>
//导入js
import movies from '@/api/movies/movies'
export default {
data() {
return {
moviesQuery: {},
list: null,
current:1,
limit:3,
total:0
};
},
created() {
this.getList()
},
methods: {
getList(page=1) {//影片列表
this.current = page
movies.getListMovies(this.moviesQuery,this.current,this.limit).then((result) => {
this.list = result.data.list
this.total = result.data.total
}).catch((err) => {
console.log(err)
});
},
resetData() {
this.moviesQuery = {};
}
},
};
</script>
<style>
</style>
8.4 视频播放后端编写
- 创建一个页面html
package com.xiudun.controller;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.xiudun.entity.EduVideo;
import com.xiudun.exceptionhandler.XiudunException;
import com.xiudun.service.EduVideoService;
import com.xiudun.util.InitObject;
import com.xiudun.util.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.ws.rs.PUT;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* 影视视频 前端控制器
* </p>
*
* @author xiudun
* @since 2021-03-01
*/
@RestController
@RequestMapping("/edu-video")
public class EduVideoController {
@Autowired
private EduVideoService videoService;
@ApiOperation("视频上传")
@PostMapping("uploadAlyVideo")
public R uploadAlyVideo(MultipartFile file){
//视频id
String id = videoService.uploadVideoAly(file);
return R.ok().data("videoId", id);
}
@ApiOperation("根据id删除视频")
@DeleteMapping("deleteVideo/{id}")
public R deleteVideo(@PathVariable String id){
videoService.deleteById(id);
return R.ok();
}
@ApiOperation("批量删除视频")
@DeleteMapping("deleteBatchVideo")
public R deleteBatchVideo(@RequestParam("videoList")List<String> videoList){
videoService.removeMoreAlyVideo(videoList);
return R.ok();
}
@ApiOperation("播放视频")
@RequestMapping("vo/{id}")
public ModelAndView playVideo(@PathVariable String id){
try {
//阿里云对象
DefaultAcsClient client = InitObject.initCodClient("LTAI4GEJWzPR9hdaJ",
"TtBQk0jzh7nAB3cJMGwlGtsG");
//创建请求和相应的对象
GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
//添加视频的id
request.setVideoId(id);
response = client.getAcsResponse(request);
//授权码
String playAuth = response.getPlayAuth();
//把视频的id和授权码传到网页中播放视频
Map<String,String> map = new HashMap<>();
map.put("videoId",id);
map.put("playAuth",playAuth);
return new ModelAndView("show", map);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
- html网页:show.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>视频播放</title>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://g.alicdn.com/de/prismplayer/2.8.1/skins/default/aliplayer-min.css" />
<script charset="utf-8" type="text/javascript" src="https://g.alicdn.com/de/prismplayer/2.8.1/aliplayer-min.js"></script>
</head>
</html>
</head>
<body>
<div class="prism-player" id="J_prismPlayer"></div>
<script th:inline="javascript">
var player = new Aliplayer({
id: 'J_prismPlayer',
width: '100%',
autoplay: false,
//视频的id
vid : [[${videoId}]],
playauth : [[${playAuth}]],
cover: 'http://liveroom-img.oss-cn-qingdao.aliyuncs.com/logo.png',
encryptType:1, //当播放私有加密流时需要设置。
},function(player){
console.log('播放器创建好了。')
});
</script>
</body>
</html>
8.5 编写视频播放列表vue:chapterVideo.vue
<template>
<div class="app-container">
<h2>播放影片</h2>
<ul>
<li
v-for="chapter in chapterVideoList"
:key="chapter.id">
<p>{{chapter.title}}</p>
<!-- 视频 -->
<ul>
<li
v-for="video in chapter.children"
:key="video.id">
<p>{{video.title}}</p>
<span class="acts">
<el-button @click="openVideo(video.id)" type="text">播放视频</el-button>
</span>
</li>
</ul>
</li>
</ul>
</div>
</template>
<script>
//导入脚本
import chapter from '@/api/movies/chapter'
import video from '@/api/movies/video'
export default {
data(){
return{
chapterVideoList:[],
courseId: '',
sourceVideoId: ''
}
},
created(){
if(this.$route.params && this.$route.params.id){
this. courseId = this.$route.params.id
//根据影片id 查询对应的片段
this.getChapterVideo()
}
},
methods:{
getChapterVideo(){//根据id获取章节片段
chapter.getAllChapterVideo(this.courseId).then((result) => {
this.chapterVideoList = result.data.allChapterVideo
}).catch((err) => {
console.log(err)
});
},
openVideo(id){//根据阿里云的视频id播放视频
video.videoById(id).then(res=>{
this.sourceVideoId = res.data.vsid
})
//启动一个新窗体播放
window.open('_blank').location.href="http://localhost:7000/edu-video/vo/"+this.sourceVideoId
}
}
}
</script>
<style>
</style>
第九章:Echarts图表
- 注意:数据需要集合List形式返回,因为,可以在图表中转为数组格式。
9.1 后端编写
- service
```java package com.xiudun.service;
import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.xiudun.entity.EduSubject; import com.baomidou.mybatisplus.extension.service.IService; import org.springframework.web.multipart.MultipartFile;
import java.util.List; import java.util.Map;
/**
- 影视科目 服务类
- *
- @author xiudun
@since 2021-02-28 */ public interface EduSubjectService extends IService
{ //上传excel void batchImport(MultipartFile file,EduSubjectService subjectService); //树形 List
listTree(); //根据创建的时间统计分析图表gmtCreate Map
getEcharts(String begin,String end);
}
- 实现类
```java
package com.xiudun.service.impl;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiudun.entity.EduSubject;
import com.xiudun.mapper.EduSubjectMapper;
import com.xiudun.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiudun.util.ExcelLisener;
import com.xiudun.vo.ReadData;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* <p>
* 影视科目 服务实现类
* </p>
*
* @author xiudun
* @since 2021-02-28
*/
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {
@Override
public void batchImport(MultipartFile file, EduSubjectService subjectService) {
try {
//文件输入流
InputStream inputStream = file.getInputStream();
//需要指定读取那个Class,读取默认sheet,文件流自动关闭
EasyExcel.read(inputStream, ReadData.class,new ExcelLisener(subjectService)).sheet().doRead();
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public List<EduSubject> listTree() {
//获取所有分类数据
List<EduSubject> entities = baseMapper.selectList(null);
//找到一级分类
return entities.stream().filter(categoryEntity->categoryEntity.getParentId().equals("0"))
.map(menu-> menu.setChildren(getChildrens(menu,entities)))
.sorted((m1,m2)->(m1.getSort()==null?0:m1.getSort())-(m2.getSort()==null?0:m2.getSort()))
.collect(Collectors.toList());
}
@Override
public Map<String, Object> getEcharts(String begin, String end) {
//创建集合
Map<String, Object> map = new HashMap<>();
//查询条件
QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
wrapper.eq("parent_id","0");
//数据
List<EduSubject> data = baseMapper.selectList(wrapper);
//把数据添加到list集合中
Stream<String> stringStream = data.stream().map(e -> e.getTitle());
List<String> collect = stringStream.collect(Collectors.toList());
//存储数值
List<Integer> nums = new ArrayList<>();
//根据data获取的影片数量
for (EduSubject datum : data) {
QueryWrapper<EduSubject> wrapper1 = new QueryWrapper<>();
wrapper1.eq("parent_id",datum.getId());
wrapper1.between("gmt_create",begin,end);
List<EduSubject> list = baseMapper.selectList(wrapper1);
nums.add(list.size());
}
//把两个集合添加到map中
map.put("data",collect);
map.put("nums",nums);
return map;
}
//编写一个读取树形的递归方法
private List<EduSubject> getChildrens(EduSubject root,List<EduSubject> all){
//递归查找
List<EduSubject> list = all.stream().filter(categoryEntity -> {
return categoryEntity.getParentId().equals(root.getId());//找子节点
}).map(categoryEntity -> {//子节点
categoryEntity.setChildren(getChildrens(categoryEntity, all));
return categoryEntity;
}).sorted((m1, m2) -> {
return (m1.getSort() == null ? 0 : m1.getSort()) - (m2.getSort() == null ? 0 : m2.getSort());
}).collect(Collectors.toList());
//返回子节点集合
return list;
}
}
- 控制层:controller
package com.xiudun.controller;
import com.xiudun.service.EduSubjectService;
import com.xiudun.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.Map;
/**
* <p>
* 影视科目 前端控制器
* </p>
*
* @author xiudun
* @since 2021-02-28
*/
@Api("影片分类管理")
@RestController
@RequestMapping("/edu-subject")
public class EduSubjectController {
//注入业务
@Autowired
private EduSubjectService subjectService;
@ApiOperation("excel批量导入数据")
@PostMapping("addSubject")
public R addSubject(MultipartFile file){
//上传文件
subjectService.batchImport(file,subjectService);
return R.ok();
}
@ApiOperation("分类数据Tree")
@GetMapping("getListTree")
public R listTree(){
return R.ok().data("items", subjectService.listTree());
}
@ApiOperation("Echarts图表")
@GetMapping("echarts/{begin}/{end}")
public R echarts(@PathVariable String begin,@PathVariable String end){
Map<String, Object> map = subjectService.getEcharts(begin, end);
return R.ok().data(map);
}
}
9.2 前端编写
- 需要安装Echarts
- 创建show.vue
<template>
<div class="app-container">
<!-- 表单 -->
<el-form :inline="true" class="demo-form-inline">
<el-select v-model="searchObj.type" placeholder="请选择">
<el-option label="影片分类" value="subject_num" />
<el-option label="演员统计" value="actor_num" />
</el-select>
<!-- 日历控件 -->
<el-form-item>
<el-date-picker
v-model="searchObj.begin"
type="date"
value-format="yyyy-MM-dd"
placeholder="开始日期"/>
</el-form-item>
<el-form-item>
<el-date-picker
v-model="searchObj.end"
type="date"
value-format="yyyy-MM-dd"
placeholder="结束日期"/>
</el-form-item>
<el-button type="primary" :disabled="btnDisabled" @click="showChart()">查 询</el-button>
</el-form>
<!-- 图表需要渲染的地方 -->
<div class="chart-container">
<div id="chart" class="chart" style="height:500px;width:100%"></div>
</div>
</div>
</template>
<script>
import echarts from 'echarts'
export default {
data(){
return{
searchObj:{},
btnDisabled: false,
begin: '',
end: '',
title: '',
chart: '',
xData: [],
yData: []
}
},
methods:{
showChart(){
},
//设置图表的参数
setChart(){
//初始化echarts
this.chart = echarts.init(document.getElementById('chart'))
//设置echarts的配置项和数据
option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}]
};
//添加到图表中
this.chart.setOption(option);
}
}
}
</script>
<style>
</style>
- 设置index.js路由路径
- 使用固定数据
<template>
<div class="app-container">
<!-- 表单 -->
<el-form :inline="true" class="demo-form-inline">
<el-select v-model="searchObj.type" placeholder="请选择">
<el-option label="影片分类" value="subject_num" />
<el-option label="演员统计" value="actor_num" />
</el-select>
<!-- 日历控件 -->
<el-form-item>
<el-date-picker
v-model="searchObj.begin"
type="date"
value-format="yyyy-MM-dd"
placeholder="开始日期"/>
</el-form-item>
<el-form-item>
<el-date-picker
v-model="searchObj.end"
type="date"
value-format="yyyy-MM-dd"
placeholder="结束日期"/>
</el-form-item>
<el-button type="primary" :disabled="btnDisabled" @click="showChart()">查 询</el-button>
</el-form>
<!-- 图表需要渲染的地方 -->
<div class="chart-container">
<div id="chart" class="chart" style="height:500px;width:100%"></div>
</div>
</div>
</template>
<script>
import echarts from 'echarts'
export default {
data(){
return{
searchObj:{},
btnDisabled: false,
begin: '',
end: '',
title: '',
chart: '',
xData: [],
yData: []
}
},
methods:{
showChart(){
this.initChartData()
this.setChart()
},
initChartData(){},
//设置图表的参数
setChart(){
//初始化echarts
this.chart = echarts.init(document.getElementById('chart'))
//设置echarts的配置项和数据
var option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}]
}
//添加到图表中
this.chart.setOption(option)
}
}
}
</script>
<style>
</style>
9.2.1 使用后台数据
- 编写一个api/chart.js
import request from '@/utils/request'
export default {
showChart(searchObj){
return request({
url: `/edu-subject/echarts/${searchObj.begin}/${searchObj.end}/${searchObj.type}`,
method: 'get'
})
}
}
- show.vue
<template>
<div class="app-container">
<!-- 表单 -->
<el-form :inline="true" class="demo-form-inline">
<el-select v-model="searchObj.type" placeholder="请选择">
<el-option label="影片分类" value="subject_num" />
<el-option label="演员统计" value="actor_num" />
</el-select>
<!-- 日历控件 -->
<el-form-item>
<el-date-picker
v-model="searchObj.begin"
type="date"
value-format="yyyy-MM-dd"
placeholder="开始日期"/>
</el-form-item>
<el-form-item>
<el-date-picker
v-model="searchObj.end"
type="date"
value-format="yyyy-MM-dd"
placeholder="结束日期"/>
</el-form-item>
<el-button type="primary" :disabled="btnDisabled" @click="showChart()">查 询</el-button>
</el-form>
<!-- 图表需要渲染的地方 -->
<div class="chart-container">
<div id="chart" class="chart" style="height:500px;width:100%"></div>
</div>
</div>
</template>
<script>
import echarts from 'echarts'
import tb from '@/api/movies/chart'
export default {
data(){
return{
searchObj:{},
btnDisabled: false,
begin: '',
end: '',
title: '',
chart: '',
xData: [],
yData: []
}
},
methods:{
showChart(){
this.initChartData()
this.setChart()
},
initChartData(){//和后端交换数据
tb.showChart(this.searchObj).then(res=>{
//x
this.xData = res.data.data
//y
this.yData = res.data.nums
//需要统计的信息数据
switch(this.setChart.type){
case 'subject_num':
this.title = "影片分类统计"
break
case 'actor_num' :
this.title = '演员的统计'
break
}
this.setChart()
})
},
//设置图表的参数
setChart(){
//初始化echarts
this.chart = echarts.init(document.getElementById('chart'))
//设置echarts的配置项和数据
var option = {
xAxis: {
type: 'category',
data: this.xData
},
yAxis: {
type: 'value'
},
series: [{
data: this.yData,
type: 'line'
}]
}
//添加到图表中
this.chart.setOption(option)
}
}
}
</script>
<style>
</style>
问题及解决方案
1.1 注册的服务名称必须使用中划线,否则网关不识别
1.2 错误
- 解决方法:
- 因为springBoot启动服务需要main方法
- 编写一个主配置类
1.3 提示common_utils获取service_base模块加载失败
- 需要在xiudun_common的pom中添加编译插件
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<phase>none</phase>
</execution>
</executions>
<configuration>
<classifier>execute</classifier>
</configuration>
</plugin>
</plugins>
</build>