使用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:
name is required
age 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占位符会被错误的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.required(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 errors 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:
让我们看个例子。
Let’s see a sample:
public static void hello(String name, Integer age) {
validation.required(name);
validation.required(age);
validation.min(age, 0);
render(name, age); }
现在是模板。
and now the template:
#{ifErrors}
#{errors}
#{/ifErrors}
#{else}
Hello ${name}, you are ${age}.
#{/else}
但是在实际的应用中,你想显示原先的form表单。所以你将有2个action,显示form表单,还要处理POST。
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 occur 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.
让我们看一个真实的例子。
Let’s see a real sample:
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
validation.keep(); // keep the errors for the next request
index();
}
render(name, age);
}
}
And the **view/Application/index.html** template:
#{ifErrors}
#{/errors}
#{/ifErrors}
#{form @Application.hello()}
Name:
Age:
You can create a better user experience by displaying each error message next to the field that generated the error:
#{ifErrors}
#{/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.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. Let’s rewrite 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(); // 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}
#{/ifErrors}
#{form @Application.hello()}
Name:
#{error 'https://www.doczj.com/doc/da15471818.html,' /}
Age:
value="${flash['user.age']}" />
#{error 'user.age' /}
#{/form}
自定义验证
Custom validation
如果在play.data.validation没有发现你需要的验证,你可以自己写。然后使用@CheckWith注解绑定到你自己的Check实现里去。
Can’t 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:
评卷浏览 考生姓名张彬答题开始时间2013-04-24 10:15 结束时间2013-05-02 10:15 考生得分0 满分161 及格分60 一、单项选择题(共41题,41分) 1. Customer对象在程序执行到第几行时变为脱管状态? Customer customer=new Customer(); //line1 customer.setName("张三"); Session session=sessionFactory.openSession(); //line2 Transaction tx = session1.beginTransaction(); session.save(customer); //line3 https://www.doczj.com/doc/da15471818.html,mit(); //line4 session.close(); //line5 (1 分) A) line1 B) line2 C) line4 D) line5 —标准答案:D —考生答案:D —考生得分:1 评语: 2. 在struts2应用开发中下列描述正确的是(1 分) A) 为每一个Action在XML中配置一个action,并且这个XML配置文件必须命名为struts.xml,并放置在类的根路径下。 B) 为每一个可能接收的逻辑请求编写一个Action类,该类必须继承父类ActionSupport 。 C) 在web程序的部署描述文件(web.xml)中配置struts2核心控制器,该核心控制器是一个过滤器。 D) Struts2的Action必须实现Action接口。 —标准答案:C —考生答案: —考生得分:0 评语:
web项目前端开发经验总结 最近这一个月完成了自己的第一个java web项目,是给某杂志社做的在线投稿系统,虽然进度很慢,但是中间确实学到了不少东西,深刻体会到了自己看几个月书都不如做一个项目来的实在。这个项目自己主要负责的是JSP页面、JS脚本、CSS样式表的编写,虽然主要做的是前端,但是在设计前端后台交互功能时,对MVC架构和数据库又多了一分了解,这一个月的时间,自己在技术上也确实成长了不少。 下面分成几块总结一下自己的这个项目中的心得吧: 1.项目开发流程:从确认需求开始,到原型设计,再到原型测试,这些都没什么说的了,主要是刚开始开发前端JSP页面时,自己走了很多弯路,想到有什么页面就写什么页面,GET和POST的路径也是随心所欲,想到什么名字就起什么名字,结果发现这样做严重影响了项目开发的进度,后来经过主管的提点后,我幡然醒悟,其实,面向对象的思想就贯穿在整个项目当中,在前面的原型设计的过程中,除了页面的设计还有数据库的设计,数据库的每个表就对应着Java中的每个实体类,这个类封装了数据库中的列作为属性,封装了数据库的增删改查作为方法,就拿这个投稿系统为例,实体主要有用户、稿件等等,实体间还有着一对一映射或者一对多映射等对应关系。其实,整个系统的开发就是围绕着这些个实体进行的,甚至于我们可以把实体名字做为二级目录,把实体的增删改查作为GET或POST 的路径,譬如account/add、paper/delete等等,有了这些路径,那么与之对应的GET和POST的Controller也就有了,接下来我们要做的就是,定义Controller中返回的视图,写完Controller后再把与实体相关的增删改查方法写到服务层中,再把项目的整个骨架搭起来,再去处理细节,很快的,这个项目就成型了。这里前端和后台的配合尤为重要,数据交互是整个系统的核心。 2.JSP页面设计:提到JSP页面,在这里我想说的一点是,其实JSP页面是在服务器生成的,那么传给JSP页面的变量、参数都会在服务器转化为它们具体的值,然后再传给客户端。JSP页面可以实现很多服务器端的功能,因为可以直接在页面嵌入JAVA代码,但是我们必须明确的一点是,JSP页面主要是用来呈现视图的,不要再其中套入大量的代码,要明确前端与后台的分工。 3.JSTL标签:JSTL标签就是JSP standard taglib,即JSP标准标签库,首先,EL表达式可以非常方便的取出Controller返回的View包含的Model,甚至都无需声明EL 表达式。其次,JSTL标签可以实现很多的逻辑控制功能,比如最基本的c:if判断、c:forEach 循环,甚至有更强大的c:choose,有了这些,我们可以大大简化代码量,JSP页面中用几十行java写的代码,有时用几句JSTL标签组合就实现了,此外,像fmt:parseDate和 fmt:formatDate也是很好用的标签,用于日期的解析和格式化,此外JSTL更有强大的函数标签库fn:,项目中我也只用到了fn:length取后台传的list的长度。要善用JSTL标签,但是又不要完全依赖于它,JSTL标签很方便、快捷,但是切记,JSTL功能有限,不要完全依赖于它。 4.shiro框架:shiro框架是apache的一款面向java web项目的权限控制框架,这个框架无论前端、后台都十分好用,在前端,我们可以使用shiro强大的标签库,通过用户角色赋予用户不同的访问权限。譬如,如果一个系统的用户有访客、用户、管理员三种角色,我们就可以通过shiro标签来控制游客不能访问哪些内容,页面向用户和管理员呈现的不同内容,这就是shiro标签的神奇之处。 5.sitemesh框架:这个主要是用来将所有页面套用固定格式,用以页面的复用,其实有些时候标签更为方便,而且sitemesh框架的内存开销是的二倍,还会导致拦截器出现一些莫名的bug,所以并不推荐使用。
JavaWeb试题 一.单项选择(共20题,每题2分) 1.HTML的全称是什么( A ) A.HyperText Markup Language B.HyperTest Market Language C.HighTest Markup Language D.HyperText Market Language 2.以下选项中属于行内标签的是(A ) A、 span B、 p C、div D、hr 3.以下说法正确的是( C) A、background-color:设置文字颜色 B、back-corlor设置背景色 C、 background-color:设置背景色 D、 color:设置背景色 4.下列哪一项是CSS 正确的语法(C ) A、 body: color=black B、 {body: color:black} C、 body{color:black} D、 {body:color=black} 5.Http协议的状态码(D)表示文件没有找到
A、200 B、400 C、 500 D、 404 6.Tomcat的端口号可以在(A )文件中修改 A. server.xml B. web.xml C. tomcat.xml D. 不能改 7.在一个表单里,想要用jquery找到指定元素的第一个元素用 ( )实现,第二个元素用( A)实现。 A、first,eq(1) B、first,equ(0) C、first,eq(0) D、fir,eq(1) 8.当一个Servlet首次被请求的时候,服务器首先会调用( D )方法 A、 doGet B、 doPost C、 doInit D、 init 9.在J2EE中,重定向到另一个页面,以下(C)语句是正确的 A、 request . sendRedirect(“http :// www . svse . com . cn”); B、 request . sendRedirect(); C、 response . sendRedirect(“http: // www . svse . com . cn”); D、 response .sendRedirect(); 10.在Servlet中,response.getWriter()返回的是( B ) A、 JspWriter对象 B、 PrintWriter对象 C、 Out对象 D、 ResponseWriter对象 11.Login.jsp为登录页面,表单代码如下:
2、将规则下载初始化js中 $().ready(function() { $("#signupForm").validate({ rules: { firstname: "required", email: { required: true, email: true }, password: { required: true, minlength: 5 }, confirm_password: { required: true, minlength: 5, equalTo: "#password" } }, messages: { firstname: "请输入姓名", email: {一JQuery.validation 验证框架使用细解 一、用前必备 官方网站:http://bassistance.de/jquery-plugins/jquery-plugin-validation/ API: http://jquery.bassistance.de/api-browser/plugins.html 当前版本:1.5.5 需要JQuery版本:1.2.6+, 兼容 1.3.2 二、默认校验规则 (1)required:true 必输字段 (2)remote:"check.php" 使用ajax方法调用check.php验证输入值 (3)email:true 必须输入正确格式的电子邮件 (4)url:true 必须输入正确格式的网址 (5)date:true 必须输入正确格式的日期 (6)dateISO:true 必须输入正确格式的日期(ISO),例如:2009-06-23,1998/01/22 只验证格式,不验证有效性 (7)number:true 必须输入合法的数字(负数,小数) (8)digits:true 必须输入整数 (9)creditcard: 必须输入合法的信用卡号 (10)equalTo:"#field" 输入值必须和#field相同 (11)accept: 输入拥有合法后缀名的字符串(上传文件的后缀) (12)maxlength:5 输入长度最多是5的字符串(汉字算一个字符) (13)minlength:10 输入长度最小是10的字符串(汉字算一个字符) (14)rangelength:[5,10] 输入长度必须介于 5 和 10 之间的字符串")(汉字算一个字符) (15)range:[5,10] 输入值必须介于 5 和 10 之间 (16)max:5 输入值不能大于5 (17)min:10 输入值不能小于10 三、默认的提示 messages: { required: "This field is required.", remote: "Please fix this field.", email: "Please enter a valid email address.", url: "Please enter a valid URL.", date: "Please enter a valid date.", dateISO: "Please enter a valid date (ISO).", dateDE: "Bitte geben Sie ein g眉ltiges Datum ein.", number: "Please enter a valid number.", numberDE: "Bitte geben Sie eine Nummer ein.", digits: "Please enter only digits", creditcard: "Please enter a valid credit card number.", equalTo: "Please enter the same value again.", accept: "Please enter a value with a valid extension.", maxlength: $.validator.format("Please enter no more than {0} characters."),
JBoss4.2及JBoss5.0部署jax-ws2.0/2.1WebServices 一,部署jax-ws 2.0/2.1 POJO Web Service到JBoss4.2.2.GA 1:必须为你的POJO Web Service定义一个Servlet,并定义service的endpoint。 这意味着必须修改/增加两个文件:WEB-INF/web.xml;WEB-INF/sun-jaxws.xml (附文后) 2:最好将所需的jax-ws jars放到WEN-INF/lib里,免得将这些jar拷贝来拷贝去。 本人曾试了半天,拷来拷去,反正是搞不定。最后还是一古脑儿索性全放到WEB- INF/lib里,倒是爽快: WEB-INF/lib/jaxws-rt.jar WEB-INF/lib/jaxws-tools.jar WEB-INF/lib/log4j-1.2.8.jar WEB-INF/lib/saaj-api.jar WEB-INF/lib/saaj-impl.jar WEB-INF/lib/sjsxp.jar WEB-INF/lib/stax-ex.jar WEB-INF/lib/streambuffer.jar WEB-INF/lib/sxalan.jar 别问我到底哪个是哪个,都是干什么的。 二,部署jax-ws 2.0/2.1 POJO Web Service到JBoss5.0.0.GA 好像是去年,JBoss5面世了,根据其Release Note,它是“the final release of the JBoss 5.0 series for th e Java EE?5 codebase that fully complies with the Java EE 5 conformance testing certification requirements.” 但本人的试验结果却
jQuery formValidator使用说明 说明:jQuery formValidator表单验证插件,它是基于jQuery类库,实现了js 脚本于页面的分离。对一个表单对象,你只需要写一行代码就可以轻松实现20种以上的脚本控制。现支持一个表单元素累加很多种校验方式,采用配置信息的思想,而不是把信息写在表单元素上,能比较完美的实现ajax请求。并结合jquery.boxy实现遮罩提示。 一、所需元素 jquery-1.3.2.js (需要jquery-1.3.2以上版本) formValidator.js (表单验证基础js) formValidatorRegex.js (表单验证所需正则js) jquery.boxy.js (遮罩提示js) validator.css (表单验证样式) boxy.css (遮罩提示样式) 二、使用说明 a)使用方法 i.加载所需js和css文件 ii.初始化验证控件 ($.formValidator.initConfig({formid:"form1",onerror:functi on(msg){Boxy.alert("
jQuery formValidator表单验证插件是什么? jQuery formValidator表单验证插件,它是基于jQuery类库,实现了js脚本于页面html代码的分离。你可以划分多个校验组,每个组的校验都是互不影响。对一个表单对象,你只需要写一行代码就可以轻松实现无数种(理论上)脚本控制。目前支持5种大的校验方式,分别是:inputValidator(针对input、textarea、select控件的字符长度、值范围、选择个数的控制)、compareValidator(提供2个对象的比较,目前可以比较字符串和数值型)、ajaxValidator(通过ajax到服务器上做数据校验)、regexValidator(提供可扩展的正则表达式库)、functionValidator (可使用外部函数来做校验) 本插件于其他校验控件最大的区别有3点: 1、校验功能可以扩展。 对中文、英文、数字、整数、实数、Email地址格式、基于HTTP协议的网址格式、电话号码格式、手机号码格式、货币格式、邮政编码、身份证号码、QQ号码、日期等等这些控制,别的表单校验控件是代码里写死的,而formValidator是通过外部js文件来扩展的,你可以通过写正则表达式和函数来无限的扩展这些功能。 2、实现了校验代码于html代码的完全分离。 你的所有信息都无需配置在校验表单元素上,你只要在js上配置你的信息。使美工(界面)和javascript工程师的工作不交织在一起 3、你只需写一行代码就能完成一个表单元素的所有校验。你只需要写一行代码就能完成一下所有的控制 ?支持所有类型客户端控件的校验 ?支持jQuery所有的选择器语法,只要控件有唯一ID和type属性 ?支持函数和正则表达式的扩展。提供扩展库formValidatorReg.js,你可以自由的添加、修改里面的内容。 ?支持2种校验模式。第一种:文字提示(showword模式);第二种:弹出窗口提示(showalert模式) ?支持多个校验组。如果一个页面有多个提交按钮,分别做不同得提交,提交前要做不同的校验,所以你得用到校验组的功能。 ?支持4种状态的信息提示功能,可以灵活的控制4种状态是否显示。第一种:刚打开网页的时候进行提示;第二种:获得焦点的时候进行提示;第三种:失去焦点时,校验成功时候的提示;第四种:失去焦点时,校验失败的错误提示。 ?支持自动构建提示层。可以进行精确的定位。 ?支持自定义错误提示信息。
JQuery笔记-表单验证大全
jquery.validate.js 是 jquery 旗下的一个验证插件,借助 jquery 的优势,我们可以迅速验证一些常见的输入 , 并且可以自己扩充自己的验证方法。 举个例子,有这么一个表单: view plaincopy to clipboardprint?