0

I'm working on a Java EE project using frameworks JSF 2.1, Spring 3.1.1.Release, hibernate 3.2.1. now i'm in the phase of integrating the three of them. the build succeeded, i use tomcat server 7. but i get this exception on the the front page.

Etat HTTP 500 -

type Rapport d''exception

message

description Le serveur a rencontré une erreur interne qui l''a empêché de satisfaire la requête.

exception

javax.servlet.ServletException
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:422)
cause mère

java.lang.NullPointerException
    controller.AnneeBean.getListeAnnees(AnneeBean.java:15)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:601)
    javax.el.BeanELResolver.getValue(BeanELResolver.java:87)
    com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    org.apache.el.parser.AstValue.getValue(AstValue.java:183)
    org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
    com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    javax.faces.component.UIData.getValue(UIData.java:731)
    javax.faces.component.UIData.getDataModel(UIData.java:1798)
    javax.faces.component.UIData.setRowIndexWithoutRowStatePreserved(UIData.java:484)
    javax.faces.component.UIData.setRowIndex(UIData.java:473)
    com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:81)
    javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:820)
    javax.faces.component.UIData.encodeBegin(UIData.java:1118)
    javax.faces.component.UIComponent.encodeAll(UIComponent.java:1754)
    javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
    javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
    com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
    com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
    com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:410)
note La trace complète de la cause mère de cette erreur est disponible dans les fichiers journaux de Apache Tomcat/7.0.42.

Hibernate hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/base?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">root</property>
    <mapping resource="net/vo/Annee.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

hibernate.reveng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-catalog="base"/>
  <table-filter match-name="annee"/>
</hibernate-reverse-engineering>

AnneeDao.java

package dao;

import java.util.List;
import net.vo.Annee;

public interface AnneeDao {
    public List getAllAnnees();
    public Annee getAnnee(Integer id);
    public void insert(Annee annee);
    public void update(Annee annee);
    public void delete(Integer id);
}

AnneeHibernateDao.java

package dao;

import java.util.List;
import net.vo.Annee;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class AnneeHibernateDao implements AnneeDao{
    private List<Annee> listeAnnees;
    private Annee annee;
    public void init()
    {
        System.out.println("Méthode d'initiation");
    }
    @Override
    public List getAllAnnees() {
        Session session=HibernateUtil.getSession();
        try
        {
            session.beginTransaction();
            listeAnnees = session.createQuery("from Annee").list();
            return listeAnnees;
        }
        catch(HibernateException e)
        {
            throw e;
        }
        finally
        {
            session.close();
        }
    }

    @Override
    public Annee getAnnee(Integer id) {
       Session session = HibernateUtil.getSession();
       try
       {
           session.beginTransaction();
           Query q = session.createQuery("from Annee as a where a.annee=" + id);
           return (Annee) q.uniqueResult();
       }
       finally
       {
           session.close();
       }
    }

    @Override
    public void insert(Annee annee) {

      Session session = HibernateUtil.getSession();
      Transaction tx=null;
      try
      {
          tx = session.beginTransaction();
          session.save(annee);
          tx.commit();         
      }
      catch(RuntimeException e)
      {
          if(tx != null) 
            {
                tx.rollback();
            }
          throw e;
      }
      finally
      {
          session.close();
      }
    }

    @Override
    public void update(Annee annee) {
        Session session = HibernateUtil.getSession();
        Transaction tx=null;
        try
        {
            tx=session.beginTransaction();
            session.update(annee);
            tx.commit();
        }
         catch(RuntimeException e)
         {
           if(tx != null) 
            {
                tx.rollback();
            }
            throw e;
         }
         finally
         {
            session.close();
         }
    }

    @Override
    public void delete(Integer id) {
       Session session = HibernateUtil.getSession();
       Transaction tx = null;
       try
       {
           tx=session.beginTransaction();
           annee = (Annee) session.get(Annee.class,id);
           session.delete(annee);
           tx.commit();
       }
       catch(RuntimeException e)
         {
            if(tx != null) 
            {
                tx.rollback();
            }
            throw e;
         }
         finally
         {
            session.close();
         }
    }


}

HibernateUtil.java

package dao;

import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author images
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() {
        return sessionFactory.openSession();
    }
}

Pojo file

Annee.java

package net.vo;

public class Annee  implements java.io.Serializable {


     private int annee;

    public Annee() {
    }

