hi, this is my first web-based project using struts2.0. I met a problem when
using the validation . It seems the error message haven't been cleared and
each time I submit the form, then the error message was added after the
previous error message, it means if i submit 10 times, then there will
display 10 error message, 10 of the same. any help would be appreciated.

struts-app.xml:
<package name="account" namespace="/" extends="default">
    <global-results>
           <result name="input">jsp/account/account.jsp</result>
    <result name="login_input">index.jsp</result>
       </global-results>

       <action name="account_save" method="save" class="AccountAction">
    <interceptor-ref name="myStack"/>
 </action>
 <action name="account_*" method="{1}" class="AccountAction" >
  <result name="create_success">/jsp/message.jsp</result>
    <result name="create_failed">/jsp/message.jsp</result>
    <result name="delete_success">/jsp/message.jsp</result>
    <result name="wellcome">test.jsp</result>
    <result name="list">jsp/account/userList.jsp</result>
    <result name="account_role">jsp/account/userRole.jsp</result>
    <result name="person_input">jsp/account/personSet.jsp</result>
 </action>
</package>

AccountAction:
Jsp:
validation.xml

see the files.

the error message look just like this;
*string length shoule be 4-10 *string length shoule be 4-10 *string length
shoule be 4-10 *string length shoule be 4-10 *string length shoule be
4-10 *string
length shoule be 4-10 *string length shoule be 4-10 *string length shoule be
4-10 *string length shoule be 4-10 *string length shoule be 4-10
<[EMAIL PROTECTED] contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>
<head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link 
href="${pageContext.request.contextPath}/styles/extremecomponents.css" 
rel="stylesheet" type="text/css">
        <link href="${pageContext.request.contextPath}/styles/gehouse.css" 
rel="stylesheet" type="text/css">

<script type="text/JavaScript">
<!--
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; 
i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) 
x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) 
{
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) 
x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) 
x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; 
for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) 
x.oSrc=x.src; x.src=a[i+2];}
}
//-->
function  check(){
        
        var form = window.document.forms["account_form"];
        if(form["account.loginname"].value.length == 0){
                alert('登陆名不能为空!');
                form["account.loginname"].focus();
                return false;
        }

        if(form["account.name"].value.length==0){
                alert('用户姓名不能为空!');
                form["account.name"].focus();
                return false;
        }
        form.action="account_save.shtml";
        form.submit();
}
//var 
strURL='/jsp/messagebox.jsp?title=增加用户&msg=是否确认增加用户&type=save&actionUrl=AddUserAction!Add.shtml&doaction=AddUserAction';
//window.open(strURL,'_blank','status=no,resizable=0,toolbar=no,menubar=no,scrollbars=auto,width=30,height=50');

</script>
</head>
<body 
onLoad="MM_preloadImages('${pageContext.request.contextPath}/images/extream/lastPage.gif','${pageContext.request.contextPath}/images/extream/firstPageDisabled.gif','../images/extream/prevPageDisabled.gif','../images/extream/nextPageDisabled.gif','${pageContext.request.contextPath}/images/extream/lastPageDisabled.gif')">

 <s:form name="account_form" validate="false"> 

 <s:token></s:token>
 <s:hidden name="id"/>
                <s:url id="url" value="account!active.shtml">
                        <s:param name="id"><s:property 
value="account.id"/></s:param>
                        <s:param name="active"><s:property 
value="account.active"/></s:param>
                </s:url>
                <s:url id="url1" value="account!resetPassword.shtml">
                        <s:param name="id"><s:property 
value="account.id"/></s:param>
                </s:url>
<table  width="100%"  border="0"  cellpadding="0"  cellspacing="0">

    <tr style="padding: 0px;" >
     
      <td >

      <table width="100%" height="30" border="0" cellpadding="0" 
cellspacing="1" >
        <tr>
          <td width="45" height="40" align="right"><img 
src="${pageContext.request.contextPath}/images/extream/add.gif" width="27" 
height="30"></td>
          <td><span class="navigate">&nbsp;&nbsp;&nbsp;
          <s:if test="id == 0">
                添加用户
          </s:if>
          <s:else>编辑用户[<s:property value="account.loginname"/>]    
          <td align="right"> 
          <s:a href="%{url}">[冻结帐号]</s:a>
          &nbsp;&nbsp;<s:a href="%{url1}">[密码复位]</s:a>
          </td>
          </s:else>
          </span>
          </td>
        </tr>
      </table></td>
    </tr>
    <tr style="padding: 0px;" >

       <td colspan="2" valign="top">
        <div class="eXtremeTable">
      <table  width="100%"  border="0"  cellpadding="0"  cellspacing="1" 
