1、Play Framework 框架 验证使用Play验证HTTP数据 Validating HTTP data with Play验证确保数据有确定的值,或者符合某种特殊的需求,你可以在模型被保存进数据库之前使用验证去核实你的模型,或者直接在HTTP参数中使用它们去验证一个简单的form表单。Validations ensure that the data has certain values or meets specific requirements. You can use validation to verify that your models are correct before
2、saving them to the database, or use them directly on HTTP parameters to validate a simple form.它们怎样工作? How does it work?每一次的请求使用它自己的验证去收集错误。在控制器里,你可以直接使用Validation变量,你也可以直接访问play.data.validation.Validation类下的API中的静态方法。Each request has it own *Validation* object which collects errors. From a controll
3、er, you access it directly using the *validation* variable. You can still access a subset of the API using the *play.data.validation.Validation* class static methods.验证对象包含一个集合play.data.validation.Error对象,每一个错误有2个属性。The validation object maintains a collection of *play.data.validation.Error* objects
4、. Each error has two properties:key,它帮助你决定哪一个数据项引发的错误,key的值可以被定义但是当Play产生错误时,它使用默认的约定,遵循Java变量的名称。* The *key*. This helps you to determine which data element caused the error. The key value can be set arbitrarily but when Play generates errors, it uses default conventions that follow the Java variab
5、les names.message,它包含了错误的文字描述,message可以是文本信息,或者从错误集合里(典型的是为了国际化支持)参考一个key。* The *message*. This contains the errors textual description. The message can be a plain message or refer to a key from a message bundle (typically for internationalization support).下面我们看一下怎样去验证一个简单的HTTP参数。Lets see how to val
6、idate a simple HTTP parameter:public static void hello(String name) validation.required(name); .这段代码检查name变量被正确的设置了,如果不是的话,相应的信息会被增加到当前的错误集合中去。This code checks that the name variable is correctly set. If not, the corresponding error is added to the current errors collection.你可以重复这个操作去验证每一个你需要的变量。You
7、 can repeat this operation for each validation you need:public static void hello(String name, Integer age) validation.required(name); validation.required(age); validation.min(age, 0); .重新得到错误信息 Retrieving error messages在每一个验证结束,你可以检查是否错误都被创建并显示出来了。At the end of the validation you can check if any er
8、rors have been created and display them:public static void hello(String name, Integer age) validation.required(name); validation.required(age); validation.min(age, 0); if(validation.hasErrors() for(Error error : validation.errors() System.out.println(error.message(); 假设name和age是null,那么将会显示出:Assuming
9、 that name and age are null, this would display:name is requiredage is required默认的消息是key和message集合中key一致的,所以在conf/messages文件中你可以看到:Default messages are keys that refer to the message bundle. So in the *conf/messages* file you will have:validation.required=%s is required你可以改变这些默认的消息,然后再每一个项目中覆盖它,%s占位
10、符会被错误的key所替代,你可以使用error.message(String field)方法覆盖它。You can change this default message and override it for each application language. The *%s* placeholder will be replaced by the error key. You can override using the *error.message(String field)* method.例如:For example:Error error = validation.requir
11、ed(name).error;if(error != null) System.out.println(error.message(The name);你还可以为每一次检查明确指定不同的信息。You can also specify a different message for each check:Error error = validation.required(name).message(Fill the name!).error;if(error != null) System.out.println(error.message();再模板中显示错误信息 Displaying err
12、ors in the template再大多数情况下,你想让错误消息显示在视图模板中,你可以在模板中使用errors对象使用它们,一些tag帮助你显示这些错误。In most cases you want to display the error messages in the view template. You can access them in the template using the *errors* object. Some tags help you to display the errors:让我们看个例子。Lets see a sample:public static v
13、oid hello(String name, Integer age) validation.required(name); validation.required(age); validation.min(age, 0); render(name, age);现在是模板。and now the template:#ifErrors Oops. #errors $error #/errors#/ifErrors#else Hello $name, you are $age.#/else但是在实际的应用中,你想显示原先的form表单。所以你将有2个action,显示form表单,还要处理POST
14、。But in a real application you want to redisplay the original form. So you will have two actions: one to display the form and another one to handle the POST.当然如果有错误发生的话你需要重新跳转到第一个action,但是验证会发生在第二个action中,这样你需要一些小技巧在跳转之前保持错误信息。使用validate.keey()方法,它可以为下个action保存错误集合。Of course the validation will occu
15、r in the second action and if some error occurs you will have to redirect to the first action. In this case you need a special trick to keep your errors during the redirect. Use the *validation.keep()* method. This will save the errors collection for the next action.让我们看一个真实的例子。Lets see a real sampl
16、e:public class Application extends Controller public static void index() render(); public static void hello(String name, Integer age) validation.required(name); validation.required(age); validation.min(age, 0); if(validation.hasErrors() params.flash(); / add http parameters to the flash scope valida
17、tion.keep(); / keep the errors for the next request index(); render(name, age); And the *view/Application/index.html* template:#ifErrors Oops. #errors $error #/errors#/ifErrors#form Application.hello() Name: Age: #/formYou can create a better user experience by displaying each error message next to
18、the field that generated the error:#ifErrors Oops.#/ifErrors#form Application.hello() Name: #error name / Age: #error age / #/form使用注解 Using annotations你可以使用注解做相同的事。You can use annotations to do the same thing:public static void hello(Required String name, Required Min(0) Integer age) if(validation.
19、hasErrors() params.flash(); / add http parameters to the flash scope validation.keep(); / keep the errors for the next request index(); render(name, age);验证对象 Validating objects使用注解你可以轻松的为你的model对象增加约束,让我们重写前一个例子,使用User类。Using annotations you can easily add constraints to your model objects. Lets re
20、write the previous example using a User class.First the *User* class:package models;public class User Required public String name; Required Min(0) public Integer age;然后修改hello action.Then the modified *hello* action:public static void hello(Valid User user) if(validation.hasErrors() params.flash();
21、/ add http parameters to the flash scope validation.keep(); / keep the errors for the next request index(); render(name, age);最后增加一个修改后的form表单And finally the modified form:#ifErrors Oops.#/ifErrors#form Application.hello() Name: #error user.name / Age: #error user.age / #/form自定义验证 Custom validation
22、如果在play.data.validation没有发现你需要的验证,你可以自己写。然后使用CheckWith注解绑定到你自己的Check实现里去。Cant find the validator you need in the *play.data.validation* package? Write your own. You can use the generic *CheckWith* annotation to bind your own *Check* implementation.例如For example:public class User Required CheckWith(MyPasswordCheck.class) public String password; static class MyPasswordCheck extends Check public abstract boolean isSatisfied(Object user, Object password) return notMatchPreviousPasswords(password);
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1