【在线教育】课程科目入门(二)

简介: 课程科目入门

2.1.4 前端


  • 创建路由模块

image.png

/** When your routing table is too long, you can split it into small modules **/​importLayoutfrom'@/layout'​constcourseRouter= {
path: '/course',           // 当前模块前缀路径,必须以/开头component: Layout,          // 采用布局组件显示当前模块【默认】redirect: '/course/subjectList',  // “教师管理”默认显示路由name: '课程管理',            // 路由名称meta: {
title: '课程管理',         // 一级菜单名称,children.length==0 隐藏icon: 'table'// 一级菜单图标,children.length==0 隐藏  },
children: [
    {
path: 'subjectList',
component: () =>import('@/views/edu/course/subjectList.vue'),
name: '科目列表',
meta: { title: '科目列表', icon: 'list' }   //二级菜单名称    }
  ]
}
exportdefaultcourseRouter

image.png

image.png

2.2 查询所有


  • 以树形table展示数据

image.png

2.2.1 后端实现


  • 修改 EduSubjectController
packagecom.czxy.zx.course.controller;
​importcom.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
importcom.czxy.zx.course.service.EduSubjectService;
importcom.czxy.zx.domain.EduSubject;
importcom.czxy.zx.vo.BaseResult;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RestController;
​importjavax.annotation.Resource;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
​/*** @author 桐叔* @email liangtong@itcast.cn*/@RestController@RequestMapping("/subject")
publicclassEduSubjectController {
​@ResourceprivateEduSubjectServiceeduSubjectService;
​@GetMappingpublicBaseResultfindAll() {
//1 查询所有QueryWrapperqueryWrapper=newQueryWrapper();
queryWrapper.orderByAsc("parent_id");
List<EduSubject>list=eduSubjectService.list(queryWrapper);
​//2 处理父子关系List<EduSubject>resultList=newArrayList<>();
Map<String,EduSubject>cache=newHashMap<>();
list.forEach(eduSubject-> {
// 获得父EduSubjectparentEduSubject=cache.get(eduSubject.getParentId());
// 如果没有父表示第一层,如果有父追加if(parentEduSubject!=null) {
// 如果有孩子,判断父对象的集合List<EduSubject>temp=parentEduSubject.getChildren();
if(temp==null) {
parentEduSubject.setChildren(newArrayList<>());
                }
// 将孩子添加到父对象的集合中parentEduSubject.getChildren().add(eduSubject);
            } else {
resultList.add(eduSubject);
            }
// 缓存当前cache.put(eduSubject.getId(),eduSubject);
​        });
​returnBaseResult.ok("查询成功", resultList);
    }
​}
​

2.2.2 前端接口


image.png

importaxiosfrom'@/utils/request'​// 查询所有课程科目exportfunctionfindAllSub() {
returnaxios.get('/course-service/subject');
}

2.2.3 前端实现


  • 修改 @/views/edu/course/subjectList.vue

image.png

<template><div><el-tablev-loading="listLoading"      :data="subjectList"borderfithighlight-current-rowstyle="width: 100%;"row-key="title"      :tree-props="{children: 'children'}"><el-table-columnlabel="科目名称"prop="title"align="center"width="200"></el-table-column><el-table-columnlabel="排序"prop="sort"width="80px"min-width="50px"></el-table-column><el-table-columnlabel="添加时间"width="200px"align="center"><templateslot-scope="{row}"><span>{{ row.gmtCreate|parseTime('{y}-{m}-{d} {h}:{i}') }}</span></template></el-table-column><el-table-columnlabel="更新时间"width="200px"align="center"><templateslot-scope="{row}"><span>{{ row.gmtModified|parseTime('{y}-{m}-{d} {h}:{i}') }}</span></template></el-table-column><el-table-columnlabel="操作"align="center"class-name="small-padding fixed-width"><templateslot-scope="{row,$index}"><el-buttontype="primary"size="mini">修改</el-button><el-buttonv-if="row.status!='deleted'"size="mini"type="danger">删除</el-button></template></el-table-column></el-table></div></template>​<script>import { findAllSub } from'@/api/edu/course'​exportdefault {
data() {
return {
subjectList: [] ,
listLoading: false,
    }
  },
methods: {
asyncfindAllSubject() {  // 查询所有this.listLoading=truelet { data } =awaitfindAllSub()
this.subjectList=datathis.listLoading=false    }
  },
mounted() {
this.findAllSubject()
  },
}
</script>​<style>​</style>

2.3 导入科目


2.3.1 需求


image.png

2.3.2 前端


