查询用户,判断用户名是否被占用。
1.没有被占用,则注册
2.被占用,则显示用户名已被占用!
service : UserService
import com.example.pojo.User; public interface UserService { //根据用户名查询用户 User findByUserName(String username); }
mapper : UserMapper
@Mapper public interface UserMapper { //根据用户名查询用户 @Select("select * from user where username=#{username}") User findByUserName(String username); }
controller : UserController
import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.service.UserService;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
@RestController @RequestMapping("/user") @Validated public class UserController { @Autowired private UserService userService; @PostMapping("/register") public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S(5,16)$") String password) { //查询用户 User user = userService.findByUserName(username); if(user == null){ //没有占用,注册 userService.register(username,password); return Result.success(); }else { //占用 return Result.error("用户名已被占用!"); } } }标签:username,用户名,springboot,占用,User,注册,import,String From: https://www.cnblogs.com/xmz88/p/18062688