这是我学习JSF的一点总结:
我会给大家见绍三种类型的验证:
1.js
2.消息验证标签
3.validator
一、jsp页面:
大家可以参照我标注颜色的代码:
<%@ page language="java" pageEncoding="gb2312"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JSF 登录界面</title>
<script language="JavaScript">
<!--
function CheckInformation()
{
if (document.getElementById("loginForm:number").value==""){
alert("学号不能为空!");
return false;
}
if (document.getElementById("loginForm:pwd").value==""){
alert("密码不能为空!");
return false;
}
}
-->
</script>
</head>
<body>
<f:view>
<h:form id="loginForm">
<h:panelGrid columns="3">
<h:outputLabel for="number" value="姓名:"></h:outputLabel>
<h:inputText id="number" required="true"
value="#{loginBean.number}" validator="#{loginBean.validate}"></h:inputText>
<h:message for="number"></h:message>
<h:outputLabel for="pwd" value="密码:"></h:outputLabel>
<h:inputSecret id="pwd" required="true" value="#{loginBean.pwd}">
<f:validator validatorId="passwordValidator"/>
</h:inputSecret>
<h:message for="pwd"></h:message>
</h:panelGrid>
<h:panelGrid columns="2">
<h:commandButton value="登录" action="#{loginBean.login}" οnclick=" return CheckInformation()"/>
<h:commandButton value="取消" type="reset" />
</h:panelGrid>
</h:form>
</f:view>
</body>
</html>
二、java关键代码
...
public void validate(FacesContext context, UIComponent component, Object obj) throws ValidatorException {
String number = (String) obj;
if (number.length() < 2) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "用户编号小于2", "用户编号小于2");
throw new ValidatorException(message);
}
...