Struts的ActionForm表单验证
(2007-05-08 11:41:34)
struts-config.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<data-sources />
<form-beans >
<form-bean name="registerForm" type="com.sunxin.struts.form.RegisterForm" />
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings >
<action
attribute="registerForm"
input="/register.jsp"
name="registerForm"
path="/register"
scope="request"
type="com.sunxin.struts.action.RegisterAction"
validate="true">
<forward name="success" path="/pages/success.jsp" />
<forward name="failure" path="/pages/failure.jsp" />
</action>
</action-mappings>
<message-resources parameter="com.sunxin.struts.ApplicationResources" />
<!--
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
-->
</struts-config>
RegisterForm.java
//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.1.1/xslt/JavaClass.xsl
package com.sunxin.struts.form;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.validator.ValidatorForm;
/**
* MyEclipse Struts Creation date: 05-02-2007
*
* XDoclet definition:
*
* @struts.form name="registerForm"
*/
//若继承自ValidatorForm,则validate()方法不要,并且要配置好
//validator-rules.xml文件和validation.xml文件
public class RegisterForm extends {
// --------------------------------------------------------- Instance
// Variables
/** sex property */
private Byte sex;
/** password property */
private String password;
/** username property */
private String username;
/** email property */
private String email;
/** pwdAnswer property */
private String pwdAnswer;
/** pwdQuestion property */
private String pwdQuestion;
// --------------------------------------------------------- Methods
/**
* Returns the sex.
*
* @return Byte
*/
public Byte getSex() {
return sex;
}
/**
* Set the sex.
*
* @param sex
* The sex to set
*/
public void setSex(Byte sex) {
this.sex = sex;
}
/**
* Returns the password.
*
* @return String
*/
public String getPassword() {
return password;
}
/**
* Set the password.
*
* @param password
* The password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Returns the username.
*
* @return String
*/
public String getUsername() {
return username;
}
/**
* Set the username.
*
* @param username
* The username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Returns the email.
*
* @return String
*/
public String getEmail() {
return email;
}
/**
* Set the email.
*
* @param email
* The email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Returns the pwdAnswer.
*
* @return String
*/
public String getPwdAnswer() {
return pwdAnswer;
}
/**
* Set the pwdAnswer.
*
* @param pwdAnswer
* The pwdAnswer to set
*/
public void setPwdAnswer(String pwdAnswer) {
this.pwdAnswer = pwdAnswer;
}
/**
* Returns the pwdQuestion.
*
* @return String
*/
public String getPwdQuestion() {
return pwdQuestion;
}
/**
* Set the pwdQuestion.
*
* @param pwdQuestion
* The pwdQuestion to set
*/
public void setPwdQuestion(String pwdQuestion) {
this.pwdQuestion = pwdQuestion;
}
/* (non-Javadoc)
* @see org.apache.struts.action.ActionForm#validate(org.apache.struts.action.ActionMapping, javax.servlet.http.HttpServletRequest)
*/
public ActionErrors validate(ActionMapping mapping,HttpServletRequest request){
ActionErrors errors = new ActionErrors();
if(null==username||"".equals(username)){
ActionError error1 = new ActionError("error.register.username.notnull");
//ActionMessage msg1 = new ActionMessage("error.register.username.notnull");
errors.add("username",error1);
}
if(null==password|"".equals(password)){
ActionError error2 = new ActionError("error.register.password.notnull");
errors.add("password",error2);
}
return errors;
}
/*
* (non-Javadoc)
*
* @see org.apache.struts.action.ActionForm#reset(org.apache.struts.action.ActionMapping,
* javax.servlet.http.HttpServletRequest)
*/
public void reset(ActionMapping arg0, HttpServletRequest arg1) {
// TODO Auto-generated method stub
// super.reset(arg0, arg1);
// 将请求改为GBK编码,必须在表单被后来的业务逻辑使用之前改过来!否则无效
try {
arg1.setCharacterEncoding("GBK");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
sex = new Byte("1");
}
}
RegisterAction.java
//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.1.1/xslt/JavaClass.xsl
package com.sunxin.struts.action;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.sunxin.struts.lession02.dao.RegUserDAO;
import org.sunxin.struts.lession02.entity.RegUser;
import org.sunxin.struts.lession02.entity.RegUserId;
import org.sunxin.struts.lession02.exception.UsernameExistException;
/**
* MyEclipse Struts Creation date: 05-02-2007
*
* XDoclet definition:
*
* @struts.action path="/register" name="registerForm" input="/register.jsp"
* scope="request"
* @struts.action-forward name="success" path="/WEB-INF/pages/success.jsp"
* @struts.action-forward name="failure" path="/WEB-INF/pages/failure.jsp"
*/
public class RegisterAction extends Action {
// --------------------------------------------------------- Instance
// Variables
// --------------------------------------------------------- Methods
/**
* Method execute
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
//为了防止乱码 必须 赶在 ActionForm提交之前进行转换
//在RegisterForm.java的reset()方法对request重新编码
// RegisterForm registerForm = (RegisterForm) form;
// TODO Auto-generated method stub
RegUser user = new RegUser();
try {
System.out.println("OK!");
BeanUtils.copyProperties(user, form);
user.setRegDate(new Date());
user.setLastLoginIp(request.getRemoteAddr());
// user.setLastLoginDate();
// 插入id(最难搞定)
String password = request.getParameter("password");
RegUserId id = new RegUserId();
id.setId(new Integer(3));
id.setPassword(password);
user.setId(id);
// 执行数据的插入
RegUserDAO userDAO = new RegUserDAO();
userDAO.register(user);
return mapping.findForward("success");
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//同名用户已经存在,抛出一个异常
catch (UsernameExistException e) {
//ActionMessage构造函数的第二个参数是资源文件里面error项的第一个参数{0}
ActionMessage msg = new ActionMessage("error.register.username.exist",user.getUsername());
ActionMessages messages = new ActionMessages();
messages.add("register.username",msg);
//将错误集合放到request对象中
try{
//在这个版本的struts中 saveErrors(),无法传递ActionMessages类参数
//saveErrors(request,messages);
saveMessages(request,messages);
}catch(java.lang.ClassCastException e2){
e2.printStackTrace();
}
}
return mapping.findForward("failure");
}
}