基于springboot和jwt的预约系统

1、依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>mysql</groupId>
  8. <artifactId>mysql-connector-java</artifactId>
  9. <scope>runtime</scope>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.projectlombok</groupId>
  13. <artifactId>lombok</artifactId>
  14. <optional>true</optional>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-test</artifactId>
  19. <scope>test</scope>
  20. </dependency>
  21. <!-- mybatis plus -->
  22. <dependency>
  23. <groupId>com.baomidou</groupId>
  24. <artifactId>mybatis-plus-boot-starter</artifactId>
  25. <version>3.4.3.1</version>
  26. </dependency>
  27. <dependency>
  28. <groupId>com.h2database</groupId>
  29. <artifactId>h2</artifactId>
  30. <scope>runtime</scope>
  31. </dependency>
  32. <!-- mybatis plus generator 代码生成器 -->
  33. <dependency>
  34. <groupId>com.baomidou</groupId>
  35. <artifactId>mybatis-plus-generator</artifactId>
  36. <version>3.4.1</version>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.apache.velocity</groupId>
  40. <artifactId>velocity-engine-core</artifactId>
  41. <version>2.0</version>
  42. </dependency>
  43. <!-- swagger2 -->
  44. <dependency>
  45. <groupId>io.springfox</groupId>
  46. <artifactId>springfox-swagger-ui</artifactId>
  47. <version>2.4.0</version>
  48. </dependency>
  49. <dependency>
  50. <groupId>io.springfox</groupId>
  51. <artifactId>springfox-swagger2</artifactId>
  52. <version>2.4.0</version>
  53. </dependency>
  54. <!-- hutool -->
  55. <dependency>
  56. <groupId>cn.hutool</groupId>
  57. <artifactId>hutool-all</artifactId>
  58. <version>5.7.4</version>
  59. </dependency>
  60. <dependency>
  61. <groupId>junit</groupId>
  62. <artifactId>junit</artifactId>
  63. </dependency>
  64. <!-- JWT-->
  65. <dependency>
  66. <groupId>io.jsonwebtoken</groupId>
  67. <artifactId>jjwt</artifactId>
  68. <version>0.9.1</version>
  69. </dependency>
  70. <!-- 坑!! 不引入下面依赖JWT报错-->
  71. <dependency>
  72. <groupId>javax.xml.bind</groupId>
  73. <artifactId>jaxb-api</artifactId>
  74. <version>2.3.0</version>
  75. </dependency>
  76. <dependency>
  77. <groupId>com.sun.xml.bind</groupId>
  78. <artifactId>jaxb-impl</artifactId>
  79. <version>2.3.0</version>
  80. </dependency>
  81. <dependency>
  82. <groupId>com.sun.xml.bind</groupId>
  83. <artifactId>jaxb-core</artifactId>
  84. <version>2.3.0</version>
  85. </dependency>
  86. <dependency>
  87. <groupId>javax.activation</groupId>
  88. <artifactId>activation</artifactId>
  89. <version>1.1.1</version>
  90. </dependency>
  91. <!-- easy excel-->
  92. <dependency>
  93. <groupId>com.alibaba</groupId>
  94. <artifactId>easyexcel</artifactId>
  95. <version>2.1.1</version>
  96. </dependency>
  97. <dependency>
  98. <groupId>org.apache.poi</groupId>
  99. <artifactId>poi</artifactId>
  100. <version>3.17</version>
  101. </dependency>
  102. <dependency>
  103. <groupId>org.apache.poi</groupId>
  104. <artifactId>poi-ooxml</artifactId>
  105. <version>3.17</version>
  106. </dependency>
  107. <!-- sureness鉴权 -->
  108. <dependency>
  109. <groupId>com.usthe.sureness</groupId>
  110. <artifactId>sureness-core</artifactId>
  111. <version>1.0.3</version>
  112. </dependency>
  113. </dependencies>

2、建表 使用mybatisplus代码生成器

  1. import com.baomidou.mybatisplus.generator.AutoGenerator;
  2. import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
  3. import com.baomidou.mybatisplus.generator.config.GlobalConfig;
  4. import com.baomidou.mybatisplus.generator.config.PackageConfig;
  5. import com.baomidou.mybatisplus.generator.config.StrategyConfig;
  6. import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  7. public class Main {
  8. public static void main(String[] args) {
  9. //创建AutoGenerator对象
  10. AutoGenerator autoGenerator = new AutoGenerator();
  11. //数据源
  12. DataSourceConfig dataSourceConfig = new DataSourceConfig();
  13. dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/yuyue?useUnicode=true&useSSL=false&characterEncoding=UTF-8");
  14. dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
  15. dataSourceConfig.setUsername("root");
  16. dataSourceConfig.setPassword("123456");
  17. autoGenerator.setDataSource(dataSourceConfig);
  18. //全局配置
  19. GlobalConfig globalConfig = new GlobalConfig();
  20. //System.getProperty("user.dir")工程绝对路径
  21. globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
  22. globalConfig.setAuthor("william");
  23. //创建后不打开文件
  24. globalConfig.setOpen(false);
  25. autoGenerator.setGlobalConfig(globalConfig);
  26. // 包信息
  27. PackageConfig packageConfig = new PackageConfig();
  28. packageConfig.setParent("com.william");
  29. //各层存放位置
  30. packageConfig.setController("controller");
  31. packageConfig.setService("service");
  32. packageConfig.setServiceImpl("service.impl");
  33. packageConfig.setEntity("entity");
  34. packageConfig.setMapper("mapper");
  35. autoGenerator.setPackageInfo(packageConfig);
  36. // 配置策略
  37. StrategyConfig strategyConfig = new StrategyConfig();
  38. //entity生成后自动使用lombok注解
  39. strategyConfig.setEntityLombokModel(true);
  40. //开启下划线转驼峰
  41. strategyConfig.setNaming(NamingStrategy.underline_to_camel);
  42. autoGenerator.setStrategy(strategyConfig);
  43. //开始生成
  44. autoGenerator.execute();
  45. }
  46. }