bgcolor="#C5E3FF">
   
            <tr class="odd" >
              <td  width="13%" align="right" class="bgtitle"  ><FONT 
color=ff9933>*</FONT> 登陆名称:</td>
              <td width="87%"><s:textfield  name="account.loginname"  size="15" 
maxlength="20"/><s:fielderror><s:param>account.loginname</s:param></s:fielderror></td>
            </tr>
            <tr class="odd"   >
              <td  width="13%" align="right" class="bgtitle"  ><FONT 
color=ff9933>*</FONT> 用户名称:</td>
              <td width="87%"><s:textfield  name="account.name"  size="15" 
maxlength="20"/><s:fielderror><s:param>account.name</s:param></s:fielderror></td>
            </tr>
            <tr class="odd"  >
              <td  width="13%"  align="right" class="bgtitle"  
>电子邮件:</td>
              <td><s:textfield   name="account.email" size="15" 
maxlength="20"/></td>
            </tr>
            <s:hidden name="retRef"><s:property value="#retRef"/></s:hidden>
            <tr class="odd"   >
              <td  width="13%"  align="right" class="bgtitle" 
>联系电话:</td>
              <td><s:textfield   name="account.phone" size="15" 
maxlength="20"/></td>
            </tr>            
        </table>

        </td>
    </tr>
    <tr style="padding: 0px;" >
      <td height="50" align="center" ><a href="#" 
onMouseOut="MM_swapImgRestore()" 
onMouseOver="MM_swapImage('Image3','','${pageContext.request.contextPath}/images/extream/chongshu1.gif',1)"><img
 src="${pageContext.request.contextPath}/images/extream/chongshu2.gif" 
name="Image3" width="63" height="20" border="0">&nbsp;&nbsp;&nbsp;&nbsp;</a><a 
href="#" onclick="check()" onMouseOut="MM_swapImgRestore()" 
onMouseOver="MM_swapImage('Image9','','${pageContext.request.contextPath}/images/extream/baocun2.gif',1)"><img
 src="${pageContext.request.contextPath}/images/extream/baocun1.gif" 
name="Image9" width="49" height="20" border="0"></a></td>
    </tr>

</table>
</s:form>
</body>
</html>
package com.gehouse.admin.web.action.account;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.gehouse.admin.bean.account.TXAccount;
import com.gehouse.admin.bean.account.TXAccountRole;
import com.gehouse.admin.bean.account.TXRole;
import com.gehouse.admin.service.ServiceException;
import com.gehouse.admin.util.Constants;
import com.gehouse.admin.util.OptionsLong;
import com.gehouse.admin.web.action.BaseCrudAction;

public class AccountAction extends BaseCrudAction {

        private static final long serialVersionUID = 1L;

        private static final Log logger = 
LogFactory.getLog(AccountAction.class);

        private TXAccount account = null;

        private String validat = null; // 登陆验证码

        private boolean active;

        private List<OptionsLong> roleValues = null;

        private List roles = new ArrayList();

        private List<TXAccountRole> userRole = null;

        private List<TXRole> allRole = null;

        private int accountId;
        
        private String retRef; 

        public String getRetRef() {
                return retRef;
        }

        public void setRetRef(String retRef) {
                this.retRef = retRef;
        }

        public boolean isActive() {
                return active;
        }

        public void setActive(boolean active) {
                this.active = active;
        }

        public String getValidat() {
                return validat;
        }

        public void setValidat(String validat) {
                this.validat = validat;
        }

        AccountAction() {
        }

        public int getId() {
                return account == null ? 0 : account.getId();
        }

        public void setId(int id) {
                if (account == null)
                        account = new TXAccount();

                account.setId(id);
        }

        public String newObject() {
                account = new TXAccount();
                this.retRef = request().getHeader("Referer");
                return INPUT;
        }

