PlayFramework框架验证

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

使用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 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 controller, 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. 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 variables’names.

message,它包含了错误的文字描述,message可以是文本信息,或者从错误集合里(典型的是为了国际化支持)参考一个key。

* The **message**. This contains the error’s textual description. The message can be a plain message or refer to a key from a message bundle (typically for internationalization support).

下面我们看一下怎样去验证一个简单的HTTP参数。

Let’s see how to validate 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 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 errors 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 that name and age are null, this would display:

相关文档
最新文档