然后在启动类加上@MapperScan("com.william.mapper")

  1. # application.yml
  2. server:
  3. port: 8081
  4. spring:
  5. datasource:
  6. driver-class-name: com.mysql.cj.jdbc.Driver
  7. username: root
  8. password: 123456
  9. url: jdbc:mysql://localhost:3306/yuyue?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8
  10. # 环境设置:dev、test、prod
  11. profiles:
  12. active: dev
  13. #mybatis日志
  14. logging:
  15. level:
  16. root: warn
  17. #配置日志级别
  18. mybatis-plus:
  19. configuration:
  20. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  21. mapper-locations: classpath*:**/mapper/xml/*.xml
  22. type-enums-package: com.william.enums

3、统一结果返回

  1. public interface ResultCode {
  2. public static Integer SUCCESS = 200;
  3. public static Integer ERROR = 400;
  4. }
  1. package com.william.commonUtils;
  2. import lombok.Data;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. @Data
  6. public class R {
  7. private Boolean success;
  8. private Integer code;
  9. private String msg;
  10. private Map<String, Object> data = new HashMap<>();
  11. private R() {
  12. }
  13. public static R ok() {
  14. R r = new R();
  15. r.setCode(ResultCode.SUCCESS);
  16. r.setSuccess(true);
  17. r.setMsg("成功");
  18. return r;
  19. }
  20. public static R error() {
  21. R r = new R();
  22. r.setCode(ResultCode.ERROR);
  23. r.setSuccess(false);
  24. r.setMsg("失败");
  25. return r;
  26. }
  27. public R success(Boolean success) {
  28. this.setSuccess(success);
  29. return this;
  30. }
  31. public R message(String message) {
  32. this.setMsg(message);
  33. return this;
  34. }
  35. public R code(Integer code) {
  36. this.setCode(code);
  37. return this;
  38. }
  39. public R data(String key, Object value) {
  40. this.data.put(key, value);
  41. return this;
  42. }
  43. public R data(Map<String, Object> map) {
  44. this.setData(map);
  45. return this;
  46. }
  47. }

4、全局异常处理

  1. /**
  2. * 自定义异常类
  3. */
  4. @Data
  5. @AllArgsConstructor
  6. @NoArgsConstructor
  7. public class MyException extends RuntimeException {
  8. /**
  9. * 状态码
  10. */
  11. private Integer code;
  12. /**
  13. * 异常信息
  14. */
  15. private String msg;
  16. }
  1. /**
  2. * 异常处理
  3. */
  4. @ControllerAdvice
  5. @Slf4j
  6. public class GlobalExceptionHandler {
  7. /**
  8. * 全局异常处理
  9. *
  10. * @param e
  11. * @return
  12. */
  13. @ExceptionHandler(Exception.class)
  14. @ResponseBody
  15. public R error(Exception e) {
  16. e.printStackTrace();
  17. return R.error().message("执行了全局异常处理:");
  18. }
  19. /**
  20. * 特定异常处理
  21. *
  22. * @param e
  23. * @return
  24. */
  25. @ExceptionHandler(ArithmeticException.class)
  26. @ResponseBody
  27. public R error(ArithmeticException e) {
  28. e.printStackTrace();
  29. return R.error().message("执行了特定异常");
  30. }
  31. /**
  32. * 自定义异常处理
  33. *
  34. * @param e
  35. * @return
  36. */
  37. @ExceptionHandler(MyException.class)
  38. @ResponseBody
  39. public R error(MyException e) {
  40. e.printStackTrace();
  41. log.error(e.getMsg());
  42. return R.error().code(e.getCode()).message(e.getMsg());
  43. }
  44. }

5、通用枚举

  1. public enum AppointStatusEnum {
  2. /**
  3. * 用户登录状态的枚举类
  4. */
  5. EFFECTIVE(0,"effective"),
  6. CANCELLED(1,"cancelled"),
  7. EXPIRED(2,"expired");
  8. @EnumValue
  9. private Integer code;
  10. @JsonValue
  11. private String msg;
  12. AppointStatusEnum(Integer code, String msg) {
  13. this.code = code;
  14. this.msg = msg;
  15. }
  16. }
  1. // 修改entity中属性的类型
  2. /**
  3. * 预约状态
  4. */
  5. private AppointStatusEnum status;

6、字段自动填充

  1. @Component
  2. public class MyMetaObjectHandler implements MetaObjectHandler {
  3. @Override
  4. public void insertFill(MetaObject metaObject) {
  5. //属性名称,不是字段名称
  6. this.setFieldValByName("createTime", new Date(), metaObject);
  7. this.setFieldValByName("updateTime", new Date(), metaObject);
  8. }
  9. @Override
  10. public void updateFill(MetaObject metaObject) {
  11. this.setFieldValByName("updateTime", new Date(), metaObject);
  12. }
  13. }
  1. /**
  2. * 创建时间
  3. */
  4. @TableField(fill = FieldFill.INSERT)
  5. private Date createTime;
  6. /**
  7. * 更新时间
  8. */
  9. @TableField(fill = FieldFill.INSERT_UPDATE)
  10. private Date updateTime;

7、逻辑删除

  1. /**
  2. * 开启逻辑删除
  3. * 未删除:1 已删除:0
  4. */
  5. @TableLogic(value = "1", delval = "0")
  6. private Integer deleted;

8、编写业务代码