        /**
         * 创建用户帐号
         * 
         * 帐号的初始密码为:111111
         */
        public String create() {
                // 判断是否重复提交
                if (!this.checkToken()) {
                        return "invalid.token";
                }
                try {
                        // 注册用户登陆名判断
                        TXAccount tmpAccount = 
this.getDomain().getAccountService().ifLoginnameUsed(account.getLoginname());
                        if (null != tmpAccount) {
                                // 注册用户登陆名重复
                                this.request().setAttribute("message", 
"注册用户名已经存在faile!");
                                return "create_failed";
                        } else {
                                
account.setPassword("96e79218965eb72c92a549dd5a330112");// 
初始密码111111,MD5加密
                                
this.getDomain().getAccountService().createAccount(account);
                                
this.addActionMessage(this.getText("useradd.succuess"));
                                this.request().setAttribute("message", "注册" 
+ account.getLoginname() + "用户成功success!");
                                if(this.retRef != null){
                                        response().sendRedirect(retRef);
                                        return null;
                                }
                                return "create_success";
                        }
                } catch (ServiceException e) {
                        e.printStackTrace();
                        return INPUT;
                } catch (IOException e) {
                        e.printStackTrace();
                        return ERROR;
                }
        }

        /**
         * 帐号信息维护
         * 
         * 根据id获得帐号信息
         */
        public String edit() {
                try {
                        this.retRef = request().getHeader("Referer");
                        // 根据用户id查询当前用户信息
                        System.err.print(account.getId());
                        account = 
getDomain().getAccountService().getAccount(account.getId());
                        if (account == null) {
                                
this.addActionError(this.getText("usermodify.error"));
                                return ERROR;
                        }

                } catch (ServiceException e) {
                        String message = "<HR color=red>系统信息:<font 
color=red>" + getClass().getName() + "**" + e.getMessage()
                                        + "</font>";
                        this.request().setAttribute("message", message);
                        this.addActionError(this.getText("usermodify.error"));
                        return ERROR;
                }
                return INPUT;
        }

        /**
         * 帐号更新
         * 
         */
        public String update() {
                if (this.hasFieldErrors()) {
                        return INPUT;
                }

                try {
                        
account.setPassword("96e79218965eb72c92a549dd5a330112");// 初始密码111111
                        
this.getDomain().getAccountService().updateAccount(account);
                        
this.addActionMessage(this.getText("usermodify.success"));
                        if(this.retRef != null){
                                response().sendRedirect(retRef);
                                return null;
                        }
                        return "create_success";
                } catch (ServiceException e) {
                        e.printStackTrace();
                        this.addActionMessage(this.getText("usermodify.error"));
                        return ERROR;
                } catch (IOException e) {
                        e.printStackTrace();
                        this.addActionMessage("返回列表页出错!");
                        return ERROR;
                }
        }

        /**
         * 个人帐号维护初始化
         * 
         * 个人帐号信息从session中获得 
根据帐号id,从数据库获得帐号信息
         * 
         * @return
         */
        public String personInit() {
                account = (TXAccount) 
this.session().getAttribute(Constants.USER_KEY);
                try {
                        account = 
this.getDomain().getAccountService().getAccount(account.getId());
                } catch (ServiceException e) {
                        e.printStackTrace();
                        return ERROR;
                }
                return "person_input";
        }

        /**
         * 更改维护自己的密码,和基本信息
         * 
         * @return
         */
        public String updatePassword() {
                try {
                        
this.getDomain().getAccountService().updateAccount(account);

                        
this.addActionMessage(this.getText("personmodify.succuess"));
                        return "create_success";
                } catch (ServiceException e) {
                        
this.addActionMessage(this.getText("personmodify.error"));
                        return ERROR;
                }
        }

        /**
         * 密码复位
         * 
         * 在用户维护中可以对帐号密码复位 
复位后密码为初始值:111111
         * 
         * @return
         */
        public String resetPassword() {
                try {
                        // 密码复位
                        
this.getDomain().getAccountService().resetPasswd(account.getId());

                        
this.addActionMessage(this.getText("user.repassword.success"));
                        return "create_success";
                } catch (ServiceException e) {
                        e.printStackTrace();
                        
this.addActionError(this.getText("user.repassword.error"));
                        return ERROR;
                }
        }

        /**
         * 帐号删除
         * 
         */
        public String delete() {
                try {
                        if(this.checkToken()) {
                                // 根据用户id进行删除操作
                                
this.getDomain().getAccountService().deleteAccount(getId());
                                
this.addActionMessage(this.getText("userdelete.succuess"));
                        }
                        this.retRef = request().getHeader("Referer");
                        if(this.retRef != null){
                                response().sendRedirect(retRef);
                                return null;
                        }
                } catch (ServiceException e) {
                        String message;
                        message = "<HR color=red>系统信息:<font color=red>" 
+ getClass().getName() + "**" + e.getMessage() + "</font>";
                        this.request().setAttribute("message", message);
                        this.addActionError(this.getText("userdelete.error"));
                        return ERROR;
                } catch (IOException e) {
                        e.printStackTrace();
                        this.addActionError("返回跳转页面时出错!");
                        return ERROR;
                }
                
                return "delete_success";
        }

        /**
         * 冻结帐号 更新帐号状态,帐号冻结,则不能使用。
         * 
         * @return
         */
        public String active() {
                try {
                        
this.getDomain().getAccountService().enableAccount(account.getId(), active);
                        
this.addActionMessage(this.getText("useractive.succuess"));
                        if (logger.isDebugEnabled())
                                
this.addActionMessage(this.getText("useractive.succuess"));
                } catch (ServiceException e) {
                        String message;
                        message = "<HR color=red>系统信息:<font color=red>" 
+ getClass().getName() + "**" + e.getMessage() + "</font>";
                        this.request().setAttribute("message", message);
                        this.addActionError(this.getText("useractive.error"));
                        return ERROR;
                }
                return "create_success";
        }

        /**
         * 帐号权限维护初始化
         * 
         * @return
         */
        public String accountRoleInit() {
                this.getRoleValuesInit();
                this.retRef = request().getHeader("Referer");
                return "account_role";
        }

        /**
         * 帐号权限维护 根据帐号id
         * 
         * @return
         */
        public String accountRole() {
                // 删除该用户所有的角色

                try {
                        
this.getDomain().getAccountService().deleteAccountRole(accountId);
                        // 添加新的角色
                        TXAccountRole accoutRole = new TXAccountRole();
                        if (roles != null) {
                                for (int i = 0; i < roles.size(); i++) {
                                        accoutRole.setAccount(accountId);
                                        accoutRole.setRole((new 
Integer((String) roles.get(i))).intValue());
                                        
this.getDomain().getAccountService().createAccountRole(accoutRole);
                                }
                        }
                        
this.addActionMessage(this.getText("user.role.add.success"));
                        if(this.retRef != null){
                                response().sendRedirect(retRef);
                                return null;
                        }
                        return "create_success";
                } catch (ServiceException e) {
                        e.printStackTrace();
                        this.request().setAttribute("message", 
getErrorMessageTitle() + e.getMessage());
                        
this.addActionError(this.getText("user.role.add.error"));
                        return ERROR;
                } catch (IOException e) {
                        e.printStackTrace();
                        this.addActionError("返回列表页时出错!");
                        return ERROR;
                }
        }

        /**
         * 初始化帐号角色
         * 
         * @return
         */
        private void getRoleValuesInit() {

                try {
                        allRole = 
this.getDomain().getAccountService().getRoleList();
                        userRole = 
this.getDomain().getAccountService().getAccountRole(accountId);
                        roleValues = new ArrayList<OptionsLong>();
                        for (int i = 0; i < allRole.size(); i++) {
                                for (int j = 0; j < userRole.size(); j++) {
                                        if ((userRole.get(j).getRole() == 
allRole.get(i).getId())) {
                                                
roles.add(Long.valueOf(allRole.get(i).getId()));
                                        }
                                }
                                roleValues.add(new 
OptionsLong(allRole.get(i).getId(), allRole.get(i).getName() + "("
                                                + allRole.get(i).getId() + 
")"));
                        }
                } catch (ServiceException e) {
                        e.printStackTrace();
                }

        }

        /**
         * 帐号登录
         * 
         * @return
         */
        public String login() {
                
                if(session().getAttribute(Constants.USER_KEY) != null)
                        return "wellcome";
                
                if (isInvalid(account.getLoginname()) || 
isInvalid(account.getPassword()) || isInvalid(getValidat())) {
                        this.addActionError(this.getText("requiredstring"));
                        this.validat = null;
                        this.account = null;
                        return "login_input";
                }

                if (!this.session().getAttribute("validcode").equals(validat)) {
                        this.addActionError(this.getText("validat.error"));
                        this.validat = null;
                        this.account = null;
                        return "login_input";
                }

                this.validat = null;
                
                if ((!account.getLoginname().equals("") || null != 
account.getLoginname())
                                && (!account.getPassword().equals("") || null 
!= account.getPassword())) {

                        try {
                                TXAccount tmpAccount = null;
                                tmpAccount = 
this.getDomain().getAccountService().getRoles(account.getLoginname(),
                                                account.getPassword());
                                if (null != tmpAccount) {
                                        
this.session().setAttribute(Constants.USER_KEY, tmpAccount);
                                        return "wellcome";
                                } else {
                                        
this.addActionError(this.getText("用户名,密码不正确!"));
                                        return "login_input";
                                }

                        } catch (ServiceException e) {
                                e.printStackTrace();
                                logger.error(e);
                        }

                }
                return "wellcome";
        }

        /**
         * 退出系统
         * 
         * @return
         */
        public String logout() {

                if (null != this.session().getAttribute(Constants.USER_KEY)) {

                        this.session().removeAttribute(Constants.USER_KEY);
                        this.session().invalidate();
                }
                return "login_input";
        }

        /**
         * 用户帐号显示列表
         * 
         */
        public String list() {
                int userCount;
                try {
                        userCount = 
getDomain().getAccountService().getUserCount();
                        List pageList = 
getDomain().getAccountService().getUserList();
                        request().getSession().setAttribute("_userCount", 
userCount);
                        request().getSession().setAttribute("_userList", 
pageList);
                } catch (ServiceException e) {
                        e.printStackTrace();
                        return ERROR;
                }
                return "list";
        }

        public TXAccount getAccount() {

                if (account == null && isPost())
                        account = new TXAccount();

                return account;
        }

        public void setAccount(TXAccount account) {
                this.account = account;
        }

        private boolean isInvalid(String value) {
                return (value == null || value.length() == 0);
        }

        public List<TXRole> getAllRole() {
                return allRole;
        }

        public void setAllRole(List<TXRole> allRole) {
                this.allRole = allRole;
        }

        public List<Long> getRoles() {
                return roles;
        }

        public void setRoles(List<Long> roles) {
                this.roles = roles;
        }

        public List<OptionsLong> getRoleValues() {
                return roleValues;
        }

        public void setRoleValues(List<OptionsLong> roleValues) {
                this.roleValues = roleValues;
        }

        public List<TXAccountRole> getUserRole() {
                return userRole;
        }

        public void setUserRole(List<TXAccountRole> userRole) {
                this.userRole = userRole;
        }

        public int getAccountId() {
                return accountId;
        }

        public void setAccountId(int accountId) {
                this.accountId = accountId;
        }
}
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd";>


<validators>
	<field name="account.name">
		<field-validator type="requiredstring">
		    <param name="trim">true</param>
			<message>用户名不可为空!</message>
		</field-validator>
		<field-validator type="stringlength">
            <param name="trim">true</param>
            <param name="minLength">4</param>
            <param name="maxLength">10</param>
            <message>长度为4-10</message>
        </field-validator>
	</field>
	<field name="account.loginname">
		<field-validator type="requiredstring">
			<message>登陆名不可为空,且为整数!</message>
		</field-validator>
		<field-validator type="stringlength">
            <param name="trim">true</param>
            <param name="minLength">4</param>
            <param name="maxLength">10</param>
            <message>长度为4-10</message>
        </field-validator>
	</field>
	
</validators>
package com.gehouse.admin.web.action;

public abstract class BaseCrudAction extends BaseAction {

        private static final long serialVersionUID = 1L;
        
        private int id ;
        
        public abstract String newObject();
        public abstract String create();
        public abstract String edit();
        public abstract String update();
        public abstract String delete();
        
        public String save()
        {
                if(getId() == 0)
                        return create();
                else
                        return update();
        }
        
        public String list() throws Exception {
                throw new Exception("not support!");
        }
        
        public int getId() {
                return id ;
        }
        
        public void setId(int id) {
                this.id = id ;
        }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to