智慧校园管理系统:主要是以年级、班级为单位,进行老师和学生信息记录和统计功能。项目采用前后端分离架构思想,前端采用HTML+CSS+VUE来实现页面效果展示,后端采用SpringBoot+MybatisPlus框架实现数据存储等服务。存储层使用高性能的MySQL,服务器使用SpringBoot内置的Tomcat9.x,项目构建工具使用Maven来管理jar包和项目构建。
使用IDEA直接搭建SpringBoot项目
<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>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.2.1.RELEASEversion>
<relativePath/>
parent>
<artifactId>zhxyartifactId>
<groupId>com.atguigugroupId>
<packaging>warpackaging>
<modelVersion>4.0.0modelVersion>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.3.1version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.3.1version>
dependency>
<dependency>
<groupId>org.freemarkergroupId>
<artifactId>freemarkerartifactId>
<version>2.3.31version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>2.7.0version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>2.7.0version>
dependency>
<dependency>
<groupId>com.github.xiaoymingroupId>
<artifactId>knife4j-spring-boot-starterartifactId>
<version>2.0.4version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.29version>
dependency>
<dependency>
<groupId>io.jsonwebtokengroupId>
<artifactId>jjwtartifactId>
<version>0.7.0version>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.4version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
java目录下
resources目录下
server:
port: 9001
spring:
#解决SpringBoot2.6.0与swagger冲突问题【原因是在springboot2.6.0中将SpringMVC 默认路径匹配策略从AntPathMatcher 更改为PathPatternParser,导致出错,解决办法是切换回原先的AntPathMatcher】
mvc:
pathmatch:
matching-strategy: ant_path_matcher
#配置数据源
datasource:
#配置数据源类型
type: com.zaxxer.hikari.HikariDataSource
#配置数据库连接属性
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/zhxy_db?characterEncoding=utf-8&serverTimezone=GMT%2B8&userSSL=false
username: root
password: root
#url: jdbc:mysql://r2czkq1vewxat78mnyg60oisurj5h4dp.mysql.qingcloud.link:3306/ssg_zhxy_db?characterEncoding=utf-8&serverTimezone=GMT%2B8&userSSL=false
#username: shangguigu
#password: shangguigu@QY123
#mybatis-plus内置连接池
hikari:
connection-test-query: SELECT 1
connection-timeout: 60000
idle-timeout: 500000
max-lifetime: 540000
maximum-pool-size: 12
minimum-idle: 10
pool-name: GuliHikariPool
thymeleaf:
#模板的模式,支持 HTML, XML TEXT JAVASCRIPT
mode: HTML5
#编码 可不用配置
encoding: UTF-8
#开发配置为false,避免修改模板还要重启服务器
cache: false
#配置模板路径,默认是templates,可以不用配置
prefix: classpath:/static/
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
servlet:
#设置文件上传上限
multipart:
max-file-size: 10MB
max-request-size: 100MB
mybatis-plus:
configuration:
#添加日志支持
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath*:/mapper/**/*.xml
package com.atguigu.zhxy.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.atguigu.zhxy.mapper")
public class MpConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// paginationInterceptor.setLimit(你的最大单页限制数量,默认 500 条,小于 0 如 -1 不受限制);
return paginationInterceptor;
}
}
package com.atguigu.zhxy.config;
import com.google.common.base.Predicates;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
/**
* Swagger2配置信息
*/
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket webApiConfig(){
//添加head参数start
List<Parameter> pars = new ArrayList<>();
ParameterBuilder tokenPar = new ParameterBuilder();
tokenPar.name("userId")
.description("用户ID")
.defaultValue("1")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(false)
.build();
pars.add(tokenPar.build());
ParameterBuilder tmpPar = new ParameterBuilder();
tmpPar.name("userTempId")
.description("临时用户ID")
.defaultValue("1")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(false)
.build();
pars.add(tmpPar.build());
//添加head参数end
return new Docket(DocumentationType.SWAGGER_2)
.groupName("webApi")
.apiInfo(webApiInfo())
.select()
//可以测试请求头中:输入token
.apis(RequestHandlerSelectors.withClassAnnotation(ApiOperation.class))
//过滤掉admin路径下的所有页面
//.paths(Predicates.and(PathSelectors.regex("/sms/.*")))
//过滤掉所有error或error.*页面
//.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build()
.globalOperationParameters(pars);
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
.title("网站-API文档")
.description("本文档描述了网站微服务接口定义")
.version("1.0")
.contact(new Contact("atguigu", "http://atguigu.com", "[email protected]"))
.build();
}
private ApiInfo adminApiInfo(){
return new ApiInfoBuilder()
.title("后台管理系统-API文档")
.description("本文档描述了后台管理系统微服务接口定义")
.version("1.0")
.contact(new Contact("atguigu", "http://atguigu.com", "[email protected]"))
.build();
}
}
验证码图片工具类
package com.atguigu.zhxy.util;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
* @project: ssm_sms
* @description: 绘制验证码图片
*/
public class CreateVerifiCodeImage {
private static int WIDTH = 90;
private static int HEIGHT = 35;
private static int FONT_SIZE = 20; //字符大小
private static char[] verifiCode; //验证码
private static BufferedImage verifiCodeImage; //验证码图片
/**
* @description: 获取验证码图片
* @param: no
* @return: java.awt.image.BufferedImage
*/
public static BufferedImage getVerifiCodeImage() {
verifiCodeImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_BGR);// create a image
Graphics graphics = verifiCodeImage.getGraphics();
verifiCode = generateCheckCode();
drawBackground(graphics);
drawRands(graphics, verifiCode);
graphics.dispose();
return verifiCodeImage;
}
/**
* @description: 获取验证码
* @param: no
* @return: char[]
*/
public static char[] getVerifiCode() {
return verifiCode;
}
/**
* @description: 随机生成验证码
* @param: no
* @return: char[]
*/
private static char[] generateCheckCode() {
String chars = "0123456789abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] rands = new char[4];
for (int i = 0; i < 4; i++) {
int rand = (int) (Math.random() * (10 + 26 * 2));
rands[i] = chars.charAt(rand);
}
return rands;
}
/**
* @description: 绘制验证码
* @param: g
* @param: rands
* @return: void
*/
private static void drawRands(Graphics g, char[] rands) {
g.setFont(new Font("Console", Font.BOLD, FONT_SIZE));
for (int i = 0; i < rands.length; i++) {
g.setColor(getRandomColor());
g.drawString("" + rands[i], i * FONT_SIZE + 10, 25);
}
}
/**
* @description: 绘制验证码图片背景
* @param: g
* @return: void
*/
private static void drawBackground(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, WIDTH, HEIGHT);
// 绘制验证码干扰点
for (int i = 0; i < 200; i++) {
int x = (int) (Math.random() * WIDTH);
int y = (int) (Math.random() * HEIGHT);
g.setColor(getRandomColor());
g.drawOval(x, y, 1, 1);
}
}
/**
* @description: 获取随机颜色
* @param: no
* @return: java.awt.Color
*/
private static Color getRandomColor() {
Random ran = new Random();
return new Color(ran.nextInt(220), ran.nextInt(220), ran.nextInt(220));
}
}
token口令生成工具 JwtHelper
package com.atguigu.zhxy.util;
import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;
import java.util.Date;
public class JwtHelper {
private static long tokenExpiration = 24*60*60*1000;
private static String tokenSignKey = "123456";
//生成token字符串
public static String createToken(Long userId, Integer userType) {
String token = Jwts.builder()
.setSubject("YYGH-USER")
.setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
.claim("userId", userId)
// .claim("userName", userName)
.claim("userType", userType)
.signWith(SignatureAlgorithm.HS512, tokenSignKey)
.compressWith(CompressionCodecs.GZIP)
.compact();
return token;
}
//从token字符串获取userid
public static Long getUserId(String token) {
if(StringUtils.isEmpty(token)) return null;
Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
Claims claims = claimsJws.getBody();
Integer userId = (Integer)claims.get("userId");
return userId.longValue();
}
//从token字符串获取userType
public static Integer getUserType(String token) {
if(StringUtils.isEmpty(token)) return null;
Jws<Claims> claimsJws
= Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
Claims claims = claimsJws.getBody();
return (Integer)(claims.get("userType"));
}
//从token字符串获取userName
public static String getUserName(String token) {
if(StringUtils.isEmpty(token)) return "";
Jws<Claims> claimsJws
= Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
Claims claims = claimsJws.getBody();
return (String)claims.get("userName");
}
//判断token是否有效
public static boolean isExpiration(String token){
try {
boolean isExpire = Jwts.parser()
.setSigningKey(tokenSignKey)
.parseClaimsJws(token)
.getBody()
.getExpiration().before(new Date());
//没有过期,有效,返回false
return isExpire;
}catch(Exception e) {
//过期出现异常,返回true
return true;
}
}
/**
* 刷新Token
* @param token
* @return
*/
public String refreshToken(String token) {
String refreshedToken;
try {
final Claims claims = Jwts.parser()
.setSigningKey(tokenSignKey)
.parseClaimsJws(token)
.getBody();
refreshedToken = JwtHelper.createToken(getUserId(token), getUserType(token));
} catch (Exception e) {
refreshedToken = null;
}
return refreshedToken;
}
public static void main(String[] args) {
// String token = JwtHelper.createToken(1L, "lucy");
// System.out.println(token);
// System.out.println(JwtHelper.getUserId(token));
// System.out.println(JwtHelper.getUserName(token));
}
}
解析request请求中的 token口令的工具AuthContextHolder
package com.atguigu.zhxy.util;
import javax.servlet.http.HttpServletRequest;
public class AuthContextHolder {
//从请求头token获取userid
public static Long getUserIdToken(HttpServletRequest request) {
//从请求头token
String token = request.getHeader("token");
//调用工具类
Long userId = JwtHelper.getUserId(token);
return userId;
}
//从请求头token获取name
public static String getUserName(HttpServletRequest request) {
//从header获取token
String token = request.getHeader("token");
//jwt从token获取username
String userName = JwtHelper.getUserName(token);
return userName;
}
}
MD5加密工具类
package com.atguigu.zhxy.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class MD5 {
public static String encrypt(String strSrc) {
try {
char hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f' };
byte[] bytes = strSrc.getBytes();
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(bytes);
bytes = md.digest();
int j = bytes.length;
char[] chars = new char[j * 2];
int k = 0;
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
chars[k++] = hexChars[b >>> 4 & 0xf];
chars[k++] = hexChars[b & 0xf];
}
return new String(chars);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new RuntimeException("MD5加密出错!!+" + e);
}
}
}
JSON响应结果格式封装类
package com.atguigu.zhxy.util;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 全局统一返回结果类
*
*/
@Data
@ApiModel(value = "全局统一返回结果")
public class Result<T> {
@ApiModelProperty(value = "返回码")
private Integer code;
@ApiModelProperty(value = "返回消息")
private String message;
@ApiModelProperty(value = "返回数据")
private T data;
public Result(){}
// 返回数据
protected static <T> Result<T> build(T data) {
Result<T> result = new Result<T>();
if (data != null)
result.setData(data);
return result;
}
public static <T> Result<T> build(T body, ResultCodeEnum resultCodeEnum) {
Result<T> result = build(body);
result.setCode(resultCodeEnum.getCode());
result.setMessage(resultCodeEnum.getMessage());
return result;
}
public static<T> Result<T> ok(){
return Result.ok(null);
}
/**
* 操作成功
* @param data
* @param
* @return
*/
public static<T> Result<T> ok(T data){
Result<T> result = build(data);
return build(data, ResultCodeEnum.SUCCESS);
}
public static<T> Result<T> fail(){
return Result.fail(null);
}
/**
* 操作失败
* @param data
* @param
* @return
*/
public static<T> Result<T> fail(T data){
Result<T> result = build(data);
return build(data, ResultCodeEnum.FAIL);
}
public Result<T> message(String msg){
this.setMessage(msg);
return this;
}
public Result<T> code(Integer code){
this.setCode(code);
return this;
}
public boolean isOk() {
if(this.getCode().intValue() == ResultCodeEnum.SUCCESS.getCode().intValue()) {
return true;
}
return false;
}
}
响应结果类型码枚举
package com.atguigu.zhxy.util;
import lombok.Getter;
/**
* 统一返回结果状态信息类
*
*/
@Getter
public enum ResultCodeEnum {
SUCCESS(200,"成功"),
FAIL(201, "失败"),
SERVICE_ERROR(2012, "服务异常"),
ILLEGAL_REQUEST( 204, "非法请求"),
PAY_RUN(205, "支付中"),
ARGUMENT_VALID_ERROR(206, "参数校验错误"),
LOGIN_ERROR(207, "用户名或密码错误"),
LOGIN_AUTH(208, "未登陆"),
PERMISSION(209, "没有权限"),
SECKILL_NO_START(210, "秒杀还没开始"),
SECKILL_RUN(211, "正在排队中"),
SECKILL_NO_PAY_ORDER(212, "您有未支付的订单"),
SECKILL_FINISH(213, "已售罄"),
SECKILL_END(214, "秒杀已结束"),
SECKILL_SUCCESS(215, "抢单成功"),
SECKILL_FAIL(216, "抢单失败"),
SECKILL_ILLEGAL(217, "请求不合法"),
SECKILL_ORDER_SUCCESS(218, "下单成功"),
COUPON_GET(220, "优惠券已经领取"),
COUPON_LIMIT_GET(221, "优惠券已发放完毕"),
//2022-02-22
LOGIN_CODE(222,"长时间未操作,会话已失效,请刷新页面后重试!"),
CODE_ERROR(223,"验证码错误!"),
TOKEN_ERROR(224,"Token无效!")
;
private Integer code;
private String message;
private ResultCodeEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
}
文件上传工具类
package com.atguigu.zhxy.util;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @project: zhxy
* @description: 上传文件的工具类
*/
public class UploadFile {
//存储文件上传失败的错误信息
private static Map<String, Object> error_result = new HashMap<>();
//存储头像的上传结果信息
private static Map<String, Object> upload_result = new HashMap<>();
/**
* @description: 效验所上传图片的大小及格式等信息...
* @param: photo
* @param: path
* @return: java.util.Map
*/
private static Map<String, Object> uploadPhoto(MultipartFile photo, String path) {
//限制头像大小(20M)
int MAX_SIZE = 20971520;
//获取图片的原始名称
String orginalName = photo.getOriginalFilename();
//如果保存文件的路径不存在,则创建该目录
File filePath = new File(path);
if (!filePath.exists()) {
filePath.mkdirs();
}
//限制上传文件的大小
if (photo.getSize() > MAX_SIZE) {
error_result.put("success", false);
error_result.put("msg", "上传的图片大小不能超过20M哟!");
return error_result;
}
// 限制上传的文件类型
String[] suffixs = new String[]{".png", ".PNG", ".jpg", ".JPG", ".jpeg", ".JPEG", ".gif", ".GIF", ".bmp", ".BMP"};
SuffixFileFilter suffixFileFilter = new SuffixFileFilter(suffixs);
if (!suffixFileFilter.accept(new File(path + orginalName))) {
error_result.put("success", false);
error_result.put("msg", "禁止上传此类型文件! 请上传图片哟!");
return error_result;
}
return null;
}
/**
* @description: (提取公共代码 : 提高代码的可重用性)获取头像的上传结果信息
* @param: photo
* @param: dirPaht
* @param: portraitPath
* @return: java.util.Map
*/
public static Map<String, Object> getUploadResult(MultipartFile photo, String dirPaht, String portraitPath) {
if (!photo.isEmpty() && photo.getSize() > 0) {
//获取图片的原始名称
String orginalName = photo.getOriginalFilename();
//上传图片,error_result:存储头像上传失败的错误信息
Map<String, Object> error_result = UploadFile.uploadPhoto(photo, dirPaht);
if (error_result != null) {
return error_result;
}
//使用UUID重命名图片名称(uuid__原始图片名称)
String newPhotoName = UUID.randomUUID() + "__" + orginalName;
//将上传的文件保存到目标目录下
try {
photo.transferTo(new File(dirPaht + newPhotoName));
upload_result.put("success", true);
upload_result.put("portrait_path", portraitPath + newPhotoName);//将存储头像的项目路径返回给页面
} catch (IOException e) {
e.printStackTrace();
upload_result.put("success", false);
upload_result.put("msg", "上传文件失败! 服务器端发生异常!");
return upload_result;
}
} else {
upload_result.put("success", false);
upload_result.put("msg", "头像上传失败! 未找到指定图片!");
}
return upload_result;
}
}
package com.atguigu.myzhxy.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("tb_admin")
public class Admin {
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
private String name;
private char gender;
private String password;
private String email;
private String telephone;
private String address;
private String portraitPath;// 头像的图片路径
}
Clazz
package com.atguigu.myzhxy.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* @project: sms
* @description: 班级信息
*/
@Data
@TableName("tb_clazz")
public class Clazz {
//班级信息
@TableId(value = "id",type = IdType.AUTO)
private Integer id; //班级Id
private String name; //班级名称
private String number; //班级人数
private String introducation; //班级介绍
//班主任信息
private String headmaster; //班主任姓名
private String telephone; //班主任电话
private String email; //班主任邮箱
//所属年级
private String gradeName; //班级所属年级
}
Grade
package com.atguigu.myzhxy.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* @project: sms
* @description: 年级及年级主任信息
*/
@Data
@TableName("tb_grade")
public class Grade {
//年级信息
@TableId(value = "id",type = IdType.AUTO)
private Integer id; //年级ID
private String name; //年级名称
private String introducation; //年级介绍
//年级主任信息
private String manager; //年级主任姓名
private String email; //年级主任邮箱
private String telephone; //年级主任电话
}
Student
package com.atguigu.myzhxy.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* @project: sms
* @description: 学生信息
*/
@Data
@TableName("tb_student")
public class Student {
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
private String sno;
private String name;
private char gender = '男';//default
private String password;
private String email;
private String telephone;
private String address;
private String introducation;
private String portraitPath;//存储头像的项目路径
private String clazzName;//班级名称
}
Teacher
package com.atguigu.myzhxy.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* @project: sms
* @description: 教师信息
*/
@Data
@TableName("tb_teacher")
public class Teacher {
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
private String tno;
private String name;
private char gender;
private String password;
private String email;
private String telephone;
private String address;
private String clazzName;
private String portraitPath;//存储头像的项目路径
// @TableLogic
// private Integer isDeleted;
}
LoginForm
package com.atguigu.myzhxy.pojo;
import lombok.Data;
/**
* @project: ssm_sms
* @description: 用户登录表单信息
*/
@Data
public class LoginForm {
private String username;
private String password;
private String verifiCode;
private Integer userType;
}
AdminMapper
package com.atguigu.myzhxy.mapper;
import com.atguigu.myzhxy.pojo.Admin;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
@Repository
public interface AdminMapper extends BaseMapper<Admin> {
}
ClazzMapper
package com.atguigu.myzhxy.mapper;
import com.atguigu.myzhxy.pojo.Clazz;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
@Repository
public interface ClazzMapper extends BaseMapper<Clazz> {
}
GradeMapper
package com.atguigu.myzhxy.mapper;
import com.atguigu.myzhxy.pojo.Grade;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
@Repository
public interface GradeMapper extends BaseMapper<Grade> {
}
StudentMapper
package com.atguigu.myzhxy.mapper;
import com.atguigu.myzhxy.pojo.Student;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
@Repository
public interface StudentMapper extends BaseMapper<Student> {
}
TeacherMapper
package com.atguigu.myzhxy.mapper;
import com.atguigu.myzhxy.pojo.Teacher;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
@Repository
public interface TeacherMapper extends BaseMapper<Teacher> {
}
AdminService
package com.atguigu.myzhxy.service;
import com.atguigu.myzhxy.pojo.Admin;
import com.baomidou.mybatisplus.extension.service.IService;
public interface AdminService extends IService<Admin> {
}
AdminServiceImpl
package com.atguigu.myzhxy.service.impl;
import com.atguigu.myzhxy.mapper.AdminMapper;
import com.atguigu.myzhxy.pojo.Admin;
import com.atguigu.myzhxy.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("adminServiceImpl")
@Transactional
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
}
ClazzService
package com.atguigu.myzhxy.service;
import com.atguigu.myzhxy.pojo.Clazz;
import com.baomidou.mybatisplus.extension.service.IService;
public interface ClazzService extends IService<Clazz> {
}
ClazzServiceImpl
package com.atguigu.myzhxy.service.impl;
import com.atguigu.myzhxy.mapper.ClazzMapper;
import com.atguigu.myzhxy.pojo.Clazz;
import com.atguigu.myzhxy.service.ClazzService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("clazzServiceImpl")
@Transactional
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper,Clazz> implements ClazzService {
}
GradeService
package com.atguigu.myzhxy.service;
import com.atguigu.myzhxy.pojo.Grade;
import com.baomidou.mybatisplus.extension.service.IService;
public interface GradeService extends IService<Grade> {
}
GradeServiceImpl
package com.atguigu.myzhxy.service.impl;
import com.atguigu.myzhxy.mapper.GradeMapper;
import com.atguigu.myzhxy.pojo.Grade;
import com.atguigu.myzhxy.service.GradeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("gradeServiceImpl")
@Transactional
public class GradeServiceImpl extends ServiceImpl<GradeMapper, Grade> implements GradeService {
}
StudentService
package com.atguigu.myzhxy.service;
import com.atguigu.myzhxy.pojo.Student;
import com.baomidou.mybatisplus.extension.service.IService;
public interface StudentService extends IService<Student> {
}
StudentServiceImpl
package com.atguigu.myzhxy.service.impl;
import com.atguigu.myzhxy.mapper.StudentMapper;
import com.atguigu.myzhxy.pojo.Student;
import com.atguigu.myzhxy.service.StudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("studentServiceImpl")
@Transactional
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
}
TeacherService
package com.atguigu.myzhxy.service;
import com.atguigu.myzhxy.pojo.Teacher;
import com.baomidou.mybatisplus.extension.service.IService;
public interface TeacherService extends IService<Teacher> {
}
TeacherServiceImpl
package com.atguigu.myzhxy.service.impl;
import com.atguigu.myzhxy.mapper.TeacherMapper;
import com.atguigu.myzhxy.pojo.Teacher;
import com.atguigu.myzhxy.service.TeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("teacherServiceImpl")
@Transactional
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {
}
AdminController
package com.atguigu.myzhxy.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/sms/adminController")
@RestController
public class AdminController {
}
ClazzController
package com.atguigu.myzhxy.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/sms/clazzController")
@RestController
public class ClazzController {
}
GradeController
package com.atguigu.myzhxy.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/sms/gradeController")
@RestController
public class GradeController {
}
StudentController
package com.atguigu.myzhxy.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/sms/studentController")
@RestController
public class StudentController {
}
TeacherController
package com.atguigu.myzhxy.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/sms/teacherController")
@RestController
public class TeacherController {
}
SystemController
package com.atguigu.myzhxy.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/sms/system")
@RestController
public class SystemController {
}
在SystemController中创建方法
@GetMapping("/getVerifiCodeImage")
public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response){
//获取图片
BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
//获取图片上的验证码
String verifiCode = new String(CreateVerifiCodeImage.getVerifiCode());
//将验证码文本放入session
HttpSession session = request.getSession();
session.setAttribute("verifiCode",verifiCode);
//将验证码响应给浏览器
try {
ImageIO.write(verifiCodeImage,"JPEG",response.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
在SystemController中注入三个Service对象,然后创建方法
/**
* 登录
* @param loginForm
* @param request
* @return
*/
@PostMapping("/login")
public Result login(@RequestBody LoginForm loginForm,HttpServletRequest request){
//验证码校验
HttpSession session = request.getSession();
String sessionVerifiCode = (String)session.getAttribute("verifiCode");
String loginVerifiCode = loginForm.getVerifiCode();
if("".equals(sessionVerifiCode)||null == sessionVerifiCode){
return Result.fail().message("验证码失效,请刷新重试!");
}
if(!sessionVerifiCode.equalsIgnoreCase(loginVerifiCode)){
return Result.fail().message("验证码有误,请小心输入后重试!");
}
//从session中移除验证码
session.removeAttribute("verifiCode");
//分用户类型校验
//准备map用户存放响应数据
Map<String,Object> map = new LinkedHashMap<>();
switch (loginForm.getUserType()){
case 1:
try {
Admin admin = adminService.login(loginForm);
if(null!=admin){
//用户类型和用户id转换成一个密文,以token的名称向客户端反馈
String token = "";
map.put("token",JwtHelper.createToken(admin.getId().longValue(),1));
}else{
throw new RuntimeException("用户名或密码有误");
}
return Result.ok(map);
} catch (RuntimeException e) {
e.printStackTrace();
return Result.fail().message(e.getMessage());
}
case 2:
try {
Student student = studentService.login(loginForm);
if(null!=student){
//用户类型和用户id转换成一个密文,以token的名称向客户端反馈
String token = "";
map.put("token",JwtHelper.createToken(student.getId().longValue(),2));
}else{
throw new RuntimeException("用户名或密码有误");
}
return Result.ok(map);
} catch (RuntimeException e) {
e.printStackTrace();
return Result.fail().message(e.getMessage());
}
case 3:
try {
Teacher teacher = teacherService.login(loginForm);
if(null!=teacher){
//用户类型和用户id转换成一个密文,以token的名称向客户端反馈
String token = "";
map.put("token",JwtHelper.createToken(teacher.getId().longValue(),3));
}else{
throw new RuntimeException("用户名或密码有误");
}
return Result.ok(map);
} catch (RuntimeException e) {
e.printStackTrace();
return Result.fail().message(e.getMessage());
}
}
return Result.fail().message("查无此用户");
}
实现login()方法
@Override
public Teacher login(LoginForm loginForm) {
QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name",loginForm.getUsername());
queryWrapper.eq("password", MD5.encrypt(loginForm.getPassword()));
Teacher teacher = baseMapper.selectOne(queryWrapper);
return teacher;
}
@Override
public Student login(LoginForm loginForm) {
QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name",loginForm.getUsername());
queryWrapper.eq("password", MD5.encrypt(loginForm.getPassword()));
Student student = baseMapper.selectOne(queryWrapper);
return student;
}
@Override
public Admin login(LoginForm loginForm) {
QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name",loginForm.getUsername());
queryWrapper.eq("password", MD5.encrypt(loginForm.getPassword()));
Admin admin = baseMapper.selectOne(queryWrapper);
return admin;
}
当验证通过后,前端会产生第二个请求,用以获取用户的类型,然后根据用户的类型来展现不同的页面,所以后端要有一个根据token解析用户类型并做出结果响应的控制层。
在SystemController中创建方法
@GetMapping("/getInfo")
public Result getInfoByToken(@RequestHeader("token") String token){
boolean expiration = JwtHelper.isExpiration(token);
if (expiration) {
return Result.build(null,ResultCodeEnum.TOKEN_ERROR);
}
//从token中解析出 用户id 和用户的类型
Long userId = JwtHelper.getUserId(token);
Integer userType = JwtHelper.getUserType(token);
Map<String,Object> map =new LinkedHashMap<>();
switch (userType){
case 1:
Admin admin =adminService.getAdminById(userId);
map.put("userType",1);
map.put("user",admin);
break;
case 2:
Student student =studentService.getStudentById(userId);
map.put("userType",2);
map.put("user",student);
break;
case 3:
Teacher teacher= teacherService.getTeacherById(userId);
map.put("userType",3);
map.put("user",teacher);
break;
}
return Result.ok(map);
}
实现方法
@Override
public Admin getAdminById(Long userId) {
QueryWrapper<Admin> queryWrapper = new QueryWrapper();
queryWrapper.eq("id",userId);
Admin admin = baseMapper.selectOne(queryWrapper);
return admin;
}
@Override
public Student getStudentById(Long userId) {
QueryWrapper<Student> queryWrapper = new QueryWrapper();
queryWrapper.eq("id",userId);
Student student = baseMapper.selectOne(queryWrapper);
return student;
}
@Override
public Teacher getTeacherById(Long userId) {
QueryWrapper<Teacher> queryWrapper = new QueryWrapper();
queryWrapper.eq("id",userId);
Teacher teacher = baseMapper.selectOne(queryWrapper);
return teacher;
}
在GradeController中注入gradeService对象,然后创建方法
@Autowired
private GradeService gradeService;
@GetMapping("/getGrades/{pageNo}/{pageSize}")
public Result getGrades(
@PathVariable("pageNo") Integer pageNo,
@PathVariable("pageSize") Integer pageSize,
String gradeName
){
//分页 带条件查询
Page<Grade> page = new Page<>(pageNo,pageSize);
//通过服务层
IPage<Grade> pageRs = gradeService.getGradeByOpr(page,gradeName);
return Result.ok(pageRs);
}
在GradeServiceImpl中实现
@Override
public IPage<Grade> getGradeByOpr(Page<Grade> pageParam, String gradeName) {
QueryWrapper<Grade> queryWrapper = new QueryWrapper();
if(!StringUtils.isEmpty(gradeName)){
queryWrapper.like("name",gradeName);
}
queryWrapper.orderByDesc("id");
Page<Grade> page = baseMapper.selectPage(pageParam, queryWrapper);
return page;
}
/**
* 年级添加或修改
* @param grade
* @return
*/
@PostMapping("/saveOrUpdateGrade")
public Result saveOrUpdateGrade(
@RequestBody Grade grade){
//接收参数
//调用服务层方法完成增减或修改
gradeService.saveOrUpdate(grade);
return Result.ok();
}
因为IService中已经存在了saveOrUpdate()方法所以不用再次实现方法。
/**
* 年级删除功能
* @param ids
* @return
*/
@DeleteMapping("/deleteGrade")
public Result deleteGrade(
@RequestBody List<Integer> ids){
gradeService.removeByIds(ids);
return Result.ok();
}
因为IService中已经存在了removeByIds()方法所以不用再次实现方法
@Api(tags = "年级控制器")
@RestController
@RequestMapping("/sms/gradeController")
public class GradeController {
@Autowired
private GradeService gradeService;
@ApiOperation("获取所有Grade信息")
@GetMapping("/getGrades")
public Result getGrades(){
List<Grade> grades = gradeService.getGrades();
return Result.ok(grades);
}
}
在GradeServiceImpl中实现方法
@Override
public List<Grade> getGrades() {
return baseMapper.selectList(null);
}
@RequestMapping("/sms/clazzController")
@RestController
public class ClazzController {
@Autowired
private ClazzService clazzService;
@ApiOperation("分页带条件查询班级信息")
@GetMapping("/getClazzsByOpr/{pageNo}/{pageSize}")
public Result getClazzByOpr(
@ApiParam("分页查询页码数") @PathVariable("pageNo") Integer pageNo,
@ApiParam("分页查询页大小")@PathVariable("pageSize") Integer pageSize,
@ApiParam("分页查询条件") Clazz clazz
){
Page<Clazz> page = new Page<>(pageNo,pageSize);
IPage<Clazz> ipage = clazzService.getClazzByOpr(page,clazz);
return Result.ok(ipage);
}
}
实现方法getClazzByOpr()
@Override
public IPage<Clazz> getClazzByOpr(Page<Clazz> pageParam, Clazz clazz) {
QueryWrapper<Clazz> queryWrapper = new QueryWrapper();
String gradeName = clazz.getGradeName();
if(!StringUtils.isEmpty(gradeName)){
queryWrapper.like("grade_name",gradeName);
}
String name = clazz.getName();
if(!StringUtils.isEmpty(name)){
queryWrapper.like("name",name);
}
//根据id进行排序
queryWrapper.orderByDesc("id");
Page<Clazz> clazzPage = baseMapper.selectPage(pageParam, queryWrapper);
return clazzPage;
}
@ApiOperation("增加或修改班级信息")
@PostMapping("/saveOrUpdateClazz")
public Result saveOrUpdateClazz(
@ApiParam("JSON格式的班级信息")@RequestBody Clazz clazz
){
clazzService.saveOrUpdate(clazz);
return Result.ok();
}
因为IService中已经存在了saveOrUpdate()方法所以不用再次实现方法。
@ApiOperation("删除单个或多个班级信息")
@DeleteMapping("/deleteClazz")
public Result deleteClazz(
@RequestBody List<Integer> ids){
clazzService.removeByIds(ids);
return Result.ok();
}
因为IService中已经存在了removeByIds()方法所以不用再次实现方法。
在ClazzController创建方法
@ApiOperation("查询所有班级信息")
@GetMapping("/getClazzs")
public Result getClazz(){
List<Clazz> clazzes = clazzService.getClazz();
return Result.ok(clazzes);
}
实现方法
@Override
public List<Clazz> getClazz() {
return baseMapper.selectList(null);
}
@RequestMapping("/sms/studentController")
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@ApiOperation("分页带条件查询学生信息")
@GetMapping("/getStudentByOpr/{pageNo}/{pageSize}")
public Result getStudentByOpr(
@ApiParam("分页查询页码数") @PathVariable("pageNo")Integer pageNo,
@ApiParam("分页查询页大小")@PathVariable("pageSize") Integer pageSize,
@ApiParam("查询条件") Student student
){
//分页信息封装
Page<Student> pageParam = new Page(pageNo,pageSize);
//进行查询
IPage<Student> studentPage = studentService.getStudentByOpr(pageParam,student);
return Result.ok(studentPage);
}
}
在StudentServiceImpl中实现getStudentByOpr()方法
@Override
public IPage<Student> getStudentByOpr(Page<Student> pageParam, Student student) {
QueryWrapper<Student> studentQueryWrapper = new QueryWrapper();
if(!StringUtils.isEmpty(student.getName())){
studentQueryWrapper.like("name",student.getName());
}
if(!StringUtils.isEmpty(student.getClazzName())){
studentQueryWrapper.like("clazz_name",student.getClazzName());
}
studentQueryWrapper.orderByDesc("id");
Page<Student> studentPage = baseMapper.selectPage(pageParam,studentQueryWrapper);
return studentPage;
}
@ApiOperation("文件上传统一入口")
@PostMapping("/headerImgUpload")
public Result headerImgUpload(
@ApiParam("头像文件") @RequestPart MultipartFile multipartFile,
HttpServletRequest request
){
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
String originalFilename = multipartFile.getOriginalFilename();
int i = originalFilename.lastIndexOf(".");
String newFileName = uuid+originalFilename.substring(i);
//保存文件 将文件发送到第三方/独立的服务器
String portraitPath = "E:/桌面/zhxy/target/classes/public/upload".concat(newFileName);
try {
multipartFile.transferTo(new File(portraitPath));
} catch (IOException e) {
e.printStackTrace();
}
//响应图片路径
String path = "upload/".concat(newFileName);
return Result.ok(path);
}
@ApiOperation("保存或者修改学生信息")
@PostMapping("/addOrUpdateStudent")
public Result addOrUpdateStudent(
@ApiParam("要保存或修改的学生JSON")@RequestBody Student student
){
Integer id = student.getId();
if(null == id||0 == id){
student.setPassword(MD5.encrypt(student.getPassword()));
}
studentService.saveOrUpdate(student);
return Result.ok();
}
因为IService中已经存在了saveOrUpdate()方法所以不用再次实现方法。
@ApiOperation("删除单个或多个学生信息")
@DeleteMapping("/delStudentById")
public Result delStudentById(
@ApiParam("要删除的学生的编号JSON集合")@RequestBody List<Integer> ids
){
studentService.removeByIds(ids);
return Result.ok();
}
因为IService中已经存在了removeByI ds()方法所以不用再次实现方法。
@RequestMapping("/sms/adminController")
@RestController
public class AdminController {
@Autowired
private AdminService adminService;
@ApiOperation("分页带条件查询管理员信息")
@GetMapping("/getAllAdmin/{pageNo}/{pageSize}")
public Result getAllAdmin(
@ApiParam("页码数") @PathVariable("pageNo") Integer pageNo,
@ApiParam("页大小") @PathVariable("pageSize") Integer pageSize,
@ApiParam("管理员名字") String adminName
){
Page<Admin> pageParam = new Page<Admin>(pageNo,pageSize);
IPage<Admin> iPage = adminService.getAdminByOpr(pageParam,adminName);
return Result.ok(iPage);
}
}
实现方法getAdminByOpr()
@Override
public IPage<Admin> getAdminByOpr(Page<Admin> pageParam, String adminName) {
QueryWrapper<Admin> queryWrapper = new QueryWrapper();
if (!StringUtils.isEmpty(adminName)) {
queryWrapper.like("name",adminName);
}
queryWrapper.orderByDesc("id");
Page<Admin> page = baseMapper.selectPage(pageParam,queryWrapper);
return page;
}
@ApiOperation("增加或修改管理员信息")
@PostMapping("/saveOrUpdateAdmin")
public Result saveOrUpdateAdmin(
@ApiParam("JSON格式Admin对象") @RequestBody Admin admin
){
Integer id = admin.getId();
if(id == null||0 ==id){
admin.setPassword(MD5.encrypt(admin.getPassword()));
}
adminService.saveOrUpdate(admin);
return Result.ok();
}
@ApiOperation("删除单个或多个管理员信息")
@DeleteMapping("/deleteAdmin")
public Result deleteAdmin(
@ApiParam("要删除的管理员的多个ID的JSON集合") @RequestBody List<Integer> ids
){
adminService.removeByIds(ids);
return Result.ok();
}
@Autowired
private TeacherService teacherService;
@ApiOperation("分页获取教师信息带条件")
@GetMapping("/getTeacher/{pageNo}/{pageSize}")
public Result getTeacher(
@ApiParam("分页页码数") @PathVariable("pageNo") Integer pageNo,
@ApiParam("分页大小") @PathVariable("pageSize") Integer pageSize,
Teacher teacher
){
Page<Teacher> pageParam = new Page<>(pageNo,pageSize);
IPage<Teacher> page = teacherService.getTeacherByOpr(pageParam,teacher);
return Result.ok(page);
}
@ApiOperation("添加或修改教师信息")
@PostMapping("/saveOrUpdateTeacher")
public Result saveOrUpdateTeacher(
@ApiParam("保存或修改的JSON格式对象") @RequestBody Teacher teacher
){
//如果新增要对密码进行加密
if(teacher.getId()==null||teacher.getId()==0){
teacher.setPassword(MD5.encrypt(teacher.getPassword()));
}
teacherService.saveOrUpdate(teacher);
return Result.ok();
}
@ApiOperation("删除单个或多个教师信息")
@DeleteMapping("/deleteTeacher")
public Result deleteTeacher(
@ApiParam("要删除的教师信息的id的JSON集合") @RequestBody List<Integer> ids
){
teacherService.removeByIds(ids);
return Result.ok();
}
在SystemController中创建方法
@ApiOperation("更新用户密码的处理器")
@PostMapping("/updatePwd/{oldPwd}/{newPwd}")
public Result updatePwd(
@RequestHeader("token") String token,
@PathVariable("oldPwd") String oldPwd,
@PathVariable("newPwd") String newPwd
){
boolean expiration = JwtHelper.isExpiration(token);
if(expiration){
//token过期
return Result.fail().message("token失效,请重新登录后修改密码");
}
//获取用户id和用户类型
Integer userType = JwtHelper.getUserType(token);
Long userId = JwtHelper.getUserId(token);
oldPwd = MD5.encrypt(oldPwd);
newPwd = MD5.encrypt(newPwd);
switch (userType){
case 1:
QueryWrapper<Admin> queryWrapper1 = new QueryWrapper();
queryWrapper1.eq("id",userId.intValue());
queryWrapper1.eq("password", oldPwd);
Admin admin = adminService.getOne(queryWrapper1);
if(admin!=null){
admin.setPassword(newPwd);
adminService.saveOrUpdate(admin);
}else{
return Result.fail().message("原密码有误!");
}
break;
case 2:
QueryWrapper<Student> queryWrapper2 = new QueryWrapper();
queryWrapper2.eq("id",userId.intValue());
queryWrapper2.eq("password", oldPwd);
Student student = studentService.getOne(queryWrapper2);
if(student!=null){
student.setPassword(newPwd);
studentService.saveOrUpdate(student);
}else{
return Result.fail().message("原密码有误!");
}
break;
case 3:
QueryWrapper<Teacher> queryWrapper3 = new QueryWrapper();
queryWrapper3.eq("id",userId.intValue());
queryWrapper3.eq("password", oldPwd);
Teacher teacher = teacherService.getOne(queryWrapper3;
if(teacher!=null){
teacher.setPassword(newPwd);
teacherService.saveOrUpdate(teacher);
}else{
return Result.fail().message("原密码有误!");
}
break;
}
return Result.ok();
}