springboot注册参数校验(两种方法)

方法一

@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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值