标题:JSF的ValueChangeListener出现空指针异常
取消只看楼主
hwoarangzk
Rank: 4
来 自:冰封王座
等 级:贵宾
威 望:12
帖 子:1894
专家分:0
注 册:2007-7-17
得分:0 
十分感谢!问题已解决!原来在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>
再谢次!

I'm here, as always...
2008-01-31 11:06



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-199029-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.178177 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved