表单数据验证主要分为数据格式上的合法性验证和逻辑上的有效性验证。例如,填写登录信息时要求必要的字段不能为空,这属于数据格式上的合法性验证,可以在服务器端进行、也可使用JavaScript等脚本程序在客户端实现。逻辑上的有效性验证,一般是对通过数据格式检查的用户身份信息进行验证、例如:判断是否为合法用户,通常在服务器端进行。
在服务器端:实现身份验证应用程序的表单数据格式验证
1.修改配置文件struts-config.xml,确保在需要进行表单验证的相关<action>元素中包含下述两个属性。
- validate : 用于表明是否进行表单验证。如果设定其值为TRUE,则STRUTS架构的RequestProcessor对象在使用表单数据填充ActionForm Bean时,会自动调用该Bean实例的validate( )方法进行验证。
- input:给出表单验证出错时要转向的错误处理页面。
<action-mappings>
<action path="/login" type="classmate.LoginAction" name="formBean1" scope="request" validate="true" input="/error.jsp" />
<action path="/regist" forward="/regist.jsp"/>
</action-mappings>
2.重写validate( )方法,实现表单验证
public class UserForm extends ActionForm {
........................................................... public void reset(ActionMapping mapping, HttpServletRequest request) {
this.name = null;
this.psw = null;
}
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if ((name == null) || (name.equals(""))){
errors.add(ActionErrors.GLOBAL_MESSAGE,new ActionMessage("error.psw.required"));
}
if((psw == null) || (psw.equals(""))){
errors.add(ActionErrors.GLOBAL_MESSAGE,new ActionMessage("error.psw.required"));
}
return errors;
}
}
3. 在错误处理JSP页面中(error.jsp)显示错误信息:
在服务器端:实现身份验证应用程序的表单数据业务逻辑验证
1. 修改Action Bean类 LoginAction 的 execute( )方法,在其中加入错误管理逻辑,实现对用户登录信息的进一步检查。
public final class LoginAction extends Action{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
UserForm userform = (UserForm) form;
String name = userform.getName();
String psw = userform.getPsw();
if("jenny".equals(name) && "hi".equals(psw)){
UserLoginLog ul = new UserLoginLog();
ul.save(name,psw);
return mapping.findForward("successed");
}else{
ActionMessages errors = new ActionMessages();
errors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("label.deny"));
if (!errors.isEmpty()) {
saveErrors(request, errors);
}
return mapping.findForward("failed");
}
}
}
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<h1><p><img src="cry.gif">
<html:errors/>