Bean主体类
package Adam.Bean;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.beans.VetoableChangeSupport;
public class MyJavaBean {
public MyJavaBean() {
propertySupport = new PropertyChangeSupport(this);
vetoableSupport = new VetoableChangeSupport(this);
}
public void setSex(String newSex) {
if (!newSex.equals(sex)) {
String oldValue = sex;
// 属性验证
try {
vetoableSupport.fireVetoableChange("changesex", sex, newSex);
// 没的被阻止
sex = newSex;
} catch (Exception e) {
System .out.println("禁止修改");
}
propertySupport.firePropertyChange("changesex", oldValue, newSex);
}
}
public String getSex()
{
return this.sex;
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertySupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertySupport.removePropertyChangeListener(listener);
}
public void addVetoableChangeListener(VetoableChangeListener listener) {
vetoableSupport.addVetoableChangeListener(listener);
}
public void removeVetoableChangeListener(VetoableChangeListener listener) {
vetoableSupport.removeVetoableChangeListener(listener);
}
private String sex="male";
PropertyChangeSupport propertySupport;
VetoableChangeSupport vetoableSupport;
}
事件类
package Adam.Bean;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
public class MyJavaBeanPropertyListener implements PropertyChangeListener,
VetoableChangeListener {
@Override
public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
if (evt.getNewValue().equals("female")) {
// 处理监听到的事件
System.out.println("\"NewValue:\"" + evt.getNewValue() + "\"OldValue:\"" + evt.getOldValue() + "\"");
throw new PropertyVetoException("禁止变性", evt);
}
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("\"NewValue:\"" + evt.getNewValue() + "\"OldValue:\"" + evt.getOldValue() + "\"");
}
}
JSP文件
pageEncoding="UTF-8"%>
Insert title heremyBean.addPropertyChangeListener(new MyJavaBeanPropertyListener());
myBean.addVetoableChangeListener(new MyJavaBeanPropertyListener());
%>