使用upload组件<!--文件上传--><el-uploadclass="upload-demo"      :action="updateUrl"      :limit="1"      :on-exceed="handleExceed"      :before-upload="beforeUpload"      :on-remove="handleRemove"      :on-success="handleSuccess"      :file-list="fileList"><el-buttonsize="small"type="primary">点击上传</el-button><divslot="tip"class="el-upload__tip">只能上传xls或xlsx文件,且不超过500kb</div></el-upload>声明变量data() {
return {
fileList: [],     //上传文件列表updateUrl: process.env.VUE_APP_BASE_API+'/course-service/subject/upload',   //上传路径    }
  },
编写处理函数handleExceed(files, fileList) {   // 超出个数限制this.$message.warning(`当前选择1个文件`);
    },
beforeUpload(file) {      // 上传文件之前// 是否是 xlsx 文件(2003)constisXlsx=file.type==='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'// 是否是 xls 文件(2010)constisXls=file.type==='application/vnd.ms-excel'constisLt2M=file.size/1024/1024<2;
​if (!isXlsx&&!isXls) {
this.$message.error('上传文件不是excel文件!');
      }
if (!isLt2M) {
this.$message.error('上传文件大小不能超过 2MB!');
      }
return (isXlsx||isXls) &&isLt2M;
    },
handleRemove(file, fileList) {  // 文件列表移除文件console.log(file, fileList);
    },
handleSuccess(response, file, fileList) { // 文件上传成功// 成功提示this.$message.success(response.message)
// 刷新this.findAllSubject()
    }

2.3.2 前端:完整版


<template><div><el-tablev-loading="listLoading"      :data="subjectList"borderfithighlight-current-rowstyle="width: 100%;"row-key="title"      :tree-props="{children: 'children'}"><el-table-columnlabel="科目名称"prop="title"align="left"width="200"></el-table-column><el-table-columnlabel="排序"prop="sort"width="80px"min-width="50px"></el-table-column><el-table-columnlabel="添加时间"width="200px"align="center"><templateslot-scope="{row}"><span>{{ row.gmtCreate|parseTime('{y}-{m}-{d} {h}:{i}') }}</span></template></el-table-column><el-table-columnlabel="更新时间"width="200px"align="center"><templateslot-scope="{row}"><span>{{ row.gmtModified|parseTime('{y}-{m}-{d} {h}:{i}') }}</span></template></el-table-column><el-table-columnlabel="操作"align="center"class-name="small-padding fixed-width"><templateslot-scope="{row}"><el-buttontype="primary"size="mini">修改</el-button><el-buttonv-if="row.status!='deleted'"size="mini"type="danger">删除</el-button></template></el-table-column></el-table>​<!--文件上传--><el-uploadclass="upload-demo"      :action="updateUrl"      :limit="1"      :on-exceed="handleExceed"      :before-upload="beforeUpload"      :on-remove="handleRemove"      :on-success="handleSuccess"      :file-list="fileList"><el-buttonsize="small"type="primary">点击上传</el-button><divslot="tip"class="el-upload__tip">只能上传xls或xlsx文件,且不超过500kb</div></el-upload></div></template>​<script>import { findAllSub } from'@/api/edu/course'​exportdefault {
data() {
return {
subjectList: [] ,
listLoading: false,
fileList: [],     //上传文件列表updateUrl: process.env.VUE_APP_BASE_API+'/course-service/subject/upload',   //上传路径    }
  },
methods: {
asyncfindAllSubject() {  // 查询所有this.listLoading=truelet { data } =awaitfindAllSub()
this.subjectList=datathis.listLoading=false    },
handleExceed(files, fileList) {   // 超出个数限制this.$message.warning(`当前选择1个文件`);
    },
beforeUpload(file) {      // 上传文件之前// 是否是 xlsx 文件(2003)constisXlsx=file.type==='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'// 是否是 xls 文件(2010)constisXls=file.type==='application/vnd.ms-excel'constisLt2M=file.size/1024/1024<2;
​if (!isXlsx&&!isXls) {
this.$message.error('上传文件不是excel文件!');
      }
if (!isLt2M) {
this.$message.error('上传文件大小不能超过 2MB!');
      }
return (isXlsx||isXls) &&isLt2M;
    },
handleRemove(file, fileList) {  // 文件列表移除文件console.log(file, fileList);
    },
handleSuccess(response, file, fileList) { // 文件上传成功// 成功提示this.$message.success(response.message)
// 刷新this.findAllSubject()
    }
  },
mounted() {
this.findAllSubject()
  },
}
</script>​<style>​</style>

2.3.4 后端


1) 完善JavaBean

packagecom.czxy.zx.domain;
​importcom.baomidou.mybatisplus.annotation.*;
importcom.fasterxml.jackson.annotation.JsonFormat;
importlombok.Data;
importorg.springframework.format.annotation.DateTimeFormat;
​importjava.util.ArrayList;
importjava.util.Date;
importjava.util.List;
​/*** 课程科目(EduSubject)表实体类** @author 桐叔*/@Data@TableName("edu_subject")
publicclassEduSubject{
@TableId(type=IdType.ASSIGN_UUID)
//课程科目IDprivateStringid;
//科目名称privateStringtitle;
//父IDprivateStringparentId;
//排序字段privateIntegersort;
//创建时间@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
@TableField(fill=FieldFill.INSERT)
privateDategmtCreate;
//更新时间@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
@TableField(fill=FieldFill.INSERT)
privateDategmtModified;
​@TableField(exist=false)
privateList<EduSubject>children=newArrayList<>();
​}

image.png

packagecom.czxy.zx.course.handler;
​importcom.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
importorg.apache.ibatis.reflection.MetaObject;
importorg.springframework.stereotype.Component;
​importjava.util.Date;
​/*** @author 桐叔* @email liangtong@itcast.cn*/@ComponentpublicclassSubjectMetaObjectHandlerimplementsMetaObjectHandler {
@OverridepublicvoidinsertFill(MetaObjectmetaObject) {
// 创建时间this.setFieldValByName("gmtCreate",newDate(), metaObject);
// 修改时间this.setFieldValByName("gmtModified",newDate() , metaObject);
    }
​@OverridepublicvoidupdateFill(MetaObjectmetaObject) {
// 修改时,填充的内容this.setFieldValByName("gmtModified",newDate() , metaObject);
    }
}

image.png

接口packagecom.czxy.zx.course.service;
​importcom.baomidou.mybatisplus.extension.service.IService;
importcom.czxy.zx.domain.EduSubject;
​/*** @author 桐叔* @email liangtong@itcast.cn*/publicinterfaceEduSubjectServiceextendsIService<EduSubject> {
/*** 通过title查询* @param title* @return*/EduSubjectfindByTitle(Stringtitle);
}
​实现类packagecom.czxy.zx.course.service.impl;
​importcom.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
importcom.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
importcom.czxy.zx.course.mapper.EduSubjectMapper;
importcom.czxy.zx.course.service.EduSubjectService;
importcom.czxy.zx.domain.EduSubject;
importorg.springframework.stereotype.Service;
importorg.springframework.transaction.annotation.Transactional;
​/*** @author 桐叔* @email liangtong@itcast.cn*/@Service@TransactionalpublicclassEduSubjectServiceImplextendsServiceImpl<EduSubjectMapper, EduSubject>implementsEduSubjectService {
@OverridepublicEduSubjectfindByTitle(Stringtitle) {
QueryWrapperqueryWrapper=newQueryWrapper();
queryWrapper.eq("title", title);
​EduSubjecteduSubject=baseMapper.selectOne(queryWrapper);
returneduSubject;
    }
}
​4)controller:上传/*** 文件上传* @param file* @return*/@PostMapping("/upload")
publicBaseResultupload(MultipartFilefile) {
try {
// 解析excelEasyExcel.read(file.getInputStream(), UploadSubjectVo.class, eduSubjectListener).sheet(0).doRead();
​returnBaseResult.ok("上传成功");
        } catch (IOExceptione) {
returnBaseResult.error("上传失败");
        }
    }