    public Annee(int annee) {
       this.annee = annee;
    }

    public int getAnnee() {
        return this.annee;
    }

    public void setAnnee(int annee) {
        this.annee = annee;
    }




}

Mapping file : Annee.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 13 mai 2014 18:23:22 by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
    <class name="net.vo.Annee" table="annee" catalog="base">
        <id name="annee" type="int">
            <column name="annee" />
            <generator class="assigned" />
        </id>
    </class>
</hibernate-mapping>

Spring AnneeMetier.java

package model.services;

import java.util.List;

public interface AnneeMetier {
    public List getAllAnnees();
}

AnneeMetierImpl.java

package model.services;

import dao.AnneeDao;
import java.util.List;
import net.vo.Annee;

public class AnneeMetierImpl implements AnneeMetier{

    private AnneeDao anneeDao;

    @Override
    public List getAllAnnees() {
            return anneeDao.getAllAnnees();
    }

    public void setAnneeDao(AnneeDao anneeDao) {
        this.anneeDao = anneeDao;
    }

    public AnneeDao getAnneeDao() {
        return anneeDao;
    }

}

JSF AnneeBean.java

package controller;

import java.util.List;
import model.services.AnneeMetier;
import net.vo.Annee;

public class AnneeBean {

    private AnneeMetier anneeMetier;

    private List<Annee> listeAnnees;

    public List getListeAnnees() {
        listeAnnees = anneeMetier.getAllAnnees();
        return listeAnnees;
    }

    public void setListeAnnees(List listeAnnees) {
        this.listeAnnees = listeAnnees;
    }

    public AnneeMetier getAnneeMetier() {
        return anneeMetier;
    }

    public void setAnneeMetier(AnneeMetier anneeMetier) {
        this.anneeMetier = anneeMetier;
    }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
       <listener>
      <listener-class>
         org.springframework.web.context.ContextLoaderListener
      </listener-class>
   </listener>
   <listener>
      <listener-class>
         org.springframework.web.context.request.RequestContextListener
      </listener-class>
   </listener>
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"
       xmlns:context="http://www.springframework.org/schema/context/spring-context-3.1.xsd"
       xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
          http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/aop/spring-aop-3.1.xsd/spring-spring-aop-3.1.xsd-3.1.1.RELEASE.xsd
          http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/context/spring-context-3.1.xsd/spring-spring-context-2.5.xsd-3.1.1.RELEASE.xsd
          http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/tx/spring-tx-3.1.xsd/spring-spring-tx-3.1.xsd-3.1.1.RELEASE.xsd
">
     <bean id="anneeDao" class="dao.AnneeHibernateDao"></bean>
    <bean id="anneeMetier" class="model.services.AnneeMetierImpl">
        <property name="anneeDao" ref="anneeDao"/>  
    </bean>  

</beans>

faces-config.xml

<?xml version='1.0' encoding='UTF-8'?>

<!-- =========== FULL CONFIGURATION FILE ================================== -->

<faces-config version="2.1"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd">

<application>
   <variable-resolver>
      org.springframework.web.jsf.DelegatingVariableResolver
   </variable-resolver>
</application>
 <managed-bean>
      <managed-bean-name>anneeBean</managed-bean-name>
      <managed-bean-class>controller.AnneeBean</managed-bean-class>
      <managed-bean-scope>request</managed-bean-scope>
   </managed-bean> 
</faces-config>

index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.org/ui">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <h:dataTable var="annees" value="#{anneeBean.listeAnnees}">
                    <p:column headerText="Annee">
                        <h:outputText value="#{annee.annees}"/>
                    </p:column>
                </h:dataTable>
    </h:body>
</html>

please could you help me, i will appreciate it a lot

edit : this is the stacktrace updated

mai 14, 2014 1:14:41 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/testJSF_Spring_Hibernate] threw exception [Erreur lors de linjection de ressources dans le bean géré anneeBean] with root cause
java.lang.NullPointerException
    at model.services.AnneeMetierImpl.getAllAnnees(AnneeMetierImpl.java:17)
    at controller.AnneeBean.init(AnneeBean.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.faces.vendor.WebContainerInjectionProvider.invokeAnnotatedMethod(WebContainerInjectionProvider.java:117)
    at com.sun.faces.vendor.WebContainerInjectionProvider.invokePostConstruct(WebContainerInjectionProvider.java:99)
    at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:223)
    at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:105)
    at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
    at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
    at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
    at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at com.sun.faces.el.ChainAwareVariableResolver.resolveVariable(ChainAwareVariableResolver.java:107)
    at org.springframework.web.jsf.DelegatingVariableResolver.resolveOriginal(DelegatingVariableResolver.java:123)
    at org.springframework.web.jsf.DelegatingVariableResolver.resolveVariable(DelegatingVariableResolver.java:108)
    at com.sun.faces.el.VariableResolverChainWrapper.getValue(VariableResolverChainWrapper.java:115)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:72)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:161)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIData.getValue(UIData.java:731)
    at javax.faces.component.UIData.getDataModel(UIData.java:1798)
    at javax.faces.component.UIData.setRowIndexWithoutRowStatePreserved(UIData.java:484)
    at javax.faces.component.UIData.setRowIndex(UIData.java:473)
    at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:81)
    at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:820)
    at javax.faces.component.UIData.encodeBegin(UIData.java:1118)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1754)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:410)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

edit 2 : this is the AnneeBean Class

package controller;

import java.util.List;
import javax.annotation.PostConstruct;
import model.services.AnneeMetier;
import model.services.AnneeMetierImpl;
import net.vo.Annee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("view")
public class AnneeBean {

    @Autowired
    private AnneeMetier anneeMetier;

    private List<Annee> listeAnnees;

    @PostConstruct
    public void init() {
        anneeMetier = new AnneeMetierImpl();
        listeAnnees = anneeMetier.getAllAnnees();
    }
    public List getListeAnnees() {
        listeAnnees = anneeMetier.getAllAnnees();
        return listeAnnees;
    }

    public void setListeAnnees(List listeAnnees) {
        this.listeAnnees = listeAnnees;
    }

    public AnneeMetier getAnneeMetier() {
        return anneeMetier;
    }

    public void setAnneeMetier(AnneeMetier anneeMetier) {
        this.anneeMetier = anneeMetier;
    }

}

edit 3 : index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.org/ui"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
 <h:form>
     <p:dataTable var="listeAnnees" value="#{anneeBean.listeAnnees}">
                <p:column headerText="Annee">
                    <h:outputText value="#{listeAnnees.annee}"/>
                    </p:column>
            </p:dataTable>        
        </h:form>
    </h:body>
</html>
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Marina
  • 71
  • 2
  • 15
  • in index.xhtml, i call the method getListAnnee which is in the bean AnneeBean.java public List getListeAnnees() { listeAnnees = anneeMetier.getAllAnnees(); //here i call the spring method return listeAnnees; } – Marina May 13 '14 at 18:25
  • its seems like "anneeMetier" is null in AnneeBean.getListeAnnees. You should set a empty list to it on initalisation or make a null check. – pL4Gu33 May 13 '14 at 18:26

2 Answers2

3

The naive solution for non-JSF developers would be to simply initialize the variables inside the getter to resolve the null value in the attributes. This is:

public List getListeAnnees() {
    listeAnnees = getAnneeMetier().getAllAnnees();
    return listeAnnees;
}

public AnneeMetier getAnneeMetier() {
    if (anneeMetier == null) {
        anneeMetier = new AnneeMetierImpl();
    }
    return anneeMetier;
}

But this may generate lot of overhead from server in case AnneeMetier#getAllAnnees() retrieves the data from database. This is explained here: Why JSF calls getters multiple times

To solve this, you do two things:

  1. Define the right scope of your bean.
  2. Initialize the necessary data for work using @PostConstruct annotated method.

And this would result in:

  1. Defining the scope as @ViewScoped (explained in the link above).
  2. Initializing listeAnnees in @PostConstruct method.
  3. Remove any business logic from getters/setters

So the code would look like this:

@ManagedBean
@ViewScoped
public class AnneeBean {
    private AnneeMetier anneeMetier;
    private List<Annee> listeAnnees;

    @PostConstruct
    public void init() {
        anneeMetier = new AnneeMetierImpl();
        listeAnnees = anneeMetier.getAllAnnees();
    }

    public List getListeAnnees() {
        return listeAnnees;
    }

    public void setListeAnnees(List listeAnnees) {
        this.listeAnnees = listeAnnees;
    }

    public AnneeMetier getAnneeMetier() {
        return anneeMetier;
    }

    public void setAnneeMetier(AnneeMetier anneeMetier) {
        this.anneeMetier = anneeMetier;
    }
}

BUT since you're trying to integrate JSF with Spring, you have to take into account that Spring has not yet full support of JSF 2 @ViewScoped annotation. For this case, you have/need to implement it yourself. There are plenty examples on the net about this, and looks that the most popular is from Cagatay's. In this way, you'll be able to gain power from both sides. And your bean will look like this:

@Component
@Scope("view")
public class AnneeBean {
    @Autowired
    private AnneeMetier anneeMetier;
    private List<Annee> listeAnnees;

    @PostConstruct
    public void init() {
        listeAnnees = anneeMetier.getAllAnnees();
    }

    public List getListeAnnees() {
        return listeAnnees;
    }

    public void setListeAnnees(List listeAnnees) {
        this.listeAnnees = listeAnnees;
    }
}

More info:


Since you're learning Spring, the best bet would be to enable component scan and use annotations to configure your spring beans. Do the following:

  • Remove any bean configuration in applicationContext.xml.
  • Add this configuration to enable bean scan annotations:

    <!-- 
        These will enable component scan by annotation configuration
        rather than XML configuration. One per package
    -->
    <context:component-scan base-package="dao" />
    <context:component-scan base-package="model.services" />
    

    Or if all your classes are inside one root package.

    <!--
        Assuming there's a root package for your packages like this
    <context:component-scan base-package="com.myproject.dao" />
    <context:component-scan base-package="com.myproject.model.services" />
    -->
    <context:component-scan base-package="com.myproject" />
    
  • Start configuring your Spring managed beans by annotations:

    @Repository
    public class AnneeHibernateDao implements AnneeDao{
        //...
    }
    
    @Service
    public class AnneeMetierImpl implements AnneeMetier{
        @Autowired
        private AnneeDao anneeDao;
        //...
    }
    

Compile your project and run it.

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • i added the stacktrace, you can see it now – Marina May 13 '14 at 23:12
  • @Marina it is strange that you don't have `context` enabled in your spring applicationContext.xml. Which version of Spring are you using? – Luiggi Mendoza May 13 '14 at 23:14
  • i'm using spring 3.1.1.RELEASE – Marina May 13 '14 at 23:16
  • Please check how to enable component scan in your project. If that doesn't work, configure each spring bean manually in your project again: AnneeHibertnateDao and AnneeMetierImpl. – Luiggi Mendoza May 13 '14 at 23:20
  • i added and i changed the root element of applicationContext now the build is succesfull but i got i think the same error as before. i will show u the log – Marina May 13 '14 at 23:41
  • Did you add the autowired annotation as well? – Luiggi Mendoza May 14 '14 at 00:01
  • yes, i added authowird annotation in AnneeMetierImpl and AnneeBean – Marina May 14 '14 at 00:08
  • Could you please update the question and add the current stacktrace? – Luiggi Mendoza May 14 '14 at 00:10
  • i've updated the question as requested @Luiggi Mendoza – Marina May 14 '14 at 00:41
  • @Marina the only think I can come up with is that you're creating `AnneeMetier` manually inside `AnneeBean` class. Can you check this please? – Luiggi Mendoza May 14 '14 at 04:01
  • i edited the question, i added the class AnneeBean.java @Luiggi Mendoza – Marina May 14 '14 at 13:22
  • @Marina the problem is that you're manually creating `anneeMetier` inside `@PostConstruct public void init()` method. I updated my last code to not do that. Just remove that line and everything will work as expected since `anneeMetier` will be injected by Spring. – Luiggi Mendoza May 14 '14 at 14:31
  • i removed that line, but the same error remains, i have an exception java.lang.NullPointerException on the line : listeAnnees = anneeMetier.getAllAnnees(); in init method @Luiggi Mendoza – Marina May 14 '14 at 14:59
  • @Marina silly me. I forgot to tell you to add the component scan for controller package. Add it like you did for dao package in applicationContext.xml and it should work. – Luiggi Mendoza May 14 '14 at 15:08
  • i added it, but the error is still the same. @Luiggi Mendoza – Marina May 14 '14 at 15:26
  • @Marina this is completely weird. I can only imagine that the instance of `AnneeBean` class is managed by JSF and not by Spring. If so, then you should remove the bean declaration from faces-config.xml file as well. – Luiggi Mendoza May 14 '14 at 15:49
  • in faces-config.xml, i have managed bean declaration, and i removed it anneeBean controller.AnneeBean request i get this exception : javax.servlet.ServletException: No Scope registered for scope 'view' javax.faces.webapp.FacesServlet.service(FacesServlet.java:422) @Luiggi Mendoza – Marina May 14 '14 at 15:54
  • @Marina ok, now looks like you haven't read my answer at all. Read this part: *BUT since you're trying to integrate JSF with Spring, you have to take into account that Spring has not yet full support of JSF 2 `@ViewScoped` annotation. For this case, you have/need to implement it yourself. There are plenty examples on the net about this, and looks that the most popular is from Cagatay's*. – Luiggi Mendoza May 14 '14 at 16:58
  • thank you for your help, i don't get the errors anymore but the page on the navigator is blank. I don't get the data in the database @Luiggi Mendoza – Marina May 14 '14 at 23:10
  • @Marina could you try going through the elements of the list inside `init` method and print them, just to make sure there is data in the list and the problem is somewhere else? – Luiggi Mendoza May 14 '14 at 23:18
  • i tried this in init method int i=0; List annees = anneeMetier.getAllAnnees(); Annee annee = (Annee)annees.get(i); System.out.println(annee.getAnnee() + "init"); and i get the data which is in the database @Luiggi Mendoza – Marina May 14 '14 at 23:28
  • i don't get the data in the datable, i think there is something wrong in the index.xhtml file @Luiggi Mendoza – Marina May 15 '14 at 00:17
  • The bean is generated in the right way, the injections work and the data is retrieved, but looks like JSF is unable to retrieve the bean from Spring context. Try changing the EL resolver in faces-config.xml to ` org.springframework.web.jsf.el.SpringBeanFacesELResolver`. – Luiggi Mendoza May 15 '14 at 00:25
  • @Marina also, follow the configuration explained here: http://www.mkyong.com/jsf2/jsf-2-0-spring-integration-example/ – Luiggi Mendoza May 15 '14 at 00:27
  • thank ypu so much for your help, i found the problem it was that the method getAllAnnees() in AnneeBean was returning List and it should return List, i also made some changes in index.xhtml as i will edit on the question if somone gets the same problem as me @Luiggi Mendoza – Marina May 15 '14 at 16:23
2

You are using getListeAnnees where you intend to call a method of your private object called anneeMetier, which is not initialized yet. You initialize that object through your setAnneeMetier method, which is never initialized in your code, therefore it is null. You can solve your problem by doing one of the following:

  1. You initialize anneeMetier by calling the setAnneeMetier before you use getListeAnnees

  2. You implement a constructor for your AnneeBean class where you initialize anneeMetier

  3. You modify your getter (getListeAnnees) to be such as follows:

    public List getListeAnnees() { if (anneeMetier == null) { return new ArrayList<Annee>(); } listeAnnees = anneeMetier.getAllAnnees(); return listeAnnees; }

EDIT: pL4GU33's comment might be useful, so I add his comment's idea to the answer:

public List getListeAnnees() { if (anneeMetier == null) { return Collections.emptyList(); } listeAnnees = anneeMetier.getAllAnnees(); return listeAnnees; }

His solution is more type-agnostic, so I upvote his comment.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • 1
    For 3 i would prefer return Collections.emptyList(). http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#emptyList%28%29 instead of new ArrayList() – pL4Gu33 May 13 '14 at 18:59
  • If you had worked with JSF 2 previously, you would know this is not the right solution. – Luiggi Mendoza May 13 '14 at 19:13
  • @LuiggiMendoza, can you elaborate your comment? What is wrong with the suggestions? – Lajos Arpad May 13 '14 at 19:14
  • Read here: [Why JSF calls getters multiple times](http://stackoverflow.com/q/2090033/1065197). Since the bean is request scoped, doing this means retrieving the object from database on every request (which IMO is not desired). – Luiggi Mendoza May 13 '14 at 19:15
  • That is true and it is undesirable indeed, however, the question was about having a NullPointerException, not about minimizing the number of requests. So your point is valid, but I am not sure we are helping the op if we optimize his/her approach before we fix the NullPointerException. Also, getting the resources from the database on every request might be useful in the case when inserts, updates and deletes are frequent. – Lajos Arpad May 13 '14 at 19:20
  • Not if the data changes and JSF cannot validate the component tree. My recommendation: do not try to answer JSF related questions if you haven't worked with it. – Luiggi Mendoza May 13 '14 at 19:23