方法一
@PostMapping("/register")
public Result register(String username, String password) {
if (username!=null&&username.length()>=5&&username.length()<=16 &&
password!=null&&password.length()>=5&&password.length()<=16) {
//查询用户
User u=userService.findByUserName(username);
if(u==null) {
//没有占用
//注册
userService.register(username,password);
return Result.success();
}else {
//占用
return Result.error("用户名已被占用");
}
}else{
return Result.error("参数不合法");
}
}
方法二
使用Spring Validation,对注册接口的参数进行合法校验
1.引入 Spring Validation起步依赖
2.在参数前面添加@Patterm注解
3.在Controller类上添加@Validation注解
在pow.xml文件内写
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
在UserController中
package com.it.controller;
import com.it.pojo.Result;
import com.it.pojo.User;
import com.it.service.UserService;
import jakarta.validation.constraints.Pattern;
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")
@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 u=userService.findByUserName(username);
if(u==null) {
//没有占用
//注册
userService.register(username,password);
return Result.success();
}else {
//占用
return Result.error("用户名已被占用");
}
}
}
接口报500错误
配置一个包建一个GlobalExceptionHandler类
package com.it.exceptioon;
import com.it.pojo.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public Result handleException(Exception e){
e.printStackTrace();
return Result.error(StringUtils.hasLength(e.getMessage())? e.getMessage():"操作失败");
}
}
如果hasLength报红是因为导错包了
要导这个
import org.springframework.util.StringUtils;