注释了后端的lsgwr.exam文件包

feature/lxh
李炫好 2 months ago
parent 218783f26b
commit 9d444f55a3

@ -16,15 +16,22 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Slf4j @Slf4j
public class CORSConf { public class CORSConf {
// 创建一个 WebMvcConfigurer Bean
@Bean @Bean
public WebMvcConfigurer corsConfigurer() { public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() { return new WebMvcConfigurer() {
// 重写 addCorsMappings 方法
@Override @Override
public void addCorsMappings(CorsRegistry registry) { public void addCorsMappings(CorsRegistry registry) {
// 记录初始化 CORSConfiguration 配置
log.info("初始化 CORSConfiguration 配置"); log.info("初始化 CORSConfiguration 配置");
// 添加映射
registry.addMapping("/**") registry.addMapping("/**")
// 允许所有请求头
.allowedHeaders("*") .allowedHeaders("*")
// 允许所有请求方法
.allowedMethods("*") .allowedMethods("*")
// 允许所有请求来源
.allowedOrigins("*"); .allowedOrigins("*");
} }
}; };

@ -15,9 +15,11 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration @Configuration
public class IntercepterConfig implements WebMvcConfigurer { public class IntercepterConfig implements WebMvcConfigurer {
// 注入LoginInterceptor
@Autowired @Autowired
private LoginInterceptor loginInterceptor; private LoginInterceptor loginInterceptor;
// 添加拦截器
@Override @Override
public void addInterceptors(InterceptorRegistry registry) { public void addInterceptors(InterceptorRegistry registry) {
// 拦截user下的api // 拦截user下的api

@ -9,10 +9,14 @@ import org.springframework.http.HttpStatus;
@Configuration @Configuration
public class ServletConfig { public class ServletConfig {
// 创建一个WebServerFactoryCustomizer bean用于自定义WebServerFactory
@Bean @Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() { public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
// 返回一个lambda表达式用于自定义WebServerFactory
return factory -> { return factory -> {
// 创建一个ErrorPage对象用于处理404错误
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/"); ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/");
// 将ErrorPage对象添加到WebServerFactory中
factory.addErrorPages(error404Page); factory.addErrorPages(error404Page);
}; };
} }

@ -29,32 +29,48 @@ public class Swagger2Config {
@Bean @Bean
public Docket api() { public Docket api() {
// 创建一个参数构建器
ParameterBuilder ticketPar = new ParameterBuilder(); ParameterBuilder ticketPar = new ParameterBuilder();
// 创建一个参数集合
List<Parameter> pars = new ArrayList<>(); List<Parameter> pars = new ArrayList<>();
// 设置参数名
ticketPar.name("Access-Token").description("Rest接口权限认证token,无需鉴权可为空") ticketPar.name("Access-Token").description("Rest接口权限认证token,无需鉴权可为空")
// 设置参数类型
.modelRef(new ModelRef("string")).parameterType("header") .modelRef(new ModelRef("string")).parameterType("header")
//header中的ticket参数非必填传空也可以 // header中的ticket参数非必填传空也可以
.required(false).build(); .required(false).build();
//根据每个方法名也知道当前方法在设置什么参数 // 根据每个方法名也知道当前方法在设置什么参数
pars.add(ticketPar.build()); pars.add(ticketPar.build());
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
// 设置文档信息
.apiInfo(apiInfo()) .apiInfo(apiInfo())
// 选择要扫描的接口
.select() .select()
// 自行修改为自己的包路径 // 自行修改为自己的包路径
.apis(RequestHandlerSelectors.basePackage("lsgwr")) .apis(RequestHandlerSelectors.basePackage("lsgwr"))
// 选择所有的路径
.paths(PathSelectors.any()) .paths(PathSelectors.any())
// 构建Docket
.build() .build()
// 设置全局参数
.globalOperationParameters(pars); .globalOperationParameters(pars);
} }
private ApiInfo apiInfo() { private ApiInfo apiInfo() {
// 创建ApiInfo对象
return new ApiInfoBuilder() return new ApiInfoBuilder()
// 设置API标题
.title("online exam by springboot") .title("online exam by springboot")
// 设置API描述
.description("在线考试系统 by 梁山广 at 2021") .description("在线考试系统 by 梁山广 at 2021")
// 设置API服务条款URL
.termsOfServiceUrl("https://github.com/19920625lsg/spring-boot-online-exam") .termsOfServiceUrl("https://github.com/19920625lsg/spring-boot-online-exam")
// 设置API版本
.version("2.0") .version("2.0")
// 设置API联系人信息
.contact(new Contact("liangshanguang", "https://github.com/lsgwr/spring-boot-online-exam", "liangshanguang2@gmail.com")) .contact(new Contact("liangshanguang", "https://github.com/lsgwr/spring-boot-online-exam", "liangshanguang2@gmail.com"))
// 构建ApiInfo对象
.build(); .build();
} }
} }

@ -29,7 +29,10 @@ public class ExamController {
private ExamService examService; private ExamService examService;
/** /**
* @Description: 使examService.getQuestionAll(),ResultVO, * @Description: 使examService.getQuestionAll(),
*
* ResultVO,
*
* &#064;ApiOperationAPI,SwaggerUI * &#064;ApiOperationAPI,SwaggerUI
*/ */
@GetMapping("/question/all") @GetMapping("/question/all")
@ -73,10 +76,20 @@ ResultVO<List<QuestionVo>> getQuestionAll() {
/** /**
* *
* @Description: QuestionCreateSimplifyVoQuestionCreateVoID使examService.questionCreate() * @Description: QuestionCreateSimplifyVo
* @param questionCreateSimplifyVo QuestionCreateSimplifyVo * QuestionCreateVoID
*
* 使examService.questionCreate()
*
* @param questionCreateSimplifyVo
*
* QuestionCreateSimplifyVo
*
* @param request HttpServletRequestID * @param request HttpServletRequestID
*
* @return ResultVO<String> * @return ResultVO<String>
*
*
*/ */
@PostMapping("/question/create") @PostMapping("/question/create")
@ApiOperation("创建问题") @ApiOperation("创建问题")
@ -103,7 +116,10 @@ ResultVO<List<QuestionVo>> getQuestionAll() {
} }
/** /**
* @Description: ,使examService.getSelections()ResultVO * @Description: ,
*
* 使examService.getSelections()ResultVO
*
* @return ResultVO<QuestionAllVo> * @return ResultVO<QuestionAllVo>
*/ */
@GetMapping("/question/selection") @GetMapping("/question/selection")
@ -221,7 +237,10 @@ ResultVO<QuestionSelectionVo> getSelections() {
/** /**
* @Description: * @Description:
* @return ResultVO<List<ExamCardVo>> *
* @return ResultVO<List<ExamCardVo>>
*
*
*/ */
@GetMapping("/card/list") @GetMapping("/card/list")
@ApiOperation("获取考试列表,适配前端卡片列表") @ApiOperation("获取考试列表,适配前端卡片列表")
@ -244,7 +263,9 @@ ResultVO<QuestionSelectionVo> getSelections() {
/** /**
* @Description: id * @Description: id
*
* @param id id * @param id id
*
* @return ResultVO<ExamDetailVo> * @return ResultVO<ExamDetailVo>
*/ */
@GetMapping("/detail/{id}") @GetMapping("/detail/{id}")
@ -262,9 +283,13 @@ ResultVO<QuestionSelectionVo> getSelections() {
} }
/** /**
* @Description: 使examService.finishExam,ResultVO, * @Description: 使examService.finishExam,
*
* ResultVO,
* @param examId id * @param examId id
*
* @param answersMap * @param answersMap
*
* @param request id * @param request id
* @return * @return
*/ */
@ -290,9 +315,14 @@ ResultVO<QuestionSelectionVo> getSelections() {
} }
/** /**
* @Description: 使examService.getExamRecordList,ResultVO, * @Description: 使examService.getExamRecordList,
* ResultVO,
*
* @param request id * @param request id
* @return ResultVO<List<ExamRecordVo>> ResultVOResultVO *
* @return ResultVO<List<ExamRecordVo>>
*
* ResultVOResultVO
*/ */
@GetMapping("/record/list") @GetMapping("/record/list")
@ApiOperation("获取当前用户的考试记录") @ApiOperation("获取当前用户的考试记录")
@ -313,9 +343,16 @@ ResultVO<QuestionSelectionVo> getSelections() {
} }
/** /**
* @Description: 使examService.getExamRecordDetail,ResultVO,id * @Description: 使examService.getExamRecordDetail,
*
* ResultVO,id
*
* @param recordId id * @param recordId id
* @return ResultVO<RecordDetailVo> ResultVOResultVO *
* @return ResultVO<RecordDetailVo>
* ResultVO
*
* ResultVO
*/ */
@GetMapping("/record/detail/{recordId}") @GetMapping("/record/detail/{recordId}")
@ApiOperation("根据考试记录id获取考试记录详情") @ApiOperation("根据考试记录id获取考试记录详情")

@ -15,13 +15,22 @@ import org.springframework.web.multipart.MultipartFile;
import java.io.IOException; import java.io.IOException;
/*********************************************************** /***********************************************************
*
* @note : ,SwaggerSwaggerUI * @note : ,SwaggerSwaggerUI
* *
*
*
* @author : 广 * @author : 广
* * AjaxResponseEntity *
* * * * Ajax
* * 1. - `MultipartFile` *
* * 2. - `MultipartFile []` * ResponseEntity
* *
*
* * 1.
* - `MultipartFile`
* * 2.
* - `MultipartFile []`
* * 3. - `@ModelAttribute` * * 3. - `@ModelAttribute`
* @version : V1.0 at 2018/7/16 20:43 * @version : V1.0 at 2018/7/16 20:43
***********************************************************/ ***********************************************************/
@ -32,10 +41,14 @@ import java.io.IOException;
public class UploadDownloadController { public class UploadDownloadController {
// @Autowired // @Autowired
// AITestConfig aiTestConfig; // AITestConfig aiTestConfig;
// //
// @PostMapping("/upload/single") // @PostMapping("/upload/single")
// @ApiOperation("单文件上传") // @ApiOperation("单文件上传")
// public String uploadFile(@RequestParam("file") MultipartFile uploadfile) { // public String uploadFile(@RequestParam("file") MultipartFile uploadfile) {
// return FileTransUtil.uploadFile(uploadfile, "/root/" + File.separator + uploadfile.getOriginalFilename()); // return FileTransUtil.uploadFile(uploadfile, "/root/" + File.separator + uploadfile.getOriginalFilename());
// } // }

@ -10,9 +10,21 @@ import lombok.Data;
@Data @Data
public class RegisterDTO { public class RegisterDTO {
/**
*
*/
private String email; private String email;
/**
*
*/
private String password; private String password;
/**
*
*/
private String password2; private String password2;
/**
*
*/
private String mobile; private String mobile;
/** /**
* *

@ -15,13 +15,18 @@ import javax.persistence.Id;
@Data @Data
@Entity @Entity
public class Action { public class Action {
// 定义一个主键
@Id @Id
// 自动生成主键
@GeneratedValue @GeneratedValue
private Integer actionId; private Integer actionId;
// 定义一个动作名称
private String actionName; private String actionName;
// 定义一个动作描述
private String actionDescription; private String actionDescription;
// 定义一个默认选中状态
private Boolean defaultCheck; private Boolean defaultCheck;
} }

@ -20,36 +20,62 @@ import java.util.Date;
@Data @Data
@DynamicUpdate @DynamicUpdate
public class Exam { public class Exam {
// 考试ID
@Id @Id
private String examId; private String examId;
// 考试名称
private String examName; private String examName;
// 考试头像
private String examAvatar; private String examAvatar;
// 考试描述
private String examDescription; private String examDescription;
// 考试问题ID
private String examQuestionIds; private String examQuestionIds;
// 考试单选题ID
private String examQuestionIdsRadio; private String examQuestionIdsRadio;
// 考试多选题ID
private String examQuestionIdsCheck; private String examQuestionIdsCheck;
// 考试判断题ID
private String examQuestionIdsJudge; private String examQuestionIdsJudge;
// 考试总分
private Integer examScore; private Integer examScore;
// 考试单选题总分
private Integer examScoreRadio; private Integer examScoreRadio;
// 考试多选题总分
private Integer examScoreCheck; private Integer examScoreCheck;
// 考试判断题总分
private Integer examScoreJudge; private Integer examScoreJudge;
// 考试创建者ID
private String examCreatorId; private String examCreatorId;
// 考试时间限制
private Integer examTimeLimit; private Integer examTimeLimit;
// 考试开始时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date examStartDate; private Date examStartDate;
// 考试结束时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date examEndDate; private Date examEndDate;
/** /**
*
*
* , Java * , Java
*
*
*/ */
// 创建时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime; private Date createTime;
/** /**
* Java * Java
* @DynamicUpdate *
*
* @DynamicUpdate
*
*
*/ */
// 更新时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime; private Date updateTime;
} }

@ -18,39 +18,58 @@ import java.util.Date;
@Entity @Entity
public class ExamRecord { public class ExamRecord {
/** /**
*
*
* *
*
*
*/ */
@Id @Id
private String examRecordId; private String examRecordId;
/** /**
*
* id * id
*
*/ */
private String examId; private String examId;
/** /**
* (_-), *
* (_
*
* -),
*/ */
private String answerOptionIds; private String answerOptionIds;
/** /**
*
* userid * userid
*
*/ */
private String examJoinerId; private String examJoinerId;
/** /**
*
* *
*
*/ */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date examJoinDate; private Date examJoinDate;
/** /**
*
* () * ()
*
*/ */
private Integer examTimeCost; private Integer examTimeCost;
/** /**
*
* *
*
*/ */
private Integer examJoinScore; private Integer examJoinScore;
/** /**
*
* *
*
*/ */
private Integer examResultLevel; private Integer examResultLevel;
} }

@ -16,9 +16,12 @@ import javax.persistence.Id;
@Data @Data
@Entity @Entity
public class ExamRecordLevel { public class ExamRecordLevel {
// 考试记录等级ID
@Id @Id
@GeneratedValue @GeneratedValue
private Integer examRecordLevelId; private Integer examRecordLevelId;
// 考试记录等级名称
private String examRecordLevelName; private String examRecordLevelName;
// 考试记录等级描述
private String examRecordLevelDescription; private String examRecordLevelDescription;
} }

@ -15,13 +15,17 @@ import javax.persistence.Id;
@Data @Data
@Entity @Entity
public class Page { public class Page {
// 定义一个页面ID使用@Id注解表示该字段为主键使用@GeneratedValue注解表示该字段自动生成
@Id @Id
@GeneratedValue @GeneratedValue
private Integer pageId; private Integer pageId;
// 定义一个页面名称
private String pageName; private String pageName;
// 定义一个页面描述
private String pageDescription; private String pageDescription;
// 定义一个动作ID用于存储页面上的动作
private String actionIds; private String actionIds;
} }

@ -19,21 +19,32 @@ import java.util.Date;
@Entity @Entity
@DynamicUpdate @DynamicUpdate
public class Question { public class Question {
// 问题ID
@Id @Id
private String questionId; private String questionId;
// 问题名称
private String questionName; private String questionName;
// 问题分数
private Integer questionScore; private Integer questionScore;
// 问题创建者ID
private String questionCreatorId; private String questionCreatorId;
// 问题等级ID
private Integer questionLevelId; private Integer questionLevelId;
// 问题类型ID
private Integer questionTypeId; private Integer questionTypeId;
// 问题分类ID
private Integer questionCategoryId; private Integer questionCategoryId;
// 问题描述
private String questionDescription; private String questionDescription;
// 问题选项ID
private String questionOptionIds; private String questionOptionIds;
// 问题答案选项ID
private String questionAnswerOptionIds; private String questionAnswerOptionIds;
/** /**
* , Java * , Java
*/ */
// 创建时间格式化
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime; private Date createTime;
@ -41,6 +52,7 @@ public class Question {
* Java * Java
* @DynamicUpdate * @DynamicUpdate
*/ */
// 更新时间格式化
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime; private Date updateTime;
} }

@ -18,14 +18,19 @@ import javax.persistence.Id;
@Entity @Entity
public class QuestionCategory { public class QuestionCategory {
// 主键
@Id @Id
// 自动生成主键
@GeneratedValue @GeneratedValue
// 将该字段映射到JSON中的id字段
@JsonProperty("id") @JsonProperty("id")
private Integer questionCategoryId; private Integer questionCategoryId;
// 将该字段映射到JSON中的name字段
@JsonProperty("name") @JsonProperty("name")
private String questionCategoryName; private String questionCategoryName;
// 将该字段映射到JSON中的description字段
@JsonProperty("description") @JsonProperty("description")
private String questionCategoryDescription; private String questionCategoryDescription;
} }

@ -17,8 +17,10 @@ import javax.persistence.Id;
@Entity @Entity
@Data @Data
public class QuestionLevel { public class QuestionLevel {
// 定义实体类,表示问题等级
@Id @Id
@GeneratedValue @GeneratedValue
// 定义主键,自动生成
@JsonProperty("id") @JsonProperty("id")
private Integer questionLevelId; private Integer questionLevelId;

@ -15,8 +15,11 @@ import javax.persistence.Id;
@Data @Data
@Entity @Entity
public class QuestionOption { public class QuestionOption {
// 定义问题选项的ID
@Id @Id
private String questionOptionId; private String questionOptionId;
// 定义问题选项的内容
private String questionOptionContent; private String questionOptionContent;
// 定义问题选项的描述
private String questionOptionDescription; private String questionOptionDescription;
} }

@ -17,14 +17,19 @@ import javax.persistence.Id;
@Data @Data
@Entity @Entity
public class QuestionType { public class QuestionType {
// 主键
@Id @Id
// 自动生成主键
@GeneratedValue @GeneratedValue
// 将该字段映射到JSON中的id字段
@JsonProperty("id") @JsonProperty("id")
private Integer questionTypeId; private Integer questionTypeId;
// 将该字段映射到JSON中的name字段
@JsonProperty("name") @JsonProperty("name")
private String questionTypeName; private String questionTypeName;
// 将该字段映射到JSON中的description字段
@JsonProperty("description") @JsonProperty("description")
private String questionTypeDescription; private String questionTypeDescription;
} }

@ -16,14 +16,22 @@ import javax.persistence.Id;
@Data @Data
@Entity @Entity
public class Role { public class Role {
// 角色ID
@Id @Id
@GeneratedValue @GeneratedValue
private Integer roleId; private Integer roleId;
// 角色名称
private String roleName; private String roleName;
// 角色描述
private String roleDescription; private String roleDescription;
// 角色详情
private String roleDetail; private String roleDetail;
/** /**
*
*
* 访(-) * 访(-)
*
*
*/ */
private String rolePageIds; private String rolePageIds;
} }

@ -19,27 +19,47 @@ import java.util.Date;
@Entity @Entity
@DynamicUpdate @DynamicUpdate
public class User { public class User {
// 用户ID
@Id @Id
private String userId; private String userId;
// 用户名
private String userUsername; private String userUsername;
// 用户昵称
private String userNickname; private String userNickname;
// 用户密码
private String userPassword; private String userPassword;
// 用户角色ID
private Integer userRoleId; private Integer userRoleId;
// 用户头像
private String userAvatar; private String userAvatar;
// 用户描述
private String userDescription; private String userDescription;
// 用户邮箱
private String userEmail; private String userEmail;
// 用户电话
private String userPhone; private String userPhone;
/** /**
* , Java *
*
* ,
*
* Java
*
*
*/ */
// 创建时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime; private Date createTime;
/** /**
* Java *
* @DynamicUpdate * Java
* @DynamicUpdate
*
*
*/ */
// 更新时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime; private Date updateTime;
} }

@ -4,12 +4,19 @@ import lombok.Getter;
/** /**
* *
*
*
* @author liangshanguang * @author liangshanguang
*
*
*/ */
@Getter @Getter
public enum LoginTypeEnum { public enum LoginTypeEnum {
/** /**
*
* 12 * 12
*
*
*/ */
USERNAME(1, "用户名"), USERNAME(1, "用户名"),
EMAIL(2, "邮箱"); EMAIL(2, "邮箱");

@ -17,11 +17,14 @@ public enum ResultEnum {
ORDER_UPDATE_ERR(15, "考试更新异常"), ORDER_UPDATE_ERR(15, "考试更新异常"),
ORDER_DETAIL_EMPTY(16, "用户详情为空"); ORDER_DETAIL_EMPTY(16, "用户详情为空");
// 构造方法,用于初始化错误码和错误信息
ResultEnum(Integer code, String message) { ResultEnum(Integer code, String message) {
this.code = code; this.code = code;
this.message = message; this.message = message;
} }
// 错误码
private Integer code; private Integer code;
// 错误信息
private String message; private String message;
} }

@ -12,7 +12,11 @@ import lombok.Getter;
public enum RoleEnum { public enum RoleEnum {
/** /**
*
*
* role * role
*
*
*/ */
ADMIN(1, "管理员"), ADMIN(1, "管理员"),
TEACHER(2, "教师"), TEACHER(2, "教师"),

@ -11,15 +11,22 @@ import lombok.Getter;
@Getter @Getter
public class ExamException extends RuntimeException { public class ExamException extends RuntimeException {
// 定义异常代码
private Integer code; private Integer code;
// 构造函数传入ResultEnum枚举类型
public ExamException(ResultEnum resultEnum) { public ExamException(ResultEnum resultEnum) {
// 调用父类构造函数传入ResultEnum枚举类型的消息
super(resultEnum.getMessage()); super(resultEnum.getMessage());
// 将ResultEnum枚举类型的代码赋值给异常代码
this.code = resultEnum.getCode(); this.code = resultEnum.getCode();
} }
// 构造函数,传入异常代码和消息
public ExamException( Integer code, String message) { public ExamException( Integer code, String message) {
// 调用父类构造函数,传入消息
super(message); super(message);
// 将传入的异常代码赋值给异常代码
this.code = code; this.code = code;
} }
} }

@ -27,44 +27,67 @@ import java.io.PrintWriter;
public class LoginInterceptor implements HandlerInterceptor { public class LoginInterceptor implements HandlerInterceptor {
/** /**
*
* @Component使pplication.yml * @Component使pplication.yml
*
*
*/ */
@Value("${interceptors.auth-ignore-uris}") @Value("${interceptors.auth-ignore-uris}")
private String authIgnoreUris; private String authIgnoreUris;
/** /**
*
*
* controller * controller
* *
*
* @param request * @param request
*
* @param response * @param response
*
* @param handler * @param handler
*
* @return * @return
*
* @throws Exception * @throws Exception
*
*/ */
@Override @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 打印进入拦截器
System.out.println("进入拦截器啦!"); System.out.println("进入拦截器啦!");
// 获取请求的URI
String uri = request.getRequestURI(); String uri = request.getRequestURI();
// 打印URI
System.out.println(uri); System.out.println(uri);
// 打印无需拦截的接口路径
System.out.println("无需拦截的接口路径:" + authIgnoreUris); System.out.println("无需拦截的接口路径:" + authIgnoreUris);
// 将无需拦截的接口路径分割成数组
String[] authIgnoreUriArr = authIgnoreUris.split(","); String[] authIgnoreUriArr = authIgnoreUris.split(",");
// 登录和注册接口不需要进行token拦截和校验 // 登录和注册接口不需要进行token拦截和校验
for (String authIgnoreUri : authIgnoreUriArr) { for (String authIgnoreUri : authIgnoreUriArr) {
// 如果请求的URI在无需拦截的接口路径中则直接返回true
if (authIgnoreUri.equals(uri)) { if (authIgnoreUri.equals(uri)) {
return true; return true;
} }
} }
// 注意要和前端适配Access-Token属性前端会在登陆后的每个接口请求头加Access-Token属性 // 注意要和前端适配Access-Token属性前端会在登陆后的每个接口请求头加Access-Token属性
// 获取请求头中的token
String token = request.getHeader("Access-Token"); String token = request.getHeader("Access-Token");
// 如果token不在header中则可能在参数中
if (token == null) { if (token == null) {
// token不在header中时也可能在参数中(RequestParam) // 从参数中获取token
token = request.getParameter("token"); token = request.getParameter("token");
} }
// 如果token不为空
if (token != null) { if (token != null) {
// 请求中是携带参数的 // 请求中是携带参数的
// 校验token
Claims claims = JwtUtils.checkJWT(token); Claims claims = JwtUtils.checkJWT(token);
// 如果token校验失败
if (claims == null) { if (claims == null) {
// 返回null说明用户篡改了token导致校验失败 // 返回null说明用户篡改了token导致校验失败
// 返回错误信息
sendJsonMessage(response, JsonData.buildError("token无效请重新登录")); sendJsonMessage(response, JsonData.buildError("token无效请重新登录"));
return false; return false;
} }
@ -73,10 +96,12 @@ public class LoginInterceptor implements HandlerInterceptor {
// 用户名 // 用户名
String username = (String) claims.get("username"); String username = (String) claims.get("username");
// 把这两个参数放到请求中从而可以在controller中获取到不需要在controller中在用Jwt解密了,request.getAttribute("属性名")即可获取 // 把这两个参数放到请求中从而可以在controller中获取到不需要在controller中在用Jwt解密了,request.getAttribute("属性名")即可获取
// 将用户id和用户名放到请求中
request.setAttribute("user_id", id); request.setAttribute("user_id", id);
request.setAttribute("username", username); request.setAttribute("username", username);
return true; return true;
} }
// 如果token为空则返回错误信息
sendJsonMessage(response, JsonData.buildError("token为null,请先登录!")); sendJsonMessage(response, JsonData.buildError("token为null,请先登录!"));
return false; return false;
} }
@ -88,12 +113,19 @@ public class LoginInterceptor implements HandlerInterceptor {
* @param obj * @param obj
* @throws Exception * @throws Exception
*/ */
public static void sendJsonMessage(HttpServletResponse response, Object obj) throws Exception { // 发送JSON消息
public static void sendJsonMessage(HttpServletResponse response, Object obj) throws Exception {
// 创建Gson对象
Gson g = new Gson(); Gson g = new Gson();
// 设置响应内容类型为JSON
response.setContentType("application/json; charset=utf-8"); response.setContentType("application/json; charset=utf-8");
// 获取响应的PrintWriter对象
PrintWriter writer = response.getWriter(); PrintWriter writer = response.getWriter();
// 将对象转换为JSON字符串并写入响应
writer.print(g.toJson(obj)); writer.print(g.toJson(obj));
// 关闭PrintWriter对象
writer.close(); writer.close();
// 刷新响应缓冲区
response.flushBuffer(); response.flushBuffer();
} }
} }

@ -13,5 +13,6 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
public class DownloadQo { public class DownloadQo {
// 下载路径
String path; String path;
} }

@ -15,15 +15,21 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor @NoArgsConstructor
public class LoginQo { public class LoginQo {
/** /**
*
* 12 * 12
*
*/ */
private Integer loginType; private Integer loginType;
/** /**
*
* / * /
*
*/ */
private String userInfo; private String userInfo;
/** /**
*
* *
*
*/ */
private String password; private String password;
} }

@ -17,11 +17,19 @@ import org.springframework.web.multipart.MultipartFile;
@NoArgsConstructor @NoArgsConstructor
public class UploadModel { public class UploadModel {
/** /**
*
*
* *
*
*
*/ */
private MultipartFile[] files; private MultipartFile[] files;
/** /**
*
*
* *
*
*
*/ */
private String dir; private String dir;
} }

@ -17,11 +17,19 @@ import org.springframework.web.multipart.MultipartFile;
@NoArgsConstructor @NoArgsConstructor
public class UploadModel2 { public class UploadModel2 {
/** /**
*
*
* *
*
*
*/ */
private MultipartFile file; private MultipartFile file;
/** /**
*
*
* *
*
*
*/ */
private String dir; private String dir;
} }

Loading…
Cancel
Save