首页 > 编程知识 正文

前端参数校验,java参数校验框架

时间:2023-05-04 15:04:42 阅读:190448 作者:309

使用java后端优雅的参数检查注释验证前端参数:

publicclassuavadddto {//import javax.validation.constraints.*; @notnull(message='名称不能为空') notempty ) message='名称不能为空。 请检查并重新输入值() ) public String name; @notnull(message='接收数据不能为空') min ) value=0,message='接收数据有误,数据必须在0到100之间) max ) value=100 请检查) )公共字符串电子邮件; @length(min=11,max=11,message='输入的电话号码长度错误,必须为11位) )公共字符串移动; 添加@Valid注释,打开搬入对象的验证

@ restcontrollerpublicclassuavcontroller { @ autowiredprivateuavserviceuavservice; @postmapping(/add ) ) publicstringadd ) requestbody @ validuavaddtouavaddto ) UAVservice.saveone ) ) UAV; 返回' success '; }验证对传入参数的检查结果:

结果返回的结果太长,不符合我们传递给前端的结果。

这里创建全局的异常拦截,只将错误的信息返回到前端。

@ controller advice @ responsebodypublicclassglobalexceptioninterceptor { @ exception handler (value=methodargumentnotvalidextvalidexextor tion handler (httpservletrequestrequest,Exception e ) executionresponse=newe ewer string failmsg=null; 获得if (einstanceofmethodargumentnotvalidexception (//参数检查的具体异常信息,failmsg=(methodargumentvalidexception ) ) e ) //向前端的返回执行响应返回消息; }返回体:

//返回体此处为lombok插件@ getter @ setterpublicclassexecutionresponse { privateintegercode=responsecodeenum.response _ succe publicvoidsetfailed (string message ) this.code=responsecodeenum.response _ failed.code ); this.message=message; }添加异常拦截器后:

以这种方式优雅地将错误结果返回到前端。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。