- 1. 返回结果封装
- 2. 自定义异常
- 3. 校验工具类
- 4. 使用案例
- 5. 前端效果图
package com.course.server.dto; public class ResponseDto2. 自定义异常{ private boolean success = true; private String code; private String message; private T content; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public boolean getSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getContent() { return content; } public void setContent(T content) { this.content = content; } @Override public String toString() { final StringBuffer sb = new StringBuffer("ResponseDto{"); sb.append("success=").append(success); sb.append(", code='").append(code).append('''); sb.append(", message='").append(message).append('''); sb.append(", content=").append(content); sb.append('}'); return sb.toString(); } }
package com.course.server.exception;
public class ValidatorException extends RuntimeException {
public ValidatorException(String message) {
super(message);
}
}
3. 校验工具类
package com.course.server.util;
import com.course.server.exception.ValidatorException;
import org.springframework.util.StringUtils;
public class ValidatorUtil {
public static void require(Object str, String fieldName) {
if (StringUtils.isEmpty(str)) {
throw new ValidatorException(fieldName + "不能为空");
}
}
public static void length(String str, String fieldName, int min, int max) {
if (StringUtils.isEmpty(str)) {
return;
}
int length = 0;
if (!StringUtils.isEmpty(str)) {
length = str.length();
}
if (length < min || length > max) {
throw new ValidatorException(fieldName + "长度" + min + "~" + max + "位");
}
}
}
4. 使用案例
@PostMapping("/save")
public ResponseDto save(@RequestBody ChapterDto chapterDto) {
// 保存校验
ValidatorUtil.require(chapterDto.getName(), "名称");
ValidatorUtil.require(chapterDto.getCourseId(), "课程ID");
ValidatorUtil.length(chapterDto.getCourseId(), "课程ID", 1, 8);
ResponseDto responseDto = new ResponseDto();
chapterService.save(chapterDto);
responseDto.setContent(chapterDto);
return responseDto;
}
5. 前端效果图



