注册接口
设置用户注册接口的响应数据类Result
Result类
package com.example.Pojo;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@NoArgsConstructor//无参数构造方法
@AllArgsConstructor//全参数构造方法
public class Result <T>{
private Integer code;//业务状态码,0成功,1失败
private String message;//提示消息
private T date;//响应数据,泛型
//快速返回操作成功响应结果,带响应数据
public static <E> Result<E> success(E data){
return new Result<>(0,"操作成功",data);
}
//快速返回操作成功响应结果
public static Result success(){
return new Result(0,"操作成功",null);
}
public static Result error(String message){
return new Result(1,message,null);
}
}
设计注册功能
设计controller层的UserController
controller类
package com.example.Controller;
import com.example.Pojo.Result;
import com.example.Pojo.User;
import com.example.Service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("register")
public Result result(String username,String password){
//查询用户
User user=userService.findByUserName(username);
if (user==null){
//注册用户
userService.register(username,password);
return Result.success();
}else {
//用户名以及被占用
return Result.error("用户名以及被占用");
}
}
}
设计Service和接口implement
service层
package com.example.Service;
import com.example.Pojo.User;
public interface UserService {
//根据用户名查询用户
User findByUserName(String username);
//注册用户
void register(String username, String password);
}
package com.example.Service.Impl;
import com.example.Mapper.UserMapper;
import com.example.Pojo.User;
import com.example.Service.UserService;
import com.example.Utils.MdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findByUserName(String username) {
User user=userMapper.findByUserName(username);
return user;
}
@Override
public void register(String username, String password) {
//密码加密处理
String mdString = MdUtil.getMDString(password);
//密文密码添加
userMapper.add(username,mdString);
}
}
在Utils曾设置一个密码加密类MDUtil
加密类MDUtil
package com.example.Utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MdUtil {//密码加密
//将密码转化为16进制字符,apache校验下载文件的正确性就是用的它
protected static char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
protected static MessageDigest messageDigest=null;
static {
try {
messageDigest=MessageDigest.getInstance("MD5");
}catch (NoSuchAlgorithmException nsaex){
System.err.println(MdUtil.class.getName()+"初始化失败,MessageDigest不支持");
nsaex.printStackTrace();
}
}
//生成字符串校验码
public static String getMDString(String s){
return getMDString(s.getBytes());//分割成字节
}
public static String getMDString(byte[] bytes) {
messageDigest.update(bytes);
return bufferToHex(messageDigest.digest());
}
private static String bufferToHex(byte bytes[]) {
return bufferToHex(bytes, 0, bytes.length);
}
private static String bufferToHex(byte bytes[], int m, int n) {
StringBuffer stringbuffer = new StringBuffer(2 * n);
int k = m + n;//加密长度
for (int l = m; l < k; l++) {
appendHexPair(bytes[l], stringbuffer);
}
return stringbuffer.toString();
}
private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换, >>>
// 为逻辑右移,将符号位一起右移,此处未发现两种符号有何不同
char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换
stringbuffer.append(c0);
stringbuffer.append(c1);
}
}
设计Mapper
Mapper类
package com.example.Mapper;
import com.example.Pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
//查询用户
@Select("select * from user where username=#{username}")
User findByUserName(String username);
//添加用户
@Insert("insert into user(username ,password,create_time,update_time)" +
" values(#{username},#{password},now(),now())")
void add(String username, String password);
}
测试
启动报错
说是没有扫描到Mapper,但我看idea明显是已经装配上了
注销@Autowired,我发现mapper没有注册成功
没办法,我只好,在启动类上添加@MapperScan(basePackages = “com.example.Mapper”)
这次注册成功了
打开postman,创建工作空间
创建一个post请求,发送,发现报406,但查看数据库,我们发现数据以及加进来了
在Result添加@Data注解,再删除数据,再启动一下
校验参数
导入springboot,validation依赖,
<!--参数校验-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
在参数上添加@Pattern注解
在controller类添加@Validated注解
package com.example.Controller;
import com.example.Pojo.Result;
import com.example.Pojo.User;
import com.example.Service.UserService;
import jakarta.annotation.Resource;
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 {
@Resource
private UserService userService;
@PostMapping("register")
public Result result(@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("用户名以及被占用");
}
}
}
对参数校验失败异常进行处理
创建一个异常处理类GlobalExceptionHandler
package com.example.Exception;
import com.example.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 HandlerException(Exception e){
e.printStackTrace();
return Result.error(StringUtils.hasLength(e.getMessage())? e.getMessage():"操作失败");
}
}