找回密码
 立即注册
查看: 5|回复: 0

16,Spring Validation参数校验

[复制链接]

215

主题

6

精华

219

金币

技术维护QQ:515138

积分
468
发表于 昨天 17:57 | 显示全部楼层 |阅读模式
1.引入Spring Validation 起步依赖
2.在参数前面添加@Pattern注解
3.Controller类上添加@Validated注解

实操:
1,
  1. <dependency>
  2.             <groupId>org.springframework.boot</groupId>
  3.             <artifactId>spring-boot-starter-validation</artifactId>
  4.         </dependency>
复制代码
依赖版本,父工程管理,自带不用写。
2,示例:
  1. package com.jinhei.controller;
  2. import com.jinhei.pojp.Result;
  3. import com.jinhei.pojp.User;
  4. import com.jinhei.service.UserService;
  5. import jakarta.validation.constraints.Pattern;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.validation.annotation.Validated;
  9. import org.springframework.web.bind.annotation.PostMapping;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RestController;
  12. /**
  13. * 用户相关接口
  14. */
  15. @RestController
  16. @RequestMapping("/user")
  17. @Slf4j
  18. @Validated
  19. public class UserController {
  20.     @Autowired
  21.     private UserService userService;
  22.     /**
  23.      * 用户注册
  24.      */
  25.     @PostMapping("/register")
  26.     public Result register(@Pattern(regexp = "^[a-zA-Z0-9_-]{5,20}$") String username,@Pattern(regexp = "^[a-zA-Z0-9_-]{6,20}$") String password) {
  27.         log.info("用户注册:username={},password={}", username, password);
  28.             // 查看用户是否存在
  29.             User user = userService.findByUsername(username);
  30.             // 注册用户
  31.             if (user == null){
  32.                 userService.register(username, password);
  33.                 return Result.success();
  34.             }else {
  35.                 return Result.error("用户已存在");
  36.             }
  37.         }
  38. }
复制代码




上一篇:15,MD5加密工具类
下一篇:17,StringUtils.hasLength()作用
网站建设,公众号小程序开发,系统定制,软件App开发,技术维护【联系我们】手机/微信:17817817816 QQ:515138

QQ|Archiver|自丢网 ( 粤ICP备2024252464号-1 )

GMT+8, 2026-2-27 06:13

专注于网站建设,公众号小程序制作,商城小程序,系统定制,软件App开发

【联系我们】手机/微信:17817817816 QQ:515138

快速回复 返回顶部 返回列表