欢迎来到天天文库
浏览记录
ID:48829713
大小:18.78 KB
页数:14页
时间:2020-01-31
《Play Framework 框架 验证.doc》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、使用Play验证HTTP数据ValidatingHTTPdatawithPlay 验证确保数据有确定的值,或者符合某种特殊的需求,你可以在模型被保存进数据库之前使用验证去核实你的模型,或者直接在HTTP参数中使用它们去验证一个简单的form表单。Validationsensurethatthedatahascertainvaluesormeetsspecificrequirements.Youcanusevalidationtoverifythatyourmodelsarecorrectbeforesavingthemtothedatabase,oruseth
2、emdirectlyonHTTPparameterstovalidateasimpleform. 它们怎样工作?Howdoesitwork? 每一次的请求使用它自己的验证去收集错误。在控制器里,你可以直接使用Validation变量,你也可以直接访问play.data.validation.Validation类下的API中的静态方法。Eachrequesthasitown**Validation**objectwhichcollectserrors.Fromacontroller,youaccessitdirectlyusingthe**validation
3、**variable.YoucanstillaccessasubsetoftheAPIusingthe**play.data.validation.Validation**class’staticmethods. 验证对象包含一个集合play.data.validation.Error对象,每一个错误有2个属性。Thevalidationobjectmaintainsacollectionof**play.data.validation.Error**objects.Eacherrorhastwoproperties: key,它帮助你决定哪一个数据项引发的错
4、误,key的值可以被定义但是当Play产生错误时,它使用默认的约定,遵循Java变量的名称。*The**key**.Thishelpsyoutodeterminewhichdataelementcausedtheerror.ThekeyvaluecanbesetarbitrarilybutwhenPlaygenerateserrors,itusesdefaultconventionsthatfollowtheJavavariables’names. message,它包含了错误的文字描述,message可以是文本信息,或者从错误集合里(典型的是为了国际化支持)
5、参考一个key。*The**message**.Thiscontainstheerror’stextualdescription.Themessagecanbeaplainmessageorrefertoakeyfromamessagebundle(typicallyforinternationalizationsupport). 下面我们看一下怎样去验证一个简单的HTTP参数。Let’sseehowtovalidateasimpleHTTPparameter: publicstaticvoidhello(Stringname){ validation.r
6、equired(name); ...}这段代码检查name变量被正确的设置了,如果不是的话,相应的信息会被增加到当前的错误集合中去。Thiscodechecksthatthenamevariableiscorrectlyset.Ifnot,thecorrespondingerrorisaddedtothecurrenterrorscollection. 你可以重复这个操作去验证每一个你需要的变量。Youcanrepeatthisoperationforeachvalidationyouneed: publicstaticvoidhello(Stringna
7、me,Integerage){ validation.required(name); validation.required(age); validation.min(age,0); ...} 重新得到错误信息Retrievingerrormessages 在每一个验证结束,你可以检查是否错误都被创建并显示出来了。Attheendofthevalidationyoucancheckifanyerrorshavebeencreatedanddisplaythem: publicstaticvoidhello(Stringname,Integera
8、ge){ validation.r
此文档下载收益归作者所有