controller

  1. @CrossOrigin
  2. @RestController
  3. @RequestMapping("/xxx")

分页+条件+联表查询

  1. // mybatisplus分页插件配置
  2. @Configuration
  3. @MapperScan("com.william.mapper")
  4. public class MybatisPlusConfig {
  5. // 最新版
  6. @Bean
  7. public MybatisPlusInterceptor mybatisPlusInterceptor() {
  8. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
  9. interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
  10. return interceptor;
  11. }
  12. }
  1. // VO
  2. @Data
  3. public class PageQueryVO {
  4. /**
  5. * 学号
  6. */
  7. public String studentId;
  8. /**
  9. * 实验室号
  10. */
  11. public String roomId;
  12. /**
  13. * 用户名
  14. */
  15. public String userName;
  16. /**
  17. * 预约状态
  18. */
  19. public Integer status;
  20. }
  1. // controller
  2. @ApiOperation(value = "分页+条件+联表查询预约信息")
  3. @PostMapping("/getAppointPage/{curPage}/{pageSize}")
  4. public R getAppointPage(@PathVariable Integer curPage, @PathVariable Integer pageSize, @RequestBody(required = false) PageQueryVO pageQueryVO) {
  5. Page<AppointPageVO> page = appointmentService.getAppointPageVO(curPage, pageSize, pageQueryVO);
  6. if (page != null) {
  7. return R.ok().data("page", page).message("查询成功");
  8. } else {
  9. return R.error().message("查询失败");
  10. }
  11. }
  1. // service
  2. public interface IAppointmentService extends IService<Appointment> {
  3. Page<AppointPageVO> getAppointPageVO(Integer curPage, Integer pageSize, PageQueryVO pageQueryVO);
  4. }
  5. // service.impl
  6. @Service
  7. public class AppointmentServiceImpl extends ServiceImpl<AppointmentMapper, Appointment> implements IAppointmentService {
  8. @Override
  9. public Page<AppointPageVO> getAppointPageVO(Integer curPage, Integer pageSize, PageQueryVO pageQueryVO) {
  10. Page<AppointPageVO> page = new Page<>(curPage, pageSize);
  11. return baseMapper.pageList(page, pageQueryVO);
  12. }
  13. }
  1. // mapper
  2. public interface AppointmentMapper extends BaseMapper<Appointment> {
  3. Page<AppointPageVO> pageList(@Param("page") Page<AppointPageVO> page, @Param("pageQueryVO") PageQueryVO pageQueryVO);
  4. }
  1. // mapper.xml
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.william.mapper.AppointmentMapper">
  5. <select id="pageList" resultType="com.william.entity.vo.AppointPageVO">
  6. select a.id,
  7. a.room_id,
  8. a.date,
  9. a.time,
  10. a.status,
  11. u.user_name,
  12. u.student_id
  13. from appointment a, `user` u
  14. <where>
  15. a.user_id = u.user_id
  16. and u.deleted = 1
  17. <if test="pageQueryVO.studentId != null and !(pageQueryVO.studentId).equals('')">and u.student_id=#{pageQueryVO.studentId}</if>
  18. <if test="pageQueryVO.roomId != null and !(pageQueryVO.roomId).equals('')">and a.room_id=#{pageQueryVO.roomId}</if>
  19. <if test="pageQueryVO.status != null and !(pageQueryVO.status).equals('')">and a.status=#{pageQueryVO.status}</if>
  20. </where>
  21. order by a.id desc
  22. </select>
  23. </mapper>

9、swagger2

  1. @Configuration
  2. @EnableSwagger2
  3. public class SwaggerConfig {
  4. //默认文档地址为 http://localhost:port/swagger-ui.html
  5. @Bean
  6. public Docket createRestApi() {
  7. return new Docket(DocumentationType.SWAGGER_2) //指定Api类型为Swagger2
  8. .apiInfo(apiInfo()) //指定文档汇总信息
  9. .select()
  10. .apis(RequestHandlerSelectors
  11. .basePackage("com.william.controller")) //指定controller包路径
  12. .paths(PathSelectors.any()) //指定展示所有controller
  13. .build();
  14. }
  15. private ApiInfo apiInfo() {
  16. //返回一个apiinfo
  17. return new ApiInfoBuilder()
  18. .title("预约系统") //文档页标题
  19. .description("api文档") // 详细信息
  20. .version("1.0.0") // 文档版本号
  21. .termsOfServiceUrl("https://www.baidu.com") //网站地址
  22. .build();
  23. }
  24. }

10、登录功能

MD5

  1. /**
  2. * MD5非对称加密工具类
  3. */
  4. public final class MD5 {
  5. public static String encrypt(String strSrc) {
  6. try {
  7. char hexChars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
  8. '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  9. byte[] bytes = strSrc.getBytes();
  10. MessageDigest md = MessageDigest.getInstance("MD5");
  11. md.update(bytes);
  12. bytes = md.digest();
  13. int j = bytes.length;
  14. char[] chars = new char[j * 2];
  15. int k = 0;
  16. for (int i = 0; i < bytes.length; i++) {
  17. byte b = bytes[i];
  18. chars[k++] = hexChars[b >>> 4 & 0xf];
  19. chars[k++] = hexChars[b & 0xf];
  20. }
  21. return new String(chars);
  22. } catch (NoSuchAlgorithmException e) {
  23. e.printStackTrace();
  24. throw new RuntimeException("MD5加密出错!!+" + e);
  25. }
  26. }
  27. }

