|
1.引入Spring Validation 起步依赖 2.在参数前面添加@Pattern注解 3.在Controller类上添加@Validated注解
实操: 1,
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-validation</artifactId>
- </dependency>
复制代码 依赖版本,父工程管理,自带不用写。
2,示例:
- package com.jinhei.controller;
-
- import com.jinhei.pojp.Result;
- import com.jinhei.pojp.User;
- import com.jinhei.service.UserService;
- import jakarta.validation.constraints.Pattern;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.validation.annotation.Validated;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- /**
- * 用户相关接口
- */
- @RestController
- @RequestMapping("/user")
- @Slf4j
- @Validated
- public class UserController {
- @Autowired
- private UserService userService;
- /**
- * 用户注册
- */
- @PostMapping("/register")
- public Result register(@Pattern(regexp = "^[a-zA-Z0-9_-]{5,20}$") String username,@Pattern(regexp = "^[a-zA-Z0-9_-]{6,20}$") String password) {
- log.info("用户注册:username={},password={}", username, password);
-
- // 查看用户是否存在
- User user = userService.findByUsername(username);
- // 注册用户
- if (user == null){
- userService.register(username, password);
- return Result.success();
- }else {
- return Result.error("用户已存在");
- }
- }
-
- }
复制代码
|