spring boot 9

一、实体参数校验(Spring Validation)

1. 核心注解说明

表格

注解 作用 适用场景
@NotNull 值不能为 null 数值类型(如 Integer id)
@NotEmpty 不为 null 且内容不为空 字符串类型(如昵称、邮箱)
@Pattern 正则表达式校验格式 用户名 / 昵称长度、格式限制
@Email 校验邮箱格式 邮箱字段

2. 实体类(User.java)改造

java

运行

复制代码
@Data
public class User {
    @NotNull(message = "用户ID不能为空")
    private Integer id; // 主键ID

    @Pattern(regexp = "^\\w{5,16}$", message = "用户名必须是5-16位字母/数字/下划线")
    private String username; // 用户名(非必填)

    @NotEmpty(message = "昵称不能为空")
    @Pattern(regexp = "^\\S{1,10}$", message = "昵称必须是1-10位非空字符")
    private String nickname; // 昵称

    @NotEmpty(message = "邮箱不能为空")
    @Email(message = "邮箱格式不正确")
    private String email; // 邮箱

    private String userPic; // 用户头像地址
    private LocalDateTime createTime; // 创建时间
    private LocalDateTime updateTime; // 更新时间
}

3. Controller 接口开启校验

java

运行

复制代码
@PutMapping("/update")
public Result update(@RequestBody @Validated User user) {
    userService.update(user);
    return Result.success();
}
  • @Validated:开启实体类参数校验,校验失败会自动抛出异常

二、用户信息更新接口实现

1. 更新用户基本信息(/update)

Controller 层

java

运行

复制代码
@PutMapping("/update")
public Result update(@RequestBody @Validated User user) {
    userService.update(user);
    return Result.success();
}
Service 层

java

运行

复制代码
public void update(User user) {
    // 设置更新时间
    user.setUpdateTime(LocalDateTime.now());
    userMapper.update(user);
}
Mapper 层(SQL)

xml

复制代码
<update id="update">
    update user
    set nickname = #{nickname},
        email = #{email},
        update_time = #{updateTime}
    where id = #{id}
</update>

2. 更新用户头像(/updateAvatar)

Controller 层

java

运行

复制代码
@PatchMapping("/updateAvatar")
public Result updateAvatar(@RequestParam String avatarUrl) {
    // 从 ThreadLocal 获取当前用户ID
    Map<String, Object> claims = ThreadLocalUtil.get();
    Integer userId = (Integer) claims.get("id");
    
    userService.updateAvatar(userId, avatarUrl);
    return Result.success();
}
Service 层

java

运行

复制代码
public void updateAvatar(Integer userId, String avatarUrl) {
    userMapper.updateAvatar(userId, avatarUrl, LocalDateTime.now());
}
Mapper 层(SQL)

xml

复制代码
<update id="updateAvatar">
    update user
    set user_pic = #{avatarUrl},
        update_time = #{updateTime}
    where id = #{userId}
</update>

三、关键注意事项

  1. 参数校验生效条件

    • 实体类字段添加校验注解
    • Controller 接口参数前添加 @Validated
    • 已引入 spring-boot-starter-validation 依赖
  2. 全局异常处理 校验失败会抛出 MethodArgumentNotValidException,需要在全局异常处理器中处理:

    java

    运行

    复制代码
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return Result.error(message);
    }
  3. 用户 ID 的安全获取 头像更新接口中,用户 ID 不要由前端传入,应从 ThreadLocal 中获取,避免越权修改。

相关推荐
Joy T5 小时前
Agent 确定性上下文设计:从 Prompt 参数注入到能力分层
java·开发语言·微服务·架构·prompt·agent context
AIgorithmGEEK7 小时前
MySQL 索引全解(下):建、查、删实战与知识速查表
数据库·mysql·b+树·索引
Lost_the_wind7 小时前
MySQL学习笔记四
mysql
m0_587383008 小时前
广州 24 小时自助健身房解决方案技术实现与实战指南
java·spring·小程序·架构·需求分析
·云扬·8 小时前
Prompt 工程与安全:从 System 设计到注入防御
java·人工智能·安全·ai·prompt
代码不停9 小时前
自动化测试(java)
java·开发语言·selenium·自动化
唠点键盘之外的10 小时前
26 向量数据库实战:从 0 搭一条能用的检索链路(pgvector + Spring AI)
数据库·人工智能·spring
鬼手点金11 小时前
opencode-rules 插件
java·开发语言·前端·人工智能·chrome·git·github
paopaokaka_luck11 小时前
滑雪场管理系统(AI智能助手流式对话,ECharts 运营数据分析、教练、雪具与场地一体化预约,钱包支付退款、订单核销与服务评价)
java·人工智能·spring boot·网络协议·数据分析·echarts
考虑考虑12 小时前
@JsonInclude注解使用
spring boot·后端·spring