JwtUtil

  1. public class JwtUtil {
  2. private static String signature = "密钥";
  3. private static String tokenName = "从request.header中取token的名称";
  4. /**
  5. * 根据用户信息生成JwtToken
  6. *
  7. * @param user 用户信息
  8. * @return token
  9. */
  10. public static String createToken(User user) {
  11. JwtBuilder jwtBuilder = Jwts.builder();
  12. return jwtBuilder
  13. // header
  14. .setHeaderParam("typ", "JWT")
  15. .setHeaderParam("alg", "HS256")
  16. // payload
  17. .claim("password", user.getPassword())
  18. // userId存在Subject中
  19. .setSubject(user.getUserId().toString())
  20. // 24H过期
  21. .setExpiration(DateUtil.tomorrow())
  22. .setId(UUID.randomUUID().toString())
  23. // signature
  24. .signWith(SignatureAlgorithm.HS256, signature)
  25. .compact();
  26. }
  27. /**
  28. * 解析request.header中的token获取用户id并返回
  29. *
  30. * @param request
  31. * @return
  32. */
  33. public static String getUserIdByJwtToken(HttpServletRequest request) {
  34. String jwtToken = request.getHeader(tokenName);
  35. if (StrUtil.hasEmpty(jwtToken)) {
  36. return "";
  37. }
  38. JwtParser parser = Jwts.parser();
  39. Jws<Claims> claimsJws = parser.setSigningKey(signature).parseClaimsJws(jwtToken);
  40. Claims jwsBody = claimsJws.getBody();
  41. // 加密时Subject中存的是用户id
  42. return jwsBody.getSubject();
  43. }
  44. /**
  45. * 解析token返回body
  46. */
  47. public static Claims getBodyByJwtToken(String jwtToken) {
  48. JwtParser parser = Jwts.parser();
  49. Jws<Claims> claimsJws = parser.setSigningKey(signature).parseClaimsJws(jwtToken);
  50. // 加密时Subject中存的是用户id
  51. return claimsJws.getBody();
  52. }
  53. }

service.impl

  1. public String login(User user) {
  2. String studentId = user.getStudentId();
  3. String password = user.getPassword();
  4. // 非空校验
  5. if (StrUtil.hasEmpty(studentId) || StrUtil.hasEmpty(password)) {
  6. throw new MyException(ResultCode.ERROR, "登陆失败");
  7. }
  8. // 根据学号查数据
  9. QueryWrapper<User> wrapper = new QueryWrapper<User>();
  10. wrapper.eq("student_id", studentId);
  11. User userInBase = baseMapper.selectOne(wrapper);
  12. // 判断学号是否存在
  13. if (userInBase == null) {
  14. throw new MyException(ResultCode.ERROR, "登陆失败,用户不存在");
  15. }
  16. //判断密码是否符合 前端传来的密码通过MD5加密后和数据库中比较
  17. if (!MD5.encrypt(password).equals(userInBase.getPassword())) {
  18. throw new MyException(ResultCode.ERROR, "登录失败,密码错误");
  19. }
  20. // 登录成功,状态设为在线并返回token
  21. userInBase.setStatus(UserStatusEnum.ACTIVE);
  22. baseMapper.updateById(userInBase);
  23. return JwtUtil.createToken(userInBase);
  24. }

根据token获取用户信息

  1. @ApiOperation(value = "根据token返回用户信息和权限", notes = "token在请求中的header中携带")
  2. @GetMapping("/getUserInfo")
  3. public R getUserInfo(HttpServletRequest request) {
  4. String userId = JwtUtil.getUserIdByJwtToken(request);
  5. User user = userService.getById(userId);
  6. if (user != null) {
  7. user.setStatus(UserStatusEnum.ACTIVE);
  8. userService.updateById(user);
  9. Role role = roleService.getById(user.getRoleId());
  10. LinkedList<String> rolesList = new LinkedList<>();
  11. rolesList.add(role.getRoleKey());
  12. // 前端根据返回的roles动态生成路由
  13. return R.ok().data("userInfo", user).data("roles", rolesList).message("获取用户信息成功");
  14. } else {
  15. return R.error().message("获取用户信息失败");
  16. }
  17. }

11、使用excel导入用户

  1. @Data
  2. public class UserExcel {
  3. /**
  4. * 姓名
  5. */
  6. @ExcelProperty("姓名")
  7. private String userName;
  8. /**
  9. * 学号
  10. */
  11. @ExcelProperty("学号")
  12. private String studentId;
  13. /**
  14. * 学院
  15. */
  16. @ExcelProperty("学院")
  17. private String college;
  18. /**
  19. * 专业班级
  20. */
  21. @ExcelProperty("专业班级")
  22. private String major;
  23. }
  1. // 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去
  2. /**
  3. * easyExcel监听器
  4. * @author william
  5. */
  6. public class UploadDataListener extends AnalysisEventListener<UserExcel> {
  7. private static final Logger LOGGER = LoggerFactory.getLogger(UploadDataListener.class);
  8. /**
  9. * 每隔10条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收
  10. */
  11. private static final int BATCH_COUNT = 10;
  12. List<UserExcel> list = new ArrayList<UserExcel>();
  13. /**
  14. * 假设这个是一个DAO,当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
  15. */
  16. private IUserService userService;
  17. /**
  18. * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
  19. */
  20. public UploadDataListener(IUserService userService) {
  21. this.userService = userService;
  22. }
  23. /**
  24. * 这个每一条数据解析都会来调用
  25. */
  26. @Override
  27. public void invoke(UserExcel data, AnalysisContext context) {
  28. LOGGER.info("解析到一条数据:{}", JSONUtil.toJsonStr(data));
  29. // 判断学号是否是已经存在数据库中的
  30. String studentId = data.getStudentId();
  31. QueryWrapper<User> wrapper = new QueryWrapper<>();
  32. wrapper.eq("student_id", studentId);
  33. User one = userService.getOne(wrapper);
  34. if (one == null){
  35. list.add(data);
  36. } else {
  37. LOGGER.error("学号为{}的数据已存在!", studentId);
  38. }
  39. // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
  40. if (list.size() >= BATCH_COUNT) {
  41. saveData();
  42. // 存储完成清理 list
  43. list.clear();
  44. }
  45. }
  46. /**
  47. * 所有数据解析完成了 都会来调用
  48. *
  49. * @param context
  50. */
  51. @Override
  52. public void doAfterAllAnalysed(AnalysisContext context) {
  53. // 这里也要保存数据,确保最后遗留的数据也存储到数据库
  54. saveData();
  55. LOGGER.info("所有数据解析完成!");
  56. }
  57. /**
  58. * 加上存储数据库
  59. */
  60. private void saveData() {
  61. LOGGER.info("{}条数据,开始存储数据库!", list.size());
  62. userService.saveBatch(list);
  63. LOGGER.info("存储数据库成功!");
  64. }
  65. }
  1. @ApiOperation(value = "通过excel导入学生信息")
  2. @PostMapping("/addUserByExcel")
  3. public R addUserByExcel(MultipartFile file) throws IOException {
  4. userService.saveUsers(file, userService);
  5. return R.ok().message("导入成功");
  6. }
  1. public void saveUsers(MultipartFile file, IUserService userService) {
  2. try {
  3. //获取文件输入流
  4. InputStream inputStream = file.getInputStream();
  5. // 调用方法读取文件
  6. EasyExcel.read(inputStream, UserExcel.class, new UploadDataListener(userService)).sheet().doRead();
  7. } catch (IOException e) {
  8. e.printStackTrace();
  9. }
  10. }

