目录
一、前言介绍
随着社会的进步,高校的扩招以及升学率的提高,高校学生人数急剧增长,宿舍 随着社会的进步,高校的扩招以及升学率的提高,高校学生人数急剧增长,宿舍需求也相应增长。学生宿舍管理系统是学校不可缺少的部分,它对于学校的决策者和管理者来说至关重要。大学四年甚至是更长时间我们都几乎在宿舍和亲密舍友度过,宿舍是学生在大学校园里一个非常重要的学习、生活、娱乐的地方,它是学生生活的港湾,在这里度过成长蜕变的光辉岁月。然而,传统的宿舍管理模式面对大量学生的住房需求也相应增长. 学生宿舍管理系统是学校不可缺少的部分,它对于学校的决策者和管理者来说至关重要.大学四年甚至是更长时间我们都几乎在宿舍和亲密舍友度过,宿舍是学生在大学校园里一个非常重要的学习、生活、娱乐的地方,它是学生生活的港湾,在这里度过成长蜕变的光辉岁月.然而,传统的宿舍管理模式面对大量学生的需求,宿舍的安全问题,信息的及时更新等弊端凸显,传统的宿舍管理过度的依靠人力资源的分配、登记,对于庞大的学生人数及学生信息,显然只依靠人力,很难准确的处理好大量的数据,传统的管理模式不仅效率低,出错率高,而且难查询宿舍及学生的实时信息,对于学校的管理带来了诸多不便,因此,能够开发一个大学生宿舍管理系统及时的了解到每个宿舍的住宿情况,人员信息,对于加强学校宿舍的安全管理,优化人力资源,合理调配新生入住,提高入住效率大有裨益。社会的科技进步,管理类软件系统的快速发展为解决这一难题提供了现实途径,学生宿舍的信息化管理方式以其方便、快捷、节省人力资源等优点成为解决这一问题的有效途径,用现代计算机技术对高校内住校学生的信息进行有效管理,快捷的处理大量数据,使得高校宿舍的信息化管理已成为必然的趋势。
二、功能展示
具体可参考其他博客https://blog.csdn.net/weixin_65950231/article/details/127930529
三、优化部分
1.报修审核
2.公告通知
3.验证码登录
4.聊天室
详情请见https://blog.csdn.net/weixin_65950231/article/details/128553775
四、核心代码
1.登录及验证码获取
<template>
<div class="ValidCode disabled-select"
:style="`width:${width}; height:${height}`"
@click="refreshCode">
<span v-for="(item, index) in codeList"
:key="index"
:style="getStyle(item)">
{{item.code}}
</span>
</div>
</template>
<script>
export default {
name: "ValidCode",
model: {
prop: 'value',
event: 'input'
},
props: {
width: {
type: String,
default: '100px'
},
height: {
type: String,
default: '34px'
},
length: {
type: Number,
default: 4
}
},
data () {
return {
codeList: []
}
},
mounted () {
this.createdCode()
},
methods: {
refreshCode () {
this.createdCode()
},
createdCode () {
const len = this.length
const codeList = []
const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz0123456789'
const charsLen = chars.length
// 生成
for (let i = 0; i < len; i++) {
const rgb = [Math.round(Math.random() * 220), Math.round(Math.random() * 240), Math.round(Math.random() * 200)]
codeList.push({
code: chars.charAt(Math.floor(Math.random() * charsLen)),
color: `rgb(${rgb})`,
fontSize: `1${[Math.floor(Math.random() * 10)]}px`,
padding: `${[Math.floor(Math.random() * 10)]}px`,
transform: `rotate(${Math.floor(Math.random() * 90) - Math.floor(Math.random() * 90)}deg)`
})
}
// 指向
this.codeList = codeList
// 将当前数据派发出去
this.$emit('input', codeList.map(item => item.code).join(''))
},
getStyle (data) {
return `color: ${data.color}; font-size: ${data.fontSize}; padding: ${data.padding}; transform: ${data.transform}`
}
}
}
</script>
<style scoped >
.ValidCode {
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
span{
display: inline-block;
}
</style>
<template>
<div style="height: 100vh; overflow: hidden">
<div style="height: 50px;
line-height: 50px;
border-bottom: 2px solid var(--colorRed);
padding-left: 20px;
color: var(--colorRed)">
<b style="font-size: 24px;">xx宿舍</b>
<i style="margin-left: 20px">-- 只为更好的你</i>
</div>
<div style="width: 50%;
margin: 50px auto;
border-radius: 10px;
box-shadow: 0 0 10px -2px cornflowerblue;
display: flex">
<div style="flex: 1; padding: 50px 50px">
<img src="../assets/images/学习.png" alt="" style="width: 100%;">
</div>
<div style="flex: 1; padding: 20px">
<div class="form-toggle">
<b >账号登录</b>
</div>
<el-form ref="form" :model="form" size="normal" :rules="rules" >
<el-form-item prop="username" class="props">
<el-input placeholder="账号" clearable v-model="form.username" prefix-icon="el-icon-user" />
</el-form-item>
<el-form-item prop="password" class="props">
<el-input placeholder="密码" v-model="form.password" show-password prefix-icon="el-icon-lock" />
</el-form-item>
<ek-form-item>
<div style="display: flex">
<el-input v-model="form.validCode" style="width: 60%" placeholder="请输入验证码" size="medium"></el-input>
<ValidCode @input="createValidCode" />
</div>
</ek-form-item>
<el-form-item style="padding-top:15px">
<el-button type="primary" style="width: 100%" @click="login" round>登 录</el-button>
</el-form-item>
<!-- <el-form-item>-->
<div style="margin: 10px 0; text-align: right;">
<a href="/register" style="color: var(--colorRed)">立即注册</a>
</div>
<!-- <el-button style="width: 100%" @click="register" round>点击注册</el-button>-->
<!-- </el-form-item>-->
</el-form>
</div>
</div>
</div>
</template>
<script>
import request from "@/utils/request";
import ValidCode from "@/components/ValidCode";
const Base64 = require('js-base64').Base64
export default {
name: "Login",
components: {
ValidCode
},
data() {
return {
form: {sex: 1},
rules: {
username: [
{required: true, message: '请输入用户名', trigger: 'blur'},
{min: 3, max: 10, message: "长度在3到10个字符", trigger: "blur"},
],
password: [
{required: true, message: '请输入密码', trigger: 'blur'},
{min: 1, max: 20, message: '长度在 6 到 11 个字符', trigger: 'blur'}
],
},
validCode: '',
}
},
created() {
sessionStorage.removeItem("user")
},
methods: {
register:function(){
this.$router.push("/register");
},
//接收验证码组件提交的4位验证码
createValidCode(data) {
this.validCode = data
},
login() {
this.$refs['form'].validate((valid) => {
if (valid) {
if (!this.form.validCode) {
this.$message.error("请填写验证码")
return
}
if (this.form.validCode.toLowerCase() !== this.validCode.toLowerCase()) {
this.$message.error("验证码错误")
return
}
request.post("/user/login", this.form).then(res => {
if (res.code === '200'){
// sessionStorage.setItem("user", JSON.stringify(res.data))//缓存用户信息
localStorage.setItem("user", JSON.stringify(res.data))
if (res.data.role === 'USER') {
this.$router.push("/")
} else {
this.$router.push("/mall/index")
}
this.$message({
type: "success",
message: "登录成功"
})
// this.$router.push("/") //登录成功过后进行页面跳转到主页
} else {
this.$message({
type: "error",
message: res.msg
})
}
})
}
});
},
}
}
</script>
<style scoped>
.form-toggle {
margin: 20px 0;
text-align: center
}
.form-toggle b {
font-size: 20px;
cursor: pointer;
}
.active {
color: var(--colorRed);
}
</style>
2.后端
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Constants;
import com.example.demo.common.Result;
import com.example.demo.controller.dto.UserDTO;
import com.example.demo.entity.User;
import com.example.demo.service.IUserService;
import com.example.demo.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private IUserService userService;
@PostMapping("/login")
public Result login(@RequestBody UserDTO userDTO) {
String username = userDTO.getUsername();
String password = userDTO.getPassword();
if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
return Result.error(Constants.CODE_400,"参数错误");
}
UserDTO dto = userService.login(userDTO);
return Result.success(dto);
}
@PostMapping("/register")
public Result register(@RequestBody UserDTO userDTO) {
String username = userDTO.getUsername();
String password = userDTO.getPassword();
if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
return Result.error(Constants.CODE_400,"参数错误");
}
return Result.success(userService.register(userDTO));
}
//新增或者更新
@PostMapping
public Result save(@RequestBody User user) {
String username = user.getUsername();
if (StrUtil.isBlank(username)) {
return Result.error(Constants.CODE_400, "参数错误");
}
if (user.getId() != null) {
user.setPassword(null);
} else {
user.setNickname(user.getUsername());
if (user.getPassword() == null) {
user.setPassword("123456");
}
}
return Result.success(userService.saveOrUpdate(user));
}
//删除
// @DeleteMapping("/{id}")
// public Result delete(@PathVariable Integer id) {
// return Result.success(userService.removeById(id));
// }
@PostMapping("/del/batch")
public Result deleteBatch(@RequestBody List<Integer> ids) {//批量删除
return Result.success(userService.removeByIds(ids));
}
//查询所有数据
@GetMapping
public Result findAll() {
return Result.success(userService.list());
}
@GetMapping("/{id}")
public Result findOne(@PathVariable Integer id) {
return Result.success(userService.getById(id));
}
@GetMapping("/username/{username}")
public Result findByUsername(@PathVariable String username) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("username", username);
return Result.success(userService.getOne(queryWrapper));
}
@GetMapping("/page")
public Result findPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize,
@RequestParam(defaultValue = "") String username) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("id");
if (!"".equals(username)) {
queryWrapper.like("username", username);
}
return Result.success(userService.page(new Page<>(pageNum, pageSize), queryWrapper));
}
/**
* 导出接口
*/
@GetMapping("/export")
public void export(HttpServletResponse response) throws Exception {
//从数据库查询出所有的数据
List<User> list = userService.list();
//通过工具类创建writer 写出到磁盘路径
//ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
//在内存操作,写出到浏览器
ExcelWriter writer = ExcelUtil.getWriter(true);
//自定义标题别名
writer.addHeaderAlias("username", "用户名");
writer.addHeaderAlias("password", "密码");
writer.addHeaderAlias("nickname", "昵称");
writer.addHeaderAlias("sex", "性别");
writer.addHeaderAlias("phone", "联系方式");
writer.addHeaderAlias("address", "地址");
writer.addHeaderAlias("email", "邮箱");
writer.addHeaderAlias("createTime", "创建时间");
writer.addHeaderAlias("avatarUrl", "头像");
writer.addHeaderAlias("role", "身份");
//一次性写出list类的对象到excel,使用默认样式,强制输出标题
writer.write(list, true);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
String fileName = URLEncoder.encode("用户详情","UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName +".xlsx");
ServletOutputStream out = response.getOutputStream();
writer.flush(out, true);
out.close();
writer.close();
}
/**
* excel导入
* @param
* @throws Exception
*/
@PostMapping("/import")
public Result imp(MultipartFile file) throws Exception {
InputStream inputStream = file.getInputStream();
ExcelReader reader = ExcelUtil.getReader(inputStream);
//通过JavaBean的方式读取Excel内的对象,但要求表头必须是英文,跟JavaBean的属性要对应
List<User> list = reader.readAll(User.class);
userService.saveBatch(list);
return Result.success(true);
}
}
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Constants;
import com.example.demo.common.Result;
import com.example.demo.entity.Files;
import com.example.demo.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
@RestController
@RequestMapping("/file")
public class FileController {
@Value("${files.upload.path}")
private String fileUploadPath;
@Value("${server.ip}")
private String serverIp;
@Resource
private FileMapper fileMapper;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@PostMapping("/upload")
public String upload(@RequestParam MultipartFile file) throws IOException {
String originalFilename = file.getOriginalFilename();
String type = FileUtil.extName(originalFilename);
long size = file.getSize();
// 定义一个文件唯一的标识码
String fileUUID = IdUtil.fastSimpleUUID() + StrUtil.DOT + type;
File uploadFile = new File(fileUploadPath + fileUUID);
// 判断配置的文件目录是否存在,若不存在则创建一个新的文件目录
File parentFile = uploadFile.getParentFile();
//判断目录是否存在,不存在就新建
if (!parentFile.exists()) {
parentFile.mkdirs();
}
String url;
// 获取文件的md5
String md5 = SecureUtil.md5(file.getInputStream());
// 从数据库查询是否存在相同的记录
Files dbFiles = getFileByMd5(md5);
if (dbFiles != null) {
url = dbFiles.getUrl();
} else {
// 上传文件到磁盘
file.transferTo(uploadFile);
// 数据库若不存在重复文件,则不删除刚才上传的文件
url = "http://" + serverIp + ":9090/file/" + fileUUID;
}
//存储到数据库
Files saveFile = new Files();
saveFile.setName(originalFilename);
saveFile.setType(type);
saveFile.setSize(size/1024);
saveFile.setUrl(url);
saveFile.setMd5(md5);
fileMapper.insert(saveFile);
return url;
// String md5 = SecureUtil.md5(file.getInputStream());
// Files files = getFileByMd5(md5);
//
// String url;
// if (files != null) {
// url = files.getUrl();
// } else {
// file.transferTo(uploadFile);
// url = "http://localhost:9090/file/" + fileUUID;
// }
// //存储到数据库
// Files saveFile = new Files();
// saveFile.setName(originalFilename);
// saveFile.setType(type);
// saveFile.setSize(size/1024);
// saveFile.setUrl(url);
// saveFile.setMd5(md5);
// fileMapper.insert(saveFile);
// return url;
}
@GetMapping("/{fileUUID}")
public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
// 根据文件的唯一标识码获取文件
File uploadFile = new File(fileUploadPath + fileUUID);
// 设置输出流的格式
ServletOutputStream os = response.getOutputStream();
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
response.setContentType("application/octet-stream");
// 读取文件的字节流
os.write(FileUtil.readBytes(uploadFile));
os.flush();
os.close();
}
/**
* 通过文件的md5查询文件
* @param md5
* @return
*/
private Files getFileByMd5(String md5) {
// 查询文件的md5是否存在
QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("md5", md5);
List<Files> filesList = fileMapper.selectList(queryWrapper);
return filesList.size() == 0 ? null : filesList.get(0);
}
// @CachePut(value = "files", key = "'frontAll'")
@PostMapping("/update")
public Result update(@RequestBody Files files) {
fileMapper.updateById(files);
flushRedis(Constants.FILES_KEY);
return Result.success();
}
@GetMapping("/detail/{id}")
public Result getById(@PathVariable Integer id) {
return Result.success(fileMapper.selectById(id));
}
//清除一条缓存,key为要清空的数据
// @CacheEvict(value="files",key="'frontAll'")
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id) {
Files files = fileMapper.selectById(id);
files.setIsDelete(true);
fileMapper.updateById(files);
flushRedis(Constants.FILES_KEY);
return Result.success();
}
@PostMapping("/del/batch")
public Result deleteBatch(@RequestBody List<Integer> ids) {
// select * from sys_file where id in (id,id,id...)
QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
queryWrapper.in("id", ids);
List<Files> files = fileMapper.selectList(queryWrapper);
for (Files file : files) {
file.setIsDelete(true);
fileMapper.updateById(file);
}
return Result.success();
}
/**
* 分页查询接口
* @param pageNum
* @param pageSize
* @param name
* @return
*/
@GetMapping("/page")
public Result findPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize,
@RequestParam(defaultValue = "") String name) {
QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
// 查询未删除的记录
queryWrapper.eq("is_delete", false);
queryWrapper.orderByDesc("id");
if (!"".equals(name)) {
queryWrapper.like("name", name);
}
return Result.success(fileMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper));
}
// 删除缓存
private void flushRedis(String key) {
stringRedisTemplate.delete(key);
}
}
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Quarter;
import com.example.demo.common.Result;
import com.example.demo.entity.User;
import com.example.demo.service.IUserService;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/echarts")
public class EchartsController {
@Autowired
private IUserService userService;
@GetMapping("/example")
public Result get() {
Map<String, Object> map = new HashMap<>();
map.put("x", CollUtil.newArrayList("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"));
map.put("y", CollUtil.newArrayList(150, 230, 224, 218, 135, 147, 260));
return Result.success(map);
}
@GetMapping("/members")
public Result members() {
List<User> list = userService.list();
int q1 = 0; //第一季度
int q2 = 0; //第二季度
int q3 = 0; //第三季度
int q4 = 0; //第四季度
for (User user : list) {
Date createTime = user.getCreateTime();
Quarter quarter = DateUtil.quarterEnum(createTime);
switch (quarter) {
case Q1: q1 += 1; break;
case Q2: q2 += 1; break;
case Q3: q3 += 1; break;
case Q4: q4 += 1; break;
default: break;
}
}
return Result.success(CollUtil.newArrayList(q1, q2, q3, q4));
}
}
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.Sign;
import com.example.demo.service.ISignService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/sign")
public class SignController {
@Resource
private ISignService signService;
// 新增或者更新
@PostMapping
public Result save(@RequestBody Sign sign) {
if (sign.getId() == null) { // 新增打卡
String today = DateUtil.today();
QueryWrapper<Sign> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user", sign.getUser());
queryWrapper.eq("time", today);
Sign one = signService.getOne(queryWrapper);
if (one != null) { // 打过卡了
return Result.error("-1", "您已打过卡");
}
sign.setTime(today);
}
signService.saveOrUpdate(sign);
return Result.success();
}
//删除
// @DeleteMapping("/{id}")
// public Result delete(@PathVariable Integer id) {
// return Result.success(userService.removeById(id));
// }
@PostMapping("/del/batch")
public Result deleteBatch(@RequestBody List<Integer> ids) {//批量删除
return Result.success(signService.removeByIds(ids));
}
//查询所有数据
@GetMapping
public Result findAll() {
return Result.success(signService.list());
}
@GetMapping("/{id}")
public Result findOne(@PathVariable Integer id) {
return Result.success(signService.getById(id));
}
@GetMapping("/page")
public Result findPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize,
@RequestParam(defaultValue = "") String user) {
QueryWrapper<Sign> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("id");
if (!"".equals(user)) {
queryWrapper.like("user", user);
}
return Result.success(signService.page(new Page<>(pageNum, pageSize), queryWrapper));
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
// 当前跨域请求最大有效时长。这里默认1天
private static final long MAX_AGE = 24 * 60 * 60;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 接口统一返回包装类
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
private String code;
private String msg;
private Object data;
public static Result success() {
return new Result(Constants.CODE_200, "", null);
}
public static Result success(Object data) {
return new Result(Constants.CODE_200, "", data);
}
public static Result error(String code, String msg) {
return new Result(code, msg, null);
}
public static Result error() {
return new Result(Constants.CODE_500, "系统错误", null);
}
}
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.demo.entity.User;
import com.example.demo.service.IUserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
@Component
public class TokenUtils {
private static IUserService staticUserService;
@Resource
private IUserService userService;
@PostConstruct
public void setUserService() {
staticUserService = userService;
}
/**
* 生成token
*
* @return
*/
public static String genToken(String userId, String sign) {
return JWT.create().withAudience(userId) // 将 user id 保存到 token 里面,作为载荷
.withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
.sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥
}
/**
* 获取当前登录的用户信息
*
* @return user对象
*/
public static User getCurrentUser() {
try {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader("token");
if (StrUtil.isNotBlank(token)) {
String userId = JWT.decode(token).getAudience().get(0);
return staticUserService.getById(Integer.valueOf(userId));
}
} catch (Exception e) {
return null;
}
return null;
}
}
五、数据库sql
CREATE TABLE `file` (
`id` int NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '文件名称',
`type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '文件类型',
`size` bigint DEFAULT NULL COMMENT '文件大小(kb)',
`url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '下载链接',
`md5` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '文件md5',
`creat_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '时间',
`is_delete` tinyint(1) DEFAULT '0' COMMENT '是否删除',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=105 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `sys_user` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '用户id',
`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_turkish_ci DEFAULT NULL COMMENT '用户名',
`nickname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_turkish_ci DEFAULT NULL COMMENT '昵称',
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_turkish_ci DEFAULT NULL COMMENT '密码',
`sex` varchar(255) COLLATE utf8mb4_turkish_ci DEFAULT NULL COMMENT '性别',
`address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_turkish_ci DEFAULT NULL COMMENT '地址',
`phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_turkish_ci DEFAULT NULL COMMENT '电话',
`email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_turkish_ci DEFAULT NULL COMMENT '邮箱',
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '用户注册的时间',
`role` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_turkish_ci DEFAULT 'USER' COMMENT '身份,1为管理员,USER为普通用户',
`avatar_url` varchar(255) COLLATE utf8mb4_turkish_ci DEFAULT NULL COMMENT '头像',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_turkish_ci COMMENT='用户列表';
CREATE TABLE `sign` (
`id` int NOT NULL AUTO_INCREMENT,
`user` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户名称',
`location` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '打卡位置',
`time` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '打卡时间',
`comment` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;