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
nullpointerexceptionbecauseuserdatanot found in session scope.the reason happening put
userdatain application scope (@applicationscopedannotation on managed bean) , searching in session scope.eventhough verified
userdatanull still printslocale setbecause bean in application scope described in2.above.so solution? either change
@applicationscoped@sessionscopedor accessuserdatachanging: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