12、logback日志

logback-spring.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration scan="true" scanPeriod="10 seconds">
  3. <!-- 日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果设置为WARN,则低于WARN的信息都不会输出 -->
  4. <!-- scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true -->
  5. <!-- scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。 -->
  6. <!-- debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
  7. <contextName>logback</contextName>
  8. <!-- name的值是变量的名称,value的值时变量定义的值。通过定义的值会被插入到logger上下文中。定义变量后,可以使“${}”来使用变量。 -->
  9. <property name="log.path" value="log" />
  10. <!-- 彩色日志 -->
  11. <!-- 配置格式变量:CONSOLE_LOG_PATTERN 彩色日志格式 -->
  12. <!-- magenta:洋红 -->
  13. <!-- boldMagenta:粗红-->
  14. <!-- cyan:青色 -->
  15. <!-- white:白色 -->
  16. <!-- magenta:洋红 -->
  17. <property name="CONSOLE_LOG_PATTERN"
  18. value="%yellow(%date{yyyy-MM-dd HH:mm:ss}) |%highlight(%-5level) |%blue(%thread) |%blue(%file:%line) |%green(%logger) |%cyan(%msg%n)"/>
  19. <!--输出到控制台-->
  20. <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
  21. <!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
  22. <!-- 例如:如果此处配置了INFO级别,则后面其他位置即使配置了DEBUG级别的日志,也不会被输出 -->
  23. <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
  24. <level>DEBUG</level>
  25. </filter>
  26. <encoder>
  27. <Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
  28. <!-- 设置字符集 -->
  29. <charset>UTF-8</charset>
  30. </encoder>
  31. </appender>
  32. <!--输出到文件-->
  33. <!-- 时间滚动输出 level为 INFO 日志 -->
  34. <appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
  35. <!-- 正在记录的日志文件的路径及文件名 -->
  36. <file>${log.path}/log_info.log</file>
  37. <!--日志文件输出格式-->
  38. <encoder>
  39. <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
  40. <charset>UTF-8</charset>
  41. </encoder>
  42. <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
  43. <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  44. <!-- 每天日志归档路径以及格式 -->
  45. <fileNamePattern>${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
  46. <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
  47. <maxFileSize>100MB</maxFileSize>
  48. </timeBasedFileNamingAndTriggeringPolicy>
  49. <!--日志文件保留天数-->
  50. <maxHistory>15</maxHistory>
  51. </rollingPolicy>
  52. <!-- 此日志文件只记录info级别的 -->
  53. <filter class="ch.qos.logback.classic.filter.LevelFilter">
  54. <level>INFO</level>
  55. <onMatch>ACCEPT</onMatch>
  56. <onMismatch>DENY</onMismatch>
  57. </filter>
  58. </appender>
  59. <!-- 时间滚动输出 level为 WARN 日志 -->
  60. <appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
  61. <!-- 正在记录的日志文件的路径及文件名 -->
  62. <file>${log.path}/log_warn.log</file>
  63. <!--日志文件输出格式-->
  64. <encoder>
  65. <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
  66. <charset>UTF-8</charset> <!-- 此处设置字符集 -->
  67. </encoder>
  68. <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
  69. <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  70. <fileNamePattern>${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
  71. <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
  72. <maxFileSize>100MB</maxFileSize>
  73. </timeBasedFileNamingAndTriggeringPolicy>
  74. <!--日志文件保留天数-->
  75. <maxHistory>15</maxHistory>
  76. </rollingPolicy>
  77. <!-- 此日志文件只记录warn级别的 -->
  78. <filter class="ch.qos.logback.classic.filter.LevelFilter">
  79. <level>warn</level>
  80. <onMatch>ACCEPT</onMatch>
  81. <onMismatch>DENY</onMismatch>
  82. </filter>
  83. </appender>
  84. <!-- 时间滚动输出 level为 ERROR 日志 -->
  85. <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
  86. <!-- 正在记录的日志文件的路径及文件名 -->
  87. <file>${log.path}/log_error.log</file>
  88. <!--日志文件输出格式-->
  89. <encoder>
  90. <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
  91. <charset>UTF-8</charset> <!-- 此处设置字符集 -->
  92. </encoder>
  93. <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
  94. <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  95. <fileNamePattern>${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
  96. <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
  97. <maxFileSize>100MB</maxFileSize>
  98. </timeBasedFileNamingAndTriggeringPolicy>
  99. <!--日志文件保留天数-->
  100. <maxHistory>15</maxHistory>
  101. </rollingPolicy>
  102. <!-- 此日志文件只记录ERROR级别的 -->
  103. <filter class="ch.qos.logback.classic.filter.LevelFilter">
  104. <level>ERROR</level>
  105. <onMatch>ACCEPT</onMatch>
  106. <onMismatch>DENY</onMismatch>
  107. </filter>
  108. </appender>
  109. <!--
  110. <logger>用来设置某一个包或者具体的某一个类的日志打印级别、以及指定<appender>。
  111. <logger>仅有一个name属性,
  112. 一个可选的level和一个可选的addtivity属性。
  113. name:用来指定受此logger约束的某一个包或者具体的某一个类。
  114. level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
  115. 如果未设置此属性,那么当前logger将会继承上级的级别。
  116. -->
  117. <!--
  118. 使用mybatis的时候,sql语句是debug下才会打印,而这里我们只配置了info,所以想要查看sql语句的话,有以下两种操作:
  119. 第一种把<root level="INFO">改成<root level="DEBUG">这样就会打印sql,不过这样日志那边会出现很多其他消息
  120. 第二种就是单独给mapper下目录配置DEBUG模式,代码如下,这样配置sql语句会打印,其他还是正常DEBUG级别:
  121. -->
  122. <!--开发环境:打印控制台-->
  123. <springProfile name="dev">
  124. <!--可以输出项目中的debug日志,包括mybatis的sql日志-->
  125. <logger name="com.william" level="INFO" />
  126. <!--
  127. root节点是必选节点,用来指定最基础的日志输出级别,只有一个level属性
  128. level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,默认是DEBUG
  129. 可以包含零个或多个appender元素。
  130. -->
  131. <root level="INFO">
  132. <appender-ref ref="CONSOLE" />
  133. <appender-ref ref="INFO_FILE" />
  134. <appender-ref ref="WARN_FILE" />
  135. <appender-ref ref="ERROR_FILE" />
  136. </root>
  137. </springProfile>
  138. <!--生产环境:输出到文件-->
  139. <springProfile name="pro">
  140. <root level="INFO">
  141. <appender-ref ref="CONSOLE" />
  142. <appender-ref ref="DEBUG_FILE" />
  143. <appender-ref ref="INFO_FILE" />
  144. <appender-ref ref="ERROR_FILE" />
  145. <appender-ref ref="WARN_FILE" />
  146. </root>
  147. </springProfile>
  148. </configuration>

在全局异常处理类上加

  1. @ControllerAdvice
  2. @Slf4j

13、sureness鉴权

根据角色分配资源(RESTapi)

基于springboot和jwt的预约系统 - 图1

  1. @Component
  2. public class DatabaseAccountProvider implements SurenessAccountProvider {
  3. @Resource
  4. private IUserService userService;
  5. @Override
  6. public SurenessAccount loadAccount(String appId) {
  7. return userService.loadAccount(appId);
  8. }
  9. }
  1. // userService.impl
  2. @Override
  3. public SurenessAccount loadAccount(String appId) {
  4. User user = baseMapper.selectById(appId);
  5. if (user != null) {
  6. DefaultAccount.Builder accountBuilder = DefaultAccount.builder(appId)
  7. .setPassword(user.getPassword())
  8. .setDisabledAccount(user.getDeleted() == 0);
  9. Role role = roleMapper.selectById(user.getRoleId());
  10. if (role != null) {
  11. List<String> roles = new LinkedList<>();
  12. roles.add(role.getRoleKey());
  13. accountBuilder.setOwnRoles(roles);
  14. }
  15. return accountBuilder.build();
  16. } else {
  17. return null;
  18. }
  19. }
  1. public class RefreshExpiredTokenException extends SurenessAuthenticationException {
  2. public RefreshExpiredTokenException(String message) {
  3. super(message);
  4. }
  5. }
  1. public class PasswdSubjectCreator implements SubjectCreate {
  2. private static final String jwtName = "token名字";
  3. @Override
  4. public boolean canSupportSubject(Object context) {
  5. // define which request can be access
  6. if (context instanceof HttpServletRequest) {
  7. String token = ((HttpServletRequest) context).getHeader(jwtName);
  8. return token != null;
  9. } else {
  10. return false;
  11. }
  12. }
  13. @Override
  14. public Subject createSubject(Object context) {
  15. // create PasswordSubject from request
  16. // 从jwt中拿用户名和密码做鉴权
  17. String token = ((HttpServletRequest) context).getHeader(jwtName);
  18. Claims body = JwtUtil.getBodyByJwtToken(token);
  19. String username = body.getSubject();
  20. String password = (String) body.get("password");
  21. String remoteHost = ((HttpServletRequest) context).getRemoteHost();
  22. String requestUri = ((HttpServletRequest) context).getRequestURI();
  23. String requestType = ((HttpServletRequest) context).getMethod();
  24. String targetUri = requestUri.concat("===").concat(requestType).toLowerCase();
  25. return PasswordSubject.builder(username, password)
  26. .setRemoteHost(remoteHost)
  27. .setTargetResource(targetUri)
  28. .build();
  29. }
  30. }
  1. @Configuration
  2. public class SurenessConfiguration {
  3. @Bean
  4. ProcessorManager processorManager(SurenessAccountProvider accountProvider) {
  5. // 处理器processor初始化
  6. List<Processor> processorList = new LinkedList<>();
  7. // 使用了默认的支持NoneSubject的处理器NoneProcessor
  8. NoneProcessor noneProcessor = new NoneProcessor();
  9. processorList.add(noneProcessor);
  10. // 使用了默认的支持JwtSubject的处理器JwtProcessor
  11. JwtProcessor jwtProcessor = new JwtProcessor();
  12. processorList.add(jwtProcessor);
  13. // 使用了默认的支持PasswordSubject的处理器PasswordProcessor
  14. PasswordProcessor passwordProcessor = new PasswordProcessor();
  15. // 这里注意,PasswordProcessor需要对用户账户密码验证,所以其需要账户信息提供者来给他提供想要的账户数据,
  16. // 这里的 SurenessAccountProvider accountProvider bean就是这个账户数据提供源,
  17. // 其实现bean是上面讲到的 DatabaseAccountProvider bean,即数据库实现的账户数据提供者。
  18. passwordProcessor.setAccountProvider(accountProvider);
  19. processorList.add(passwordProcessor);
  20. return new DefaultProcessorManager(processorList);
  21. }
  22. @Bean
  23. TreePathRoleMatcher pathRoleMatcher() {
  24. // 这里的PathTreeProvider databasePathTreeProvider 就是通过数据库来提供资源权限配置信息bean实例
  25. // 下面我们再实例化一个通过文件sureness.yml提供资源权限配置信息的提供者
  26. PathTreeProvider documentPathTreeProvider = new DocumentPathTreeProvider();
  27. // 下面我们再实例化一个通过注解形式@RequiresRoles @WithoutAuth提供资源权限配置信息的提供者
  28. AnnotationPathTreeProvider annotationPathTreeProvider = new AnnotationPathTreeProvider();
  29. annotationPathTreeProvider.setScanPackages(Collections.singletonList("com.william.controller"));
  30. // 设置注解扫描包路径,也就是你提供api的controller路径 annotationPathTreeProvider.setScanPackages(Collections.singletonList("com.usthe.sureness.sample.tom.controller"));
  31. // 开始初始化资源权限匹配器,我们可以把上面三种提供者都加入到匹配器中为其提供资源权限数据,匹配器中的数据就是这三个提供者提供的数据集合。t
  32. DefaultPathRoleMatcher pathRoleMatcher = new DefaultPathRoleMatcher();
  33. pathRoleMatcher.setPathTreeProviderList(Arrays.asList(
  34. documentPathTreeProvider,
  35. annotationPathTreeProvider));
  36. // 使用资源权限配置数据来建立对应的匹配树
  37. pathRoleMatcher.buildTree();
  38. return pathRoleMatcher;
  39. }
  40. @Bean
  41. SubjectFactory subjectFactory() {
  42. // 我们之前知道了可以有各种Processor来处理对应的Jwt,那这Subject怎么得到呢,就需要不同的SubjectCreator来根据请求信息创建对应的Subject对象供之后的流程使用
  43. SubjectFactory subjectFactory = new SurenessSubjectFactory();
  44. // 这里我们注册我们需要的SubjectCreator
  45. subjectFactory.registerSubjectCreator(Arrays.asList(
  46. // 注意! 强制必须首先添加一个 noSubjectCreator
  47. new NoneSubjectServletCreator(),
  48. // 注册用来创建PasswordSubject的creator
  49. new BasicSubjectServletCreator(),
  50. // 注册用来创建JwtSubject的creator
  51. new JwtSubjectServletCreator(),
  52. // 当然你可以自己实现一个自定义的creator,实现SubjectCreate接口即可
  53. new PasswdSubjectCreator()));
  54. return subjectFactory;
  55. }
  56. @Bean
  57. SurenessSecurityManager securityManager(ProcessorManager processorManager,
  58. TreePathRoleMatcher pathRoleMatcher, SubjectFactory subjectFactory) {
  59. // 我们把上面初始化好的配置bean整合到一起初始化surenessSecurityManager
  60. SurenessSecurityManager securityManager = SurenessSecurityManager.getInstance();
  61. // 设置资源权限匹配者
  62. securityManager.setPathRoleMatcher(pathRoleMatcher);
  63. // 设置subject创建工厂
  64. securityManager.setSubjectFactory(subjectFactory);
  65. // 设置处理器processor管理者
  66. securityManager.setProcessorManager(processorManager);
  67. return securityManager;
  68. }
  69. }

过滤器

在启动类中开启@ServletComponentScan

  1. @Order(1)
  2. @WebFilter(filterName = "SurenessFilter", urlPatterns = "/*", asyncSupported = true)
  3. public class SurenessFilter implements Filter {
  4. /** logger **/
  5. private static final Logger logger = LoggerFactory.getLogger(SurenessFilter.class);
  6. @Override
  7. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
  8. try {
  9. SubjectSum subject = SurenessSecurityManager.getInstance().checkIn(servletRequest);
  10. // You can consider using SurenessContextHolder to bind subject in threadLocal
  11. // if bind, please remove it when end
  12. if (subject != null) {
  13. SurenessContextHolder.bindSubject(subject);
  14. }
  15. } catch (IncorrectCredentialsException | UnknownAccountException | ExpiredCredentialsException e1) {
  16. logger.debug("this request account info is illegal, {}", e1.getMessage());
  17. responseWrite(ResponseEntity
  18. .status(HttpStatus.UNAUTHORIZED).body("Username or password is incorrect or expired"), servletResponse);
  19. return;
  20. } catch (DisabledAccountException | ExcessiveAttemptsException e2 ) {
  21. logger.debug("the account is disabled, {}", e2.getMessage());
  22. responseWrite(ResponseEntity
  23. .status(HttpStatus.UNAUTHORIZED).body("Account is disabled"), servletResponse);
  24. return;
  25. } catch (RefreshExpiredTokenException e4) {
  26. logger.debug("this account credential token is expired, return refresh value");
  27. Map<String, String> refreshTokenMap = Collections.singletonMap("refresh-token", e4.getMessage());
  28. responseWrite(ResponseEntity
  29. .status(HttpStatus.UNAUTHORIZED).body(refreshTokenMap), servletResponse);
  30. return;
  31. } catch (UnauthorizedException e5) {
  32. logger.debug("this account can not access this resource, {}", e5.getMessage());
  33. responseWrite(ResponseEntity
  34. .status(HttpStatus.FORBIDDEN)
  35. .body("This account has no permission to access this resource"), servletResponse);
  36. return;
  37. } catch (RuntimeException e) {
  38. logger.error("other exception happen: ", e);
  39. responseWrite(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(),
  40. servletResponse);
  41. return;
  42. }
  43. try {
  44. // if ok, doFilter and add subject in request
  45. filterChain.doFilter(servletRequest, servletResponse);
  46. } finally {
  47. SurenessContextHolder.clear();
  48. }
  49. }
  50. /**
  51. * write response json data
  52. * @param content content
  53. * @param response response
  54. */
  55. private void responseWrite(ResponseEntity<?> content, ServletResponse response) {
  56. response.setCharacterEncoding("UTF-8");
  57. response.setContentType("application/json;charset=utf-8");
  58. ((HttpServletResponse)response).setStatus(content.getStatusCodeValue());
  59. content.getHeaders().forEach((key, value) ->
  60. ((HttpServletResponse) response).addHeader(key, value.get(0)));
  61. try (PrintWriter printWriter = response.getWriter()) {
  62. if (content.getBody() != null) {
  63. if (content.getBody() instanceof String) {
  64. printWriter.write(content.getBody().toString());
  65. } else {
  66. ObjectMapper objectMapper = new ObjectMapper();
  67. printWriter.write(objectMapper.writeValueAsString(content.getBody()));
  68. }
  69. } else {
  70. printWriter.flush();
  71. }
  72. } catch (IOException e) {
  73. logger.error("responseWrite response error: ", e);
  74. }
  75. }
  76. }

sureness.yml

  1. ## -- sureness.yml document dataSource-- ##
  2. # load api resource which need be protected, config role who can access these resource.
  3. # resources that are not configured are also authenticated and protected by default, but not authorized
  4. # eg: /api/v2/host===post===[role2,role3,role4] means /api/v2/host===post can be access by role2,role3,role4
  5. # eg: /api/v1/getSource3===get===[] means /api/v1/getSource3===get can not be access by any role
  6. resourceRole:
  7. - /room/editRoomInfoById===post===[admin,teacher]
  8. - /room/getRoomList===get===[admin,teacher]
  9. - /user/addUserByExcel===post===[admin,teacher]
  10. - /user/changePassword===post===[student]
  11. - /user/changePasswordById===post===[admin,teacher]
  12. - /user/editUserInfo===post===[admin,teacher]
  13. - /user/getUserList/**===post===[admin,teacher]
  14. - /user/logout===post===[admin,teacher,student]
  15. - /appointment/cancelAppointmentById/**===delete===[admin,teacher,student]
  16. - /appointment/doAppointment===post===[admin,teacher,student]
  17. - /appointment/getAppointPage/**===post===[admin,teacher]
  18. # load api resource which do not need be protected, means them need be excluded.
  19. # these api resource can be access by everyone
  20. excludedResource:
  21. - /user/login===post
  22. - /room/getRoomInfoById/**===get
  23. - /user/getUserInfo===get
  24. - /user/getUserInfoById/*===get
  25. - /appointment/getHistory/**===get
  26. - /appointment/getRecent/**===get
  27. - /**/*.css===get
  28. - /**/*.ico===get
  29. - /**/*.png===get
  30. - /swagger-ui.html===*
  31. - /swagger/**===*
  32. - /swagger-resources/**===*
  33. - /v2/**===*
  34. - /webjars/**===*
  35. - /configuration/**===*
  36. st===[role2,role3,role4] means /api/v2/host===post can be access by role2,role3,role4
  37. # eg: /api/v1/getSource3===get===[] means /api/v1/getSource3===get can not be access by any role
  38. resourceRole:
  39. - /room/editRoomInfoById===post===[admin,teacher]
  40. - /room/getRoomList===get===[admin,teacher]
  41. - /user/addUserByExcel===post===[admin,teacher]
  42. - /user/changePassword===post===[student]
  43. - /user/changePasswordById===post===[admin,teacher]
  44. - /user/editUserInfo===post===[admin,teacher]
  45. - /user/getUserList/**===post===[admin,teacher]
  46. - /user/logout===post===[admin,teacher,student]
  47. - /appointment/cancelAppointmentById/**===delete===[admin,teacher,student]
  48. - /appointment/doAppointment===post===[admin,teacher,student]
  49. - /appointment/getAppointPage/**===post===[admin,teacher]
  50. # load api resource which do not need be protected, means them need be excluded.
  51. # these api resource can be access by everyone
  52. excludedResource:
  53. - /user/login===post
  54. - /room/getRoomInfoById/**===get
  55. - /user/getUserInfo===get
  56. - /user/getUserInfoById/*===get
  57. - /appointment/getHistory/**===get
  58. - /appointment/getRecent/**===get
  59. - /**/*.css===get
  60. - /**/*.ico===get
  61. - /**/*.png===get
  62. - /swagger-ui.html===*
  63. - /swagger/**===*
  64. - /swagger-resources/**===*
  65. - /v2/**===*
  66. - /webjars/**===*
  67. - /configuration/**===*