spring boot项目中的一些常用提示信息
1. 数据范围检查
在添加或修改数据时,确保数据值在合理的范围内。例如,年龄通常应该在 0 到 150 岁之间,商品价格应该大于 0 等。
Controller 层
@RestController
@RequestMapping("/person")
public class PersonController {@Autowiredprivate PersonService personService;@PostMapping("/add")public AjaxResult addPerson(@RequestBody Person person) {if (person.getAge() < 0 || person.getAge() > 150) {return AjaxResult.error("年龄必须在 0 到 150 岁之间");}personService.addPerson(person);return AjaxResult.success("人员信息添加成功");}
}
2. 数据格式检查
确保输入的数据符合特定的格式要求,例如邮箱格式、手机号码格式等。
Controller 层
@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@PostMapping("/register")public AjaxResult registerUser(@RequestBody User user) {String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";if (!user.getEmail().matches(emailRegex)) {return AjaxResult.error("请输入有效的邮箱地址");}userService.registerUser(user);return AjaxResult.success("用户注册成功");}
}
3. 关联数据完整性检查
在插入或更新数据时,确保关联的数据是存在且有效的。例如,在添加订单时,检查对应的客户是否存在。
Controller 层
@RestController
@RequestMapping("/order")
public class OrderController {@Autowiredprivate OrderService orderService;@Autowiredprivate CustomerService customerService;@PostMapping("/add")public AjaxResult addOrder(@RequestBody Order order) {if (!customerService.existsCustomer(order.getCustomerId())) {return AjaxResult.error("关联的客户不存在,请检查客户 ID");}orderService.addOrder(order);return AjaxResult.success("订单添加成功");}
}
CustomerService 接口
public interface CustomerService {boolean existsCustomer(Long customerId);
}
CustomerServiceImpl 实现
@Service
public class CustomerServiceImpl implements CustomerService {@Autowiredprivate CustomerMapper customerMapper;@Overridepublic boolean existsCustomer(Long customerId) {return customerMapper.existsCustomer(customerId) > 0;}
}
CustomerMapper 接口
public interface CustomerMapper {int existsCustomer(Long customerId);
}
XML 文件
<mapper namespace="com.example.mapper.CustomerMapper"><select id="existsCustomer" parameterType="java.lang.Long" resultType="int">SELECT COUNT(*) FROM customer WHERE id = #{customerId}</select>
</mapper>
4. 业务规则检查
根据具体的业务逻辑进行检查,例如在添加员工时,检查员工的入职日期不能晚于当前日期。
Controller 层
@RestController
@RequestMapping("/employee")
public class EmployeeController {@Autowiredprivate EmployeeService employeeService;@PostMapping("/add")public AjaxResult addEmployee(@RequestBody Employee employee) {LocalDate currentDate = LocalDate.now();if (employee.getHireDate().isAfter(currentDate)) {return AjaxResult.error("入职日期不能晚于当前日期");}employeeService.addEmployee(employee);return AjaxResult.success("员工信息添加成功");}
}
5. 必填字段检查
确保用户提交的数据中包含必需的字段,避免空值导致系统异常。
Controller 层
@RestController
@RequestMapping("/product")
public class ProductController {@PostMapping("/add")public AjaxResult addProduct(@RequestBody Product product) {if (product.getName() == null || product.getName().trim().isEmpty()) {return AjaxResult.error("商品名称不能为空");}if (product.getPrice() == null || product.getPrice() <= 0) {return AjaxResult.error("商品价格必须大于 0");}// 保存商品...return AjaxResult.success("商品添加成功");}
}
6. 数据依赖验证
确保某些字段之间的逻辑关系正确,例如开始日期不能晚于结束日期。
Controller 层
@RestController
@RequestMapping("/project")
public class ProjectController {@PostMapping("/add")public AjaxResult addProject(@RequestBody Project project) {if (project.getStartDate().isAfter(project.getEndDate())) {return AjaxResult.error("开始日期不能晚于结束日期");}// 保存项目...return AjaxResult.success("项目添加成功");}
}
7. 数据权限验证
确保用户只能操作自己权限范围内的数据,防止越权访问。
Controller 层
@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate AuthService authService;@DeleteMapping("/{userId}")public AjaxResult deleteUser(@PathVariable Long userId) {// 检查当前用户是否有权限删除该用户if (!authService.hasPermission(userId, "user:delete")) {return AjaxResult.error("无权限删除此用户");}// 删除用户...return AjaxResult.success("用户删除成功");}
}
8. 状态流转验证
确保数据状态的变更符合业务规则,例如订单只能从"待支付"到"已支付",不能直接到"已完成"。
Controller 层
@RestController
@RequestMapping("/order")
public class OrderController {@PostMapping("/pay/{orderId}")public AjaxResult payOrder(@PathVariable Long orderId) {Order order = orderService.getOrderById(orderId);if (order.getStatus() != OrderStatus.PENDING_PAYMENT) {return AjaxResult.error("当前订单状态不允许支付操作");}// 处理支付...return AjaxResult.success("支付成功");}
}
9. 唯一性组合验证
确保多个字段的组合是唯一的,例如同一用户不能对同一商品重复评价。
Service 层
@Service
public class CommentService {@Autowiredprivate CommentRepository commentRepository;public void addComment(Comment comment) {boolean exists = commentRepository.existsByUserIdAndProductId(comment.getUserId(), comment.getProductId());if (exists) {throw new BusinessException("您已对该商品进行过评价,不能重复提交");}// 保存评论...}
}
10. 数值精度验证
确保小数位数符合业务要求,例如金额通常保留两位小数。
Controller 层
@RestController
@RequestMapping("/finance")
public class FinanceController {@PostMapping("/transfer")public AjaxResult transfer(@RequestBody TransferRequest request) {BigDecimal amount = request.getAmount();if (amount.scale() > 2) {return AjaxResult.error("金额最多保留两位小数");}// 处理转账...return AjaxResult.success("转账成功");}
}
11. 文件类型/大小验证
在上传文件时,确保文件类型和大小符合限制。
Controller 层
@RestController
@RequestMapping("/upload")
public class UploadController {@PostMapping("/image")public AjaxResult uploadImage(@RequestParam("file") MultipartFile file) {if (file.isEmpty()) {return AjaxResult.error("请选择要上传的文件");}String contentType = file.getContentType();if (!contentType.startsWith("image/")) {return AjaxResult.error("请上传图片文件");}if (file.getSize() > 5 * 1024 * 1024) { // 5MBreturn AjaxResult.error("文件大小不能超过 5MB");}// 处理上传...return AjaxResult.success("上传成功");}
}
12. 敏感信息过滤
防止用户输入包含敏感词汇或恶意脚本的内容。
Service 层
@Service
public class ContentService {@Autowiredprivate SensitiveWordFilter filter;public void publishArticle(Article article) {if (filter.containsSensitiveWord(article.getContent())) {throw new BusinessException("内容包含敏感词汇,请修改后提交");}// 保存文章...}
}
13. 业务阈值验证
确保操作不超过系统限制,例如单日提现金额上限。
Service 层
@Service
public class WithdrawalService {@Autowiredprivate AccountService accountService;public void processWithdrawal(WithdrawalRequest request) {BigDecimal dailyTotal = accountService.getDailyWithdrawalAmount(request.getUserId());BigDecimal newTotal = dailyTotal.add(request.getAmount());if (newTotal.compareTo(BigDecimal.valueOf(50000)) > 0) {throw new BusinessException("单日提现金额不能超过 50,000 元");}// 处理提现...}
}
14. 数据版本验证
在更新数据时,确保数据未被其他操作修改(乐观锁机制)。
Service 层
@Service
public class ProductService {@Transactionalpublic void updateProduct(Product product) {Product dbProduct = productRepository.findById(product.getId()).orElseThrow(() -> new EntityNotFoundException("商品不存在"));if (!dbProduct.getVersion().equals(product.getVersion())) {throw new OptimisticLockingFailureException("商品已被其他操作修改,请刷新后重试");}// 更新商品...product.setVersion(dbProduct.getVersion() + 1);productRepository.save(product);}
}
15. 外部服务依赖验证
在执行操作前,验证第三方服务状态或数据有效性,例如支付前检查银行卡状态。
Service 层
@Service
public class PaymentService {@Autowiredprivate BankApiClient bankApiClient;public void processPayment(PaymentRequest request) {BankCardStatus status = bankApiClient.checkCardStatus(request.getCardNumber());if (status != BankCardStatus.NORMAL) {throw new BusinessException("银行卡状态异常,请联系发卡行");}// 处理支付...}
}
这些验证场景覆盖了从前端表单到后端业务逻辑的多个层面,可以根据系统需求灵活组合使用。在实际开发中,建议将部分通用验证逻辑(如格式、必填项)放在前端或使用注解(如 JSR-303)实现,而复杂业务规则验证则放在服务层处理。