校验分为两部分,一部分是前端的输入时就校验,一部分时后端接收参数时的校验。本文提到的是后端接收参数时的校验。这个后端校验的存在有什么意义呢?
比如我们设置前端在输入参数时限制输入不能为空,应该为3-20位非空字符,没有按要求输入可能会出现这样的提示。

但是还是可以提交。我们在后端需要对输入的参数进行校验,防止不合法的参数对系统造成影响。这里我们会说到正则表达式校验。
过程
首先在pom.xml中添加依赖

给参数添加正则表达式
在方法中参数前加上**@Pattern(regexp="^\\s{3,20}$"),**就是给参数添加正则表达式,3到20位非空字符,因为可能只在页面中校验,不符合校验规则还是会点注册按钮,那就还是会提交数据到后端。所以保险一点还是在controller中加个校验。

再在controller类上面加@Validated

举个例子:

填写的信息都不符号规则,用户忽略提示直接点注册按钮,于是报错

在全局异常处理器中处理参数校验失败的异常
这样当然是不行的,我们可以对参数校验失败的情况做异常处理。定义一个类专门用来做参数校验失败异常处理 。在方法中返回值类型为Result,这个是自己定义的一个类,存放Result返回消息、响应内容、接口状态码。里面涉及到返回失败值的代码的部分是:

第一个参数是接口状态码,第二个参数是错误信息。
e.printStackTrace()将异常信息输出到控制台
StringUtils.hasLength(e.getMessage())?e.getMessage():"操作失败")
StringUtils是spring提供的工具类。这里的hasLength方法是看这个e.getMessage()是否有内容,是否有错误原因。如果有错误原因就返回错误原因,没有错误原因就返回"操作失败"

然后在前端vue页面 获取返回值时设置接收接口状态码为409就弹出ElMessage信息"您填写的表单项不合法,请修改后提交!"。当然了这里的接口状态码也是自己设置,ElMessage也可以自己设置,也可以用它返回的错误信息。比如自己设置:

可以设多个可能,都是根据返回结果的接口状态码来设置

注:要用ElMessage得导入一下
javascript
import {ElMessage} from "element-plus";
重新启动项目后再输入这样的不合法内容,就会给出提示了。

弹出信息提示:

或者只是用于自己测试,可以弄一个弹窗直接将报错内容输出


这部分参数校验的内容总结一下就是:
① 导入validation坐标
② 在参数上添加@Pattern注解
③ 指定校验规则在Controller类上添加@Validated注解
④ 在全局异常处理器中处理参数校验失败的异常
希望以上内容能帮助到你^_^加油加油