接口:
清单 48. 验证器接口
package com.arcmind.contact.model;
public interface Validateable {
public void validate() throws ValidationException;
}
然后修改 Contact 对象,让它实现这个接口,见清单 49:
清单 49. Contact 实现验证器接口
package com.arcmind.contact.model;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@SuppressWarnings("serial")
public class Contact implements Serializable, Validateable {
...
public void validate() throws ValidationException {
if (
homePhoneNumber == null &&
workPhoneNumber == null &&
mobilePhoneNumber == null
) {
throw new ValidationException("At least one phone number " +
"must be set", "");
}
}
...
可以创建一个 PhaseListener 寻找并检验 Validateable 对象。这个 PhaseListener 可以接收异常 消息并把它们转换为 FacesMessage,但是如何知道什么时候需要检验对象呢?看起来这一信息只能放在 控制器类中。因此,为了按照通用方式处理这个问题,可以编写一个超类控制器,它创建一个匿名的内部 类 PhaseListener,您可以绑定到这个内部类,见清单 50:
清单 50. 包含 PhaseListener 的基类
package com.arcmind.contact.controller;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import com.arcmind.contact.model.Validateable;
import com.arcmind.contact.model.ValidationException;
@SuppressWarnings("serial")
public abstract class AbstractCrudController implements Serializable {
private boolean edit;
public PhaseListener phaseListener = new PhaseListener() {
public void afterPhase(PhaseEvent event) {
validate();
}
public void beforePhase(PhaseEvent event) {
}
public PhaseId getPhaseId() {
return PhaseId.UPDATE_MODEL_VALUES;
}
};
abstract Object getFormObject(); //subclass defines this
private void validate() {
Object form = getFormObject();
if (! (form instanceof Validateable) || form == null) {
return;
}
Validateable validateable = (Validateable) form;
try {
validateable.validate(); //validate object
} catch (ValidationException validationException) {
FacesContext.getCurrentInstance().renderResponse(); //Do not invoke application.
addErrorMessage(validationException.getMessage());
}
}
public PhaseListener getPhaseListener() {
return phaseListener;
}
protected void addErrorMessage(String message) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, message, null));
}
public boolean isEdit() {
return edit;
}
public void setEdit(boolean edit) {
this.edit
|