十分感谢!问题已解决!原来在selectOneMenu中的value属性要设成新值而不是旧值,这样页面上的新值和旧值就都能正常显示了。同时,在java文件里,定义这两个字段的时候还要赋值,不然会出现空指针异常。
package src;
import javax.faces.model.*;
import javax.faces.event.*;
public class ValueChangeListenerTest {
private SelectItem[] races = {new SelectItem("HUM"), new SelectItem("ORC"), new SelectItem("UD"), new SelectItem("NE")};
private String selectedRace = "";//要与selectOneMenu中的value对应,否则会出现空指针异常
private String oldRace = "HUM";
public String getOldRace() {
return oldRace;
}
public void setOldRace(String oldRace) {
this.oldRace = oldRace;
}
public SelectItem[] getRaces() {
return races;
}
public void setRaces(SelectItem[] races) {
this.races = races;
}
public String getSelectedRace() {
return selectedRace;
}
public void setSelectedRace(String selectedRace) {
this.selectedRace = selectedRace;
}
public void selectRace(ValueChangeEvent e) {
selectedRace = e.getNewValue().toString();
oldRace = e.getOldValue().toString();
}
}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java. prefix="f" %>
<%@taglib uri="http://java. prefix="h" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Value Change Listener Test</title>
</head>
<body>
<f:view>
<h:form>
Select a race:
<h:selectOneMenu immediate="true"
value="#{vclt.selectedRace}" valueChangeListener="#{vclt.selectRace}" onchange="submit();">
(value不能缺,同时要设置成新值才能正常显示旧值)
<f:selectItems value="#{vclt.races}"/>
</h:selectOneMenu><br/>
This is the race you selected:
<h:outputText value="#{vclt.selectedRace}"></h:outputText><br/>
This is your last race:
<h:outputText value="#{vclt.oldRace}"></h:outputText>
</h:form>
</f:view>
</body>
</html>
再谢次!