I try to achieve resource injection for a long time but couldn't succeeded.
I use JSF 2.2, JDK 1.7. And my ide is eclipse luna.
I have a session scoped bean called UserBean and view scoped bean called SettingsBean.
I set them in faces-config.xml UserBean as session scoped and SettingsBean as view scoped with their bean name "settingsBean" and "userBean"
public class SettingsBean implements Serializable {
private static final long serialVersionUID = 1L;
#Inject // I also tried #ManagedProperty but didn't work
private UserBean userBean;
#PostConstruct
public void init(){
System.out.println(userBean.getUser().getFullName());
}
public UserBean getUserBean() {
return userBean;
}
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
}
The problem is I get userBean as null. What is the problem here?
Thanks for help.
I removed ManagedBean and ViewScoped definitions in faces-config.xml for settingsBean and added them in SettingsBean.java file manually.
And added this also:
#ManagedProperty(value="#{userBean}")
private UserBean userBean;
So finally, it works:
#ManagedBean
#ViewScoped
public class SettingsBean implements Serializable{
private static final long serialVersionUID = 1L;
#ManagedProperty(value="#{userBean}")
private UserBean userBean;
//...
#PostConstruct
public void init(){
System.out.println(userBean.getUser().getFullName());
}
public UserBean getUserBean() {
return userBean;
}
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
}
Related
I have this SessionScoped bean:
#ManagedBean
#SessionScoped
public class LoginBean implements Serializable {
/**
* Creates a new instance of LoginBean
*/
public LoginBean() {
this.usuario = new Usuario();
}
private Usuario usuario;
//getter & setter
}
The Usuario class:
public class Usuario {
public Usuario() {
}
private String password;
private String nombre;
private int idPlanta;
private int nivel;
private String idUsuario;
//getters & setters
}
And I want to get the value of the property idPlanta from the SessionScoped bean (LoginBean) here (in the constructor) see the comments:
#ManagedBean
#ViewScoped
public class PrincipalBean implements Serializable {
public PrincipalBean() {
System.out.println(this.login.getUsuario().getIdPlanta());
//AT THIS POINT THE VALUE OF idPlanta IS 0 but in the session I have 1...
//Method that uses the idPlanta value as a parameter
}
#ManagedProperty(value = "#{loginBean}")
private LoginBean login;
public LoginBean getLogin() {
return login;
}
public void setLogin(LoginBean login) {
this.login = login;
}
}
But when I show the value in the view it shows the value that really is in the Session idPlanta = 1. I dont understand why I cant get the value of that property in the constructor of that ViewScoped bean (PrincipalBean). I show the value in the view here(I know I can get it directly fron the LoginBean but this is just to show that the property login in PrincipalBean has the Session value):
<h:outputText class="titulo" value="Bienvenido(a) #{principalBean.login.usuario.nombre} Planta #{principalBean.login.usuario.idPlanta}" />
The value of idPlanta in PrincipalBean is very important because I use it as a method parameter to show more info when the view is showed.
Please help me. I still learning JSF.
You need to be using these values after the bean has been constructed. When your constructor is called, your bean has net yet been initialzed - therefore the injections have not yet happend. Using the #PostConstruct method you will be able to access the desired values from the injected objects.
For example :
#ManagedBean
#ViewScoped
public class PrincipalBean implements Serializable {
public PrincipalBean() {
}
#PostConstruct
public init() {
System.out.println(this.login.getUsuario().getIdPlanta());
//AT THIS POINT THE VALUE OF idPlanta IS 0 but in the session I have 1...
//Method that uses the idPlanta value as a parameter
}
#ManagedProperty(value = "#{loginBean}")
private LoginBean login;
public LoginBean getLogin() {
return login;
}
public void setLogin(LoginBean login) {
this.login = login;
}
}
See Also
Why use #PostConstruct?
Injecting Managed Beans In JSF 2.0
JSF injection with managed property, good pattern?
I have a ManagedBean of a treeNode and other managed bean where i would like to get the selectedNode and from getType i would like to execute some code but the problem i can't get the selectedNode cause every time i get this:
java.lang.NullPointerException: javax.faces.FacesException: #{dimMan.makeDim()}: java.lang.NullPointerException
and this is my two Managed bean:
#ManagedBean
#ViewScoped
public class TreeBean implements Serializable {
private static final long serialVersionUID = 2417620239014385855L;
private TreeNode root;
private TreeNode selectedNode;
.....
and the other one where i would like to make a test of the type of selected node:
#ManagedBean(name = "dimMan")
#SessionScoped
public class DimenssionManaged {
#EJB
DimensionDaoRemote dimService;
#Inject
TreeBean treeSelected;
String select;
public TreeBean getTreeSelected() {
return treeSelected;
}
public void setTreeSelected(TreeBean treeSelected) {
this.treeSelected = treeSelected;
}
public void makeDim(){
System.out.println("adding dimen");
fkey=tTable.getSelectedFk();
dimUpdate.setFk_dimension(fkey);
dimUpdate.setType_dimension(selectedType);
select=treeSelected.getSelectedNode().getParent().getType();
System.out.println(select);
if (select=="cube"){
CubeBase cub=cubManged.getCubUpdate();
dimUpdate.setCube(cub);
dimService.creat_dimension(dimUpdate);
}
else {
SchemaBase sh=shmanged.getSchema();
dimUpdate.setSchema(sh);
dimService.creat_dimension(dimUpdate);
}
}
i try also to use this annotation #ManagedProperty(value =***) but it didn't work to so what should i do to get the selectedNode type from in other ManagedBean ?
DimenssionManaged ManagedBean associated with other page? If so once you navigate TreeBean will loose its data since its in #ViewScoped.
Change TreeBean to #SessionScoped to retain the the data even after navigation, but clearing/refreshing the data again is a concern.
I have written an EJB and a dynamic web project Eclipse on GlassFish server. I used DAO , Facade and JPA. Normally I am calling a method from my service it is giving these errors ;
kitapOduncVerme.xhtml]com.sun.faces.mgbean.ManagedBeanCreationException
PWC1406: Servlet.service() for servlet Faces Servlet threw exceptionjava.lang.NullPointerException
at com.mesutemre.kitapislemleri.KitapOduncVermeBean.initList(KitapOduncVermeBean.java:47)
at com.mesutemre.kitapislemleri.KitapOduncVermeBean.initialize(KitapOduncVermeBean.java:43)
My codes are below;
#ManagedBean(name = "oduncKitapVerBean")
#ViewScoped
public class KitapOduncVermeBean implements Serializable{
private static final long serialVersionUID = 1L;
private List<Kitaplar> entityList = new ArrayList<Kitaplar>();
private Kitaplar selectedEntity;
private Kitaplar entity;
private String kullaniciadi;
private KitaplarFacade service;
public KitapOduncVermeBean() {
entity = new Kitaplar();
selectedEntity = new Kitaplar();
}
#PostConstruct
public void initialize(){
HttpSession session = Util.getSession();
kullaniciadi = Util.getUserName();
initList();
}
private void initList(){
entityList = service.findAllKitaplar();
}
DaoImpl
#SuppressWarnings("unchecked")
public List<Kitaplar> findAllKitaplar(){
return em.createNamedQuery("tumkitaplarigetir").getResultList();
}
Dao
#Stateless
#LocalBean
public class KitaplarDAO extends KitaplarDaoImpl<Kitaplar> implements Serializable{
private static final long serialVersionUID = 1L;
#Override
public List<Kitaplar> findAllKitaplar() {
return super.findAllKitaplar();
}
FacadeImpl
#Stateless
#LocalBean
public class KitaplarFacadeImpl implements KitaplarFacade,Serializable {
private static final long serialVersionUID = 1L;
#EJB
KitaplarDAO kitapDao;
#Override
public List<Kitaplar> findAllKitaplar() {
return kitapDao.findAllKitaplar();
}
}
Facade
#Local
public interface KitaplarFacade {
public abstract List<Kitaplar> findAllKitaplar();
}
I can't see any problem in this codes? But Why am I getting that errors?
ManagedBeanCrearionException is simply wrapping and rethrowing the NullPointerException, that is very easy to debug: you have a null variable at the exact line that appears in the stack trace.
In KitapOduncVermeBean class, you are declaring service property, but you are not initializing it, therefore it's null when invoked in initList() method. Since it's an EJB, annotate it as such and the EJB container will instantiate it automatically:
#EJB
private KitaplarFacade service;
Unrelated to the concrete problem, your code is too complicated: with EJB 3.x, in most web applications, you don't need EJBs to implement or expose interfaces.
I tried to inject a Managed Bean to another bean, but failed. That is the first bean:
#ManagedBean(name = "sucBean")
#SessionScoped
public class SucBean implements Serializable {
private static final long serialVersionUID = 1L;
private MapModel advancedModel;
private MapModel advancedModel2;
private Marker marker;
private Suc suc;
private List<Suc> sucDefteri;
private List<Suc> searchResult;
private Suc[] selectedSuc;
private SucService sucService;
private String aramaKriteri;
private String arananKelime;
private SucDataModel sucModel;
// other getters/setters methods
When I run the web application, I'm getting the
Caused by: java.lang.NullPointerException
at org.primefaces.component.chart.CartesianChart.getCategories(CartesianChart.java:32)
at org.primefaces.component.chart.bar.BarChartRenderer.encodeData(BarChartRenderer.java:121)
at org.primefaces.component.chart.bar.BarChartRenderer.encodeScript(BarChartRenderer.java:51)
at org.primefaces.component.chart.bar.BarChartRenderer.encodeEnd(BarChartRenderer.java:36)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1786)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
The second bean is following:
#ManagedBean(name="chartBean")
#SessionScoped
public class ChartBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private CartesianChartModel categoryModel;
#ManagedProperty("#{sucBean}")
private SucBean sucBean;
private int[] sucSayilari=new int[9];
public ChartBean()
{
createCategoryModel();
}
I think this is the problem:
public ChartBean()
{
createCategoryModel();
}
Your dependencies are not set at this point because the JSF implementation first instantiates your bean (and that means that the constructor must finish) and then injects its dependencies, so if you are using the injected bean in createCategoryModel() it will be a null reference.
If you need to do something with your bean AFTER dependencies are set use a method anotated with #PostConstruct:
public ChartBean(){
}
#PostConstruct
public void init(){
createCategoryModel();
}
(Java EE 6 with Glassfish 3.1)
I have a property file that I want to process only once at start up time, so I did this
public class Config implements ServletContextListener{
private static final String CONFIG_FILE_PATH = "C:\\dev\\harry\\core.cfg";
private static final String CONFIG_ATTRIBUTE_NAME = "config";
private long startupTime;
private ConfigRecord config;
#Override
public void contextInitialized(ServletContextEvent sce) {
this.startupTime = System.currentTimeMillis() / 1000;
this.config = new ConfigRecord(CONFIG_FILE_PATH); //Parse the property file
sce.getServletContext().setAttribute(CONFIG_ATTRIBUTE_NAME, this);
}
#Override
public void contextDestroyed(ServletContextEvent sce) {
//Nothing to do here
}
public ConfigRecord getConfig() {
return config;
}
public long getStartupTime() {
return startupTime;
}
}
and in web.xml, i register it as follow
<listener>
<listener-class>com.wf.docsys.core.servlet.Config</listener-class>
</listener>
Now how do I access the ConfigRecord config from the managed bean. I try this
#ManagedBean
#RequestScoped
public class DisplayInbound {
#EJB
private CoreMainEJBLocal coreMainEJBLocal;
#javax.ws.rs.core.Context
private ServletContext servletContext;
public void test(){
Config config = (Config) servletContext.getAttribute("config")
ConfigRecord configRecord = config.getConfig();
}
}
I dont think it work. Got NullPointerException.
That #Context annotation is only applicable in a JAX-RS controller, not in a JSF managed bean. You have to use #ManagedProperty instead. The ServletContext is available by ExternalContext#getContext(). The FacesContext itself is available by #{facesContext}.
#ManagedProperty(value="#{facesContext.externalContext.context}")
private ServletContext context;
Or because you stored the listener as a servletcontext attribute, which is basically the same as the JSF application scope, you could also just set it as managed property by its attribute name:
#ManagedProperty(value="#{config}")
private Config config;
But since you're on JSF 2.0, I'd suggest to use an #ApplicationScoped #ManagedBean instead which is eagerly constructed. With #PostConstruct and #PreDestroy in such a bean you have similar hooks on webapp's startup and shutdown as in a ServletContextListener.
#ManagedBean(eager=true)
#ApplicationScoped
public void Config {
#PostConstruct
public void applicationInitialized() {
// ...
}
#PreDestroy
public void applicationDestroyed() {
// ...
}
}
You can inject it in another beans the usual #ManagedProperty way and access it in the views the usual EL way.