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文件
<%@page import="Adam.Bean.MyJavaBeanPropertyListener"%> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="UTF-8"%> <jsp:useBean id="myBean" class="Adam.Bean.MyJavaBean" scope="page"></jsp:useBean> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <% myBean.addPropertyChangeListener(new MyJavaBeanPropertyListener()); myBean.addVetoableChangeListener(new MyJavaBeanPropertyListener()); %> <jsp:getProperty property="sex" name="myBean"/> <jsp:setProperty property="sex" name="myBean" value="female"/> <br/> <jsp:getProperty property="sex" name="myBean"/> </body> </html>