com.test.action.user包下:
SaveUserAction.java
SaveUserAction-validation.xml
SaveUserAction.java文件的内容:
package com.test.action.user;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import com.opensymphony.xwork2.ActionSupport;
import com.test.bean.User;
import com.test.service.UserService;
public class SaveUserAction extends ActionSupport
{
private User user;
private UserService service;
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
public UserService getService()
{
return service;
}
public void setService(UserService service)
{
this.service = service;
}
@Override
public String execute() throws Exception
{
this.service.save(this.user);
return SUCCESS;
}
@Override
@SuppressWarnings("unchecked")
public void validate()
{
Map map = this.getFieldErrors();
Set set = map.keySet();
for (Iterator iter = set.iterator(); iter.hasNext();)
{
System.out.println(map.get(iter.next()));
}
}
}
SaveUserAction-validation.xml的文件内容:
<?xml version="1.0" encoding="UTF-8"?>
<!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="user">
<field-validator type="visitor">
<param name="context">user</param>
<param name="appendPrefix">true</param>
<message>user's </message>
</field-validator>
</field>
</validators>
com.test.bean包下的文件:
User.java;
User-user-validation.xml
User-user-validation.xml文件的内容:
<?xml version="1.0" encoding="UTF-8"?>
<!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="firstname">
<field-validator type="requiredstring">
<message>required first name</message>
</field-validator>
</field>
<field name="lastname">
<field-validator type="requiredstring">
<message>required last name</message>
</field-validator>
</field>
<field name="age">
<field-validator type="required">
<message>required age</message>
</field-validator>
<field-validator type="int">
<param name="min">1</param>
<param name="max">150</param>
<message>age should be between ${min} and
${max}</message>
</field-validator>
</field>
</validators>
还有一个问题,就是校验信息会重复,在错误的情况下。由以下代码可以测试:
@Override
@SuppressWarnings("unchecked")
public void validate()
{
Map map = this.getFieldErrors();
Set set = map.keySet();
for (Iterator iter = set.iterator(); iter.hasNext();)
{
System.out.println(map.get(iter.next()));
}
}
}
解决方法:
applicationContext.xml 文件中的配置action中加入:Struts 2.0 的action 是有状态的
在spring 配置的action 中加上 scope="prototype";
配置如下:<bean id="saveUserAction"
class="com.test.action.user.SaveUserAction" scope="prototype">
<property name="service" ref="userService"></property>
</bean>