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">
<s:if test="id == 0">
æ·»å ç¨æ·
</s:if>
<s:else>ç¼è¾ç¨æ·[<s:property value="account.loginname"/>]
<td align="right">
<s:a href="%{url}">[å»ç»å¸å·]</s:a>
<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"> </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]