使用buffalo作为webwork的验证机制-实现
08 Feb 2006
要的人比较多,废话少说,放代码:
ValidationError.java, 主要是错误信息的一个DTO
[java]
public class ValidationError {
private String name;
private String value;
public ValidationError() {
}
public ValidationError(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
[/java]
ValidationService.java, buffalo要使用的service, 代码不复杂,没有注释,原理见前一篇文章
[java]
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.ActionProxy;
import com.opensymphony.xwork.DefaultActionInvocation;
import com.opensymphony.xwork.DefaultActionProxy;
import com.opensymphony.xwork.ValidationAware;
import com.opensymphony.xwork.config.entities.ActionConfig;
public class ValidationService {
public List validate(String namespace, String action, Map parameters) {
List errorList = new ArrayList();
Action requestedAction = null;
HashMap ctx = new HashMap();
ctx.put(ActionContext.PARAMETERS, parameters);
ValidatorActionProxy proxy;
try {
proxy = new ValidatorActionProxy(namespace, action, ctx);
proxy.execute();
requestedAction = proxy.getAction();
} catch (Exception e) {
e.printStackTrace();
return null;
}
if (requestedAction instanceof ValidationAware) {
ValidationAware va = (ValidationAware) requestedAction;
Map fe = va.getFieldErrors();
for (Iterator iterator = fe.entrySet().iterator(); iterator
.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
String name = (String) entry.getKey();
List errors = (List) entry.getValue();
for (Iterator iterator1 = errors.iterator(); iterator1
.hasNext();) {
String error = (String) iterator1.next();
errorList.add(new ValidationError(name, error));
}
}
}
return errorList;
}
public static class ValidatorActionInvocation extends
DefaultActionInvocation {
protected ValidatorActionInvocation(ActionProxy proxy, Map extraContext)
throws Exception {
super(proxy, extraContext, true);
}
protected String invokeAction(Action action, ActionConfig actionConfig)
throws Exception {
return Action.NONE; // don't actually execute the action
}
}
public static class ValidatorActionProxy extends DefaultActionProxy {
protected ValidatorActionProxy(String namespace,
String actionName,
Map extraContext) throws Exception {
super(namespace, actionName, extraContext, false);
}
protected void prepare() throws Exception {
invocation = new ValidatorActionInvocation(this, extraContext);
}
}
}
[/java]
buffalo-service.properties
[txt]
validationService=your.package.ValidationService
[/txt]
更改webwork模板中的simple/form.vm:
[html]