java - NullPointer Exception - JSF Event Handling ( ValueChangeListener ) -
i learning jsf event handling , when try run sample code, getting null pointer exception.
this index.xhtml snippet,
<h:form> <h2>implement valuechangelistener</h2> <hr /> <h:panelgrid columns="2"> selected locale: <h:selectonemenu value="#{userdata.selectedcountry}" onchange="submit()"> <f:valuechangelistener type="com.cyb3rh4wk.test.localechangelistener" /> <f:selectitems value="#{userdata.countries}" /> </h:selectonemenu> country name: <h:outputtext id="countryinterface" value="#{userdata.selectedcountry}" /> </h:panelgrid> </h:form>
userdata.java
@managedbean(name = "userdata", eager = true) @applicationscoped public class userdata implements serializable{ private static map<string, string> countrymap; private string selectedcountry = "united kingdom"; static { countrymap = new linkedhashmap<string, string>(); countrymap.put("en", "united kingdon"); countrymap.put("fr", "french"); countrymap.put("de", "german"); countrymap.put("def", "default"); } public string getselectedcountry() { return selectedcountry; } public void setselectedcountry(string selectedcountry) { this.selectedcountry = selectedcountry; system.out.println("locale set"); } public map<string, string> getcountries() { return countrymap; } public void localechanged(valuechangeevent event) { selectedcountry = event.getnewvalue().tostring(); } }
localechangelistener.java
public class localechangelistener implements valuechangelistener { @override public void processvaluechange(valuechangeevent event) throws abortprocessingexception { userdata userdata = (userdata) facescontext.getcurrentinstance().getexternalcontext().getsessionmap().get("userdata"); string newlocale = event.getnewvalue().tostring(); if (newlocale != null) userdata.setselectedcountry(newlocale); else userdata.setselectedcountry("default"); } }
when run these on glassfish server, error,
java.lang.nullpointerexception @ com.cyb3rh4wk.test.localechangelistener.processvaluechange(localechangelistener.java:25) @ com.sun.faces.facelets.tag.jsf.core.valuechangelistenerhandler$lazyvaluechangelistener.processvaluechange(valuechangelistenerhandler.java:128) @ javax.faces.event.valuechangeevent.processlistener(valuechangeevent.java:134)
can me ?
you getting
nullpointerexception
becauseuserdata
not found in session scope.the reason happening put
userdata
in application scope (@applicationscoped
annotation on managed bean) , searching in session scope.eventhough verified
userdata
null still printslocale set
because bean in application scope described in2.
above.so solution? either change
@applicationscoped
@sessionscoped
or accessuserdata
changing:userdata userdata = (userdata) facescontext.getcurrentinstance().getexternalcontext().getsessionmap().get("userdata");
to
facescontext ctx = facescontext.getcurrentinstance(); userdata userdata = (userdata)ctx.getexternalcontext().getapplicationmap().get("userdata");
Comments
Post a Comment