image.png

packagecom.czxy.zx.course.upload;
​importcom.alibaba.excel.annotation.ExcelProperty;
importlombok.Data;
​/*** @author 桐叔* @email liangtong@itcast.cn*/@DatapublicclassUploadSubjectVo {
​@ExcelProperty("一级分类")
privateStringoneLevel;
​@ExcelProperty("二级分类")
privateStringtwoLevel;
​​}

image.png

packagecom.czxy.zx.course.upload;
​importcom.alibaba.excel.context.AnalysisContext;
importcom.alibaba.excel.event.AnalysisEventListener;
importcom.czxy.zx.course.service.EduSubjectService;
importcom.czxy.zx.domain.EduSubject;
importorg.springframework.stereotype.Component;
​importjavax.annotation.Resource;
​/*** @author 桐叔* @email liangtong@itcast.cn*/@ComponentpublicclassEduSubjectListenerextendsAnalysisEventListener<UploadSubjectVo> {
​@ResourceprivateEduSubjectServiceeduSubjectService;
​@Overridepublicvoidinvoke(UploadSubjectVouploadSubjectVo, AnalysisContextanalysisContext) {
// 1. 处理一级// 1.1 查询一级EduSubjectoneSubject=eduSubjectService.findByTitle(uploadSubjectVo.getOneLevel());
// 1.2 保存一级if(oneSubject==null) {
oneSubject=newEduSubject();
oneSubject.setTitle(uploadSubjectVo.getOneLevel());
oneSubject.setSort(0);
oneSubject.setParentId("0");        // 一级默认0eduSubjectService.save(oneSubject);
        }
​// 2. 处理二级// 2.1 查询二级EduSubjecttwoSubject=eduSubjectService.findByTitle(uploadSubjectVo.getTwoLevel());
// 2.2 保存二级if(twoSubject==null) {
twoSubject=newEduSubject();
twoSubject.setTitle(uploadSubjectVo.getTwoLevel());
twoSubject.setSort(0);
twoSubject.setParentId(oneSubject.getId()); //二级的父ID为一级的IDeduSubjectService.save(twoSubject);
        }
​    }
​@OverridepublicvoiddoAfterAllAnalysed(AnalysisContextanalysisContext) {
​    }
}
相关文章
|
9月前
|
人工智能 JavaScript 编译器
AI工具的“超级外挂”:从零手把手教你搭建私人 MCP 服务器
本文手把手教你用Node.js从零搭建私人MCP(模型上下文协议)服务器,解决AI无法直接访问本地文件、数据库等痛点。含环境配置、TypeScript编译避坑、Hello World工具开发及Inspector调试全流程,助你赋予AI真实行动力!
2300 1
AI工具的“超级外挂”:从零手把手教你搭建私人 MCP 服务器
|
2月前
|
人工智能
复制另一个自己:用 QoderWake 打造个人分身
QoderWake个人分身,从你选择的聊天、会议纪要和文件中学习,记住你的经历、理解你的表达、尊重你的边界。它能代答重复问题、找回讨论背景、拟写贴近你风格的回复——让另一个“你”,在忙碌时真正帮上忙。
317 0
|
5月前
|
人工智能 算法 Java
手工测试岗正在消失:2026秋招,企业到底需要什么样的测试人才?
2026年测试行业正经历深刻变革:手工测试岗断崖式减少(需求降47%),AI与自动化覆盖超80%测试场景。企业亟需会编程、懂自动化、能开发测试工具的“测试开发工程师”,而非仅会执行用例的手工测试员。转型,刻不容缓。
|
6月前
|
人工智能 弹性计算 运维
低成本搭建AI智能体:OpenClaw 阿里云ECS/本地部署、免费大模型 API 适配教程
OpenClaw是一款开源可自主迭代的AI智能体框架,主打轻量化部署、模型高度兼容、自主任务执行与可扩展技能体系,能够依托大模型能力完成自主思考、任务拆解、工具调用、流程闭环执行,区别于传统单一对话式AI工具。该框架支持**本地部署**与**云端部署**两种模式,适配个人学习调试、本地离线开发、云端7×24小时常驻运行等不同场景。
636 0
|
JavaScript Linux 开发工具
编写第一个MCP Server之Hello world
本文介绍如何使用Node.js编写一个简单的MCP Server——“Echo”服务。通过环境搭建、项目初始化、代码实现及验证,完成MCP服务的开发与调用测试,助力快速入门MCP协议开发。
1163 2
|
UED
使echarts图例legend只选中一个(selectedMode)
本文介绍了如何在ECharts图表中设置图例(legend)的选中模式为单选('single'),以确保在有多个图例时,用户只能选择一个图例项进行展示,从而提升图表的可读性和用户体验。
1906 2
使echarts图例legend只选中一个(selectedMode)
|
人工智能 自然语言处理 前端开发
20分钟上手DeepSeek开发:SpringBoot + Vue2快速构建AI对话系统
本文介绍如何使用Spring Boot3与Vue2快速构建基于DeepSeek的AI对话系统。系统具备实时流式交互、Markdown内容渲染、前端安全防护等功能,采用响应式架构提升性能。后端以Spring Boot为核心,结合WebFlux和Lombok开发;前端使用Vue2配合WebSocket实现双向通信,并通过DOMPurify保障安全性。项目支持中文语义优化,API延迟低,成本可控,适合个人及企业应用。跟随教程,轻松开启AI应用开发之旅!
|
机器学习/深度学习 数据可视化 数据挖掘
数据集中存在大量重复值时,如何选择合适的分析方法?
总之,当数据集中存在大量重复值时,需要综合考虑各种分析方法的特点和适用范围,根据具体的分析目标和数据情况选择合适的方法,或者结合多种方法进行综合分析,以获得准确、可靠的分析结果。
985 65

热门文章

最新文章