服务器端验证用户输入数据步骤
1 html页面上插入要输入数据控件
|
1
2
3
4 |
<h:inputText size="10"
value="#{commodityBean.foradd.name}" id="input1"> <f:validator validatorId="input1Validator"
/> </h:inputText> <h:message for="input1"></h:message> |
这里要用input1Validator验证inputText控件的数值。 然后结果用message形式返回。真正验证的逻辑端在服务端执行。
2 在web-info文件夹下的face-config.xml里面写入
|
1
2
3
4
5
6
7
8 |
<validator> <validator-id> input1Validator</validator-id> <validator-class> com.fujitsu.softbg.zl.input1Validator</validator-class> </validator> |
通知服务器制动去找com.fujitsu.softbg.zl文件夹下的input1Validator.java文件。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 |
package
com.fujitsu.softbg.zl;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.faces.application.FacesMessage;import javax.faces.component.UIComponent;import javax.faces.context.FacesContext;import javax.faces.validator.Validator;import
javax.faces.validator.ValidatorException;public
class input1Validator implements
Validator { @Override public
void validate(FacesContext arg0, UIComponent arg1, Object arg2) throws
ValidatorException { // TODO Auto-generated method stub String inputvalue=arg2.toString(); String regEx="[0-9.]+";//表示一个或多个数字 Pattern p=Pattern.compile(regEx); //编译成模式 Matcher m=p.matcher(inputvalue); //创建一个匹配器 boolean
rs=m.matches(); if(!rs){ FacesMessage message = new
FacesMessage( FacesMessage.SEVERITY_ERROR, "not a vaild number", "not a vaild number"); throw
new ValidatorException(message); } }} |
这里验证用户输入的数据是0到9和小数点。如果不符合就返回提示消息。在服务端也可以像javascript一样用逻辑表达式的方式验证用户输入的字符。
原文地址:http://www.cnblogs.com/j3eee/p/3764369.html