The naive solution for non-JSF developers would be to simply initialize thevariables 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 caseAnneeMetier#getAllAnnees() retrieves the data from database. This isexplained here: Why JSF calls getters multipletimes
To solve this, you do two things:
Define the right scope of your bean.Initialize the necessary data for work using @postconstruct annotated method.And this would result in:
Defining the scope as @ViewScoped (explained in the link above).Initializing listeAnnees in @postconstruct method.Remove any business logic from getters/settersSo the code would look like this:
@ManagedBean@ViewScopedpublic 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; }}
since you’re trying to integrate JSF with Spring, you have to takeinto account that Spring has not yet full support of JSF 2 @ViewScopedannotation. For this case, youhave/need to implement it yourself. There are plenty examples on the net aboutthis, and looks that the most popular is fromCagatay’s. In this way, you’ll be able to gain powerfrom 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; }}
Since you’re learning Spring, the best bet would be to enable component scanand 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 configurationrather 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{@Autowiredprivate AnneeDao anneeDao;//... }
Compile your project and run it.
解决方法我正在使用框架JSF 2.1,Spring 3.1.1.Release,Hibernate 3.2.1进行JavaEE项目。现在我正处于整合这三个方面的阶段。构建成功,我使用了tomcat服务器7。但是我在首页上看到了这个异常。
Etat HTTP 500 -type Rapport d’’exceptionmessagedescription Le serveur a rencontré une erreur interne qui l’’a empêché de satisfaire la requête.exceptionjavax.servlet.ServletException javax.faces.webapp.FacesServlet.service(FacesServlet.java:422)cause mèrejava.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.
hibernatehibernate.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文件
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; }}
映射文件: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 /></id> </class></hibernate-mapping>
springAnneeMetier.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 class='dao.AnneeHibernateDao'></bean> <bean 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>
请你能帮我,我会很感激的
编辑: 这是更新的堆栈跟踪
mai 14,2014 1:14:41 AM org.apache.catalina.core.StandardWrapperValve invokeSEVERE: 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 causejava.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)
编辑2: 这是AnneeBean类
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; }}
编辑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>