---
title: "Struts2 validate"
author: "fosa0989"
date: "2009-04-17T16:13:35Z"
tags: []
categories: ["企业架构"]
slug: "struts2-validate"
draft: false
lastmod: "2009-05-04T00:18:19Z"
id: 369668
url: "https://hchen229.iteye.com/blog/369668"
---

如何让Validate验证只验证指定的方法？
比如updateUser()方法，如果实现validate方法，Action的所有其它方法被调用的时候都会调用，这不是我要的。
方法就是定义一个和updateUser()方法匹配的validate方法validateUpdateUser(),**此方法必须是public的**。例如：

```java
	public String updateUser()throws Exception
	{
		User old=userService.getUserByID(user.getUserID());	
		old.setUserName(user.getUserName());
		old.setUserSN(user.getUserSN());
		old.setAddress(user.getAddress());
		//old.setBirthday(birthday);
		old.setEmail(user.getEmail());
		old.setLoginName(user.getLoginName());
		old.setMobilePhone(user.getMobilePhone());
		old.setMSN(user.getMSN());
		old.setPostalCode(user.getPostalCode());
		old.setQQ(user.getQQ());
		old.setSex(user.getSex());
		
		userService.saveUser(old);
		return SUCCESS;		
	}
	
	public boolean validateUpdateUser(){
		boolean result=true;
		User snp=userService.getBySN(user.getUserSN());
		if(snp!=null&&snp.getUserID().longValue()!=user.getUserID().longValue())//new privilegeSN exists
		{
			addFieldError("user.userSN","SN exists.");
			result=false;
		}
		snp=userService.getByLoginName(user.getLoginName());
		if(snp!=null&&snp.getUserID().longValue()!=user.getUserID().longValue()){
			addFieldError("user.loginName","loginname exists.");
			result=false;			
		}
		
		if(result==false){
			User old=userService.getUserByID(user.getUserID());
			request.put(Constants.USER_OBJECT, old);
		}
		return result;		
	}
```

此外在struts.xml文件的Action配置中必须为Action指定一个input

```java
		<action name="updateUser" class="userAction" method="update">
			<result name="success" type="redirect">listUser.action</result>
			<result name="input">/page/user/edit.jsp</result>
		</action>
```
![](http://img.tongji.cn.yahoo.com/1083199/ystat.gif)