Primefaces -> DataTable - Lazy Loading - java

I have a problem with DataTable - Lazy Loading. I think the problem is in IdiomasBean.java (the equilavent to TableBean.java), if I put:
public IdiomasBean() { }
public LazyDataModel<Idiomas> getLazyModel() {
lazyModel = new LazyIdiomasDataModel(idiomasBo.findAllIdiomas());
return lazyModel;
}
I get the datatable right, but... sortBy, filterBy and onRowSelect don't work.
public IdiomasBean() {
lazyModel = new LazyIdiomasDataModel(idiomasList);
}
public LazyDataModel<Idiomas> getLazyModel() {
return lazyModel;
}
I get: java.lang.NullPointerException
Here is the stack trace:
> at
> brany.view.lazyDataModel.LazyIdiomasDataModel.load(LazyIdiomasDataModel.java:42)
> at
> org.primefaces.component.datatable.DataTable.loadLazyData(DataTable.java:690)
> at
> org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:192)
> at
> org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:108)
> at
> javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
> at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1763)
> at javax.faces.render.Renderer.encodeChildren(Renderer.java:168) at
> javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
> at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756)
> 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.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
> at
> org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
> at
> org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
> at
> org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
> at
> org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
> at
> org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
> at
> org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
> at
> org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
> at
> org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
> at
> org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
> at
> org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
> at
> org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
> at
> org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
> at
> org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
> 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)
And here is the rest of the code:
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:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>PRUEBA PRIMEFACES</title>
</h:head>
<h:body>
<h:form id="form">
<p:dataTable var="id" value="#{idiomasBean.lazyModel}" paginator="true" rows="10"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15" selectionMode="single" selection="#{idiomasBean.selectedIdiomas}" id="idiomasTable" lazy="true">
<p:ajax event="rowSelect" listener="#{idiomasBean.onRowSelect}" update=":form:display" oncomplete="idiomasDialog.show()" />
<p:column headerText="Nombre" sortBy="#{id.nombre}" filterBy="#{id.nombre}">
<h:outputText value="#{id.nombre}" />
</p:column>
<p:column headerText="Año" sortBy="#{id.name}" filterBy="#{id.name}">
<h:outputText value="#{id.name}" />
</p:column>
</p:dataTable>
<p:dialog header="Detalles Idioma" widgetVar="idiomasDialog" resizable="false"
showEffect="explode" hideEffect="explode">
<h:panelGrid id="display" columns="2" cellpadding="4">
<h:outputText value="Nombre:" />
<h:outputText value="#{idiomasBean.selectedIdiomas.nombre}" style="font-weight:bold"/>
<h:outputText value="Valoración:" />
<h:outputText value="#{idiomasBean.selectedIdiomas.valoracion}" style="font-weight:bold"/>
</h:panelGrid>
</p:dialog>
</h:form>
</h:body>
</html>
idiomasBean.java
package brany.spring.managedBean;
import brany.model.bo.imp.IdiomasBo;
import brany.model.entityBean.Idiomas;
import brany.view.lazyDataModel.LazyIdiomasDataModel;
import java.util.List;
import org.primefaces.model.LazyDataModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
#Controller
#Scope("session")
public class IdiomasBean implements java.io.Serializable {
private String nombre;
private String name;
#Autowired
private IdiomasBo idiomasBo;
private List<Idiomas> idiomasList;
private LazyDataModel<Idiomas> lazyModel;
private Idiomas selectedIdiomas;
public IdiomasBean() {
lazyModel = new LazyIdiomasDataModel(idiomasList);
}
public void setIdiomasBo (IdiomasBo idiomasBo) {
this.idiomasBo = idiomasBo;
}
public List<Idiomas> getIdiomasList() {
idiomasList = idiomasBo.findAllIdiomas();
return idiomasList;
}
public IdiomasBo getIdiomasBo () {
return idiomasBo;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public LazyDataModel<Idiomas> getLazyModel() {
return lazyModel;
}
public Idiomas getSelectedIdiomas() {
return selectedIdiomas;
}
public void setSelectedIdiomas(Idiomas selectedIdiomas) {
this.selectedIdiomas = selectedIdiomas;
}
}
LazyIdiomasDataModel.java
package brany.view.lazyDataModel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import brany.model.entityBean.Idiomas;
import brany.view.util.LazySorter;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
public class LazyIdiomasDataModel extends LazyDataModel<Idiomas> {
private List<Idiomas> datasource;
public LazyIdiomasDataModel(List<Idiomas> datasource) {
this.datasource = datasource;
}
#Override
public Idiomas getRowData(String rowKey) {
for(Idiomas idiomas : datasource) {
if(idiomas.getNombre().equals(rowKey))
return idiomas;
}
return null;
}
#Override
public Object getRowKey(Idiomas idiomas) {
return idiomas.getNombre();
}
#Override
public List<Idiomas> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {
List<Idiomas> data = new ArrayList<Idiomas>();
//filter
for(Idiomas idiomas : datasource) {
boolean match = true;
for(Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {
try {
String filterProperty = it.next();
String filterValue = filters.get(filterProperty);
String fieldValue = String.valueOf(idiomas.getClass().getField(filterProperty).get(idiomas));
if(filterValue == null || fieldValue.startsWith(filterValue)) {
match = true;
}
else {
match = false;
break;
}
} catch(Exception e) {
match = false;
}
}
if(match) {
data.add(idiomas);
}
}
//sort
if(sortField != null) {
Collections.sort(data, new LazySorter(sortField, sortOrder));
}
//rowCount
int dataSize = data.size();
this.setRowCount(dataSize);
//paginate
if(dataSize > pageSize) {
try {
return data.subList(first, first + pageSize);
}
catch(IndexOutOfBoundsException e) {
return data.subList(first, first + (dataSize % pageSize));
}
}
else {
return data;
}
}
}
IdiomasBo.java
package brany.model.bo.imp;
import brany.model.bo.IIdiomasBo;
import brany.model.dao.imp.IdiomasDao;
import brany.model.entityBean.Idiomas;
import java.util.List;
import org.springframework.stereotype.Service;
#Service
public class IdiomasBo implements IIdiomasBo {
private IdiomasDao idiomasDao;
public void setIdiomasDao (IdiomasDao idiomasDao) {
this.idiomasDao = idiomasDao;
}
#Override
public List<Idiomas> findAllIdiomas() {
return this.idiomasDao.findAllIdiomas();
}
}
IdiomasDao.java
package brany.model.dao.imp;
import brany.model.dao.IIdiomasDao;
import brany.model.entityBean.Idiomas;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
#Repository
public class IdiomasDao extends HibernateDaoSupport implements IIdiomasDao {
#Override
public List<Idiomas> findAllIdiomas() {
return getHibernateTemplate().find("from Idiomas");
}
}
Idiomas.java
package brany.model.entityBean;
public class Idiomas implements java.io.Serializable {
private Integer ididioma;
private String nombre;
private String name;
public Idiomas() {
}
public Idiomas(String nombre, String name) {
this.nombre = nombre;
this.name = name;
}
public Integer getIdidioma() {
return this.ididioma;
}
public void setIdidioma(Integer ididioma) {
this.ididioma = ididioma;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
LazySorter.java
package brany.view.util;
import java.util.Comparator;
import brany.spring.util.ReflectionUtil;
import org.primefaces.model.SortOrder;
public class LazySorter<T> implements Comparator<T> {
private String sortField;
private SortOrder sortOrder;
public LazySorter(String sortField, SortOrder sortOrder) {
this.sortField = sortField;
this.sortOrder = sortOrder;
}
#Override
public int compare(Object first, Object second) {
try {
Object value1 = ReflectionUtil.getValue(first, sortField);
Object value2 = ReflectionUtil.getValue(second, sortField);
int value = 0;
if(value1 instanceof Comparable)
value = ((Comparable) value1).compareTo(value2);
else if(value1 instanceof Boolean && !value1.equals(value2))
value = (Boolean)value1 ? 1 : -1;
return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
ReflectionUtil.java
package brany.spring.util;
public class ReflectionUtil {
public static Object getValue(Object object, String fieldName) {
try {
String getterName = "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
return object.getClass().getMethod(getterName).invoke(object);
} catch (Exception e) {
return null;
}
}
}
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>
<!-- Estamos activando el soporte de Spring para la inyección de dependencias
de tal forma que JSF sabrá que si no encuentra un bean bajo su contexto debe
ir a buscarlo al contexto de Spring -->
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
</application>
<!-- Definimos el bean que va a trabajar con la aplicación que tiene asociada la
clase IdiomasBean y seteamos el atributo (property) idiomasBo-->
<managed-bean>
<managed-bean-name>idiomasBean</managed-bean-name>
<managed-bean-class>brany.spring.managedBean.IdiomasBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>idiomasBo</property-name>
<value>#{idiomasBo}</value>
</managed-property>
</managed-bean>
</faces-config>
Does anybody have any solution?
Thanks!

Try this for your LazySorter class should fix the sort by not working
public class LazySorter implements Comparator<Idiomas> {
private String sortField;
private SortOrder sortOrder;
/**
* initializing sorting field and sorting order
* #param sortField
* #param sortOrder
*/
public LazySorter(String sortField, SortOrder sortOrder) {
this.sortField = sortField;
this.sortOrder = sortOrder;
}
/**
* Comparing object1 and object2 with reflection
* #param object1
* #param object2
* #return
*/
#Override
public int compare(Idiomas object1, Idiomas object2) {
try {
Field field1 = object1.getClass().getDeclaredField(this.sortField);
Field field2 = object2.getClass().getDeclaredField(this.sortField);
field1.setAccessible(true);
field2.setAccessible(true);
Object value1 = field1.get(object1);
Object value2 = field2.get(object2);
int value = ((Comparable)value1).compareTo(value2);
return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
}
catch(Exception e) {
throw new RuntimeException();
}
}
}

Related

Java Hibernate Web Application failed to Display data with MySQL Database

I am learning Java CRUD operation with Hibernate . I am using MYSQL database for back end and its running without any problem . But when i run the application ,its shows following errors .
java.lang.ExceptionInInitializerError
at com.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:36)
at com.util.HibernateUtil.getSessionFactory(HibernateUtil.java:42)
at com.dao.UserDAO.AllUsers(UserDAO.java:26)
at com.controller.bean.UserBean.getUsers(UserBean.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:363)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstValue.getValue(AstValue.java:140)
at com.sun.el.parser.AstValue.getValue(AstValue.java:204)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226)
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:732)
at org.primefaces.component.datatable.DataTable.getValue(DataTable.java:1002)
at org.primefaces.component.api.UIData.getDataModel(UIData.java:629)
at javax.faces.component.UIData.getRowCount(UIData.java:356)
at org.primefaces.component.api.UIData.calculateFirst(UIData.java:175)
at org.primefaces.component.datatable.DataTableRenderer.preRender(DataTableRenderer.java:110)
at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:82)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:889)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:456)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:133)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [com.mysql.jdbc.Driver]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:245)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.loadDriverIfPossible(DriverManagerConnectionProviderImpl.java:200)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildCreator(DriverManagerConnectionProviderImpl.java:156)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:95)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at com.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:29)
... 64 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : com.mysql.jdbc.Driver
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:230)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:242)
Here is code UserBeans ..
ManagedBean(name = "userBean")
#ViewScoped
public class UserBean implements Serializable {
private List<User> usersList;
private List<User> searchList;
private List<User> searchByRecordNoList;
UserDAO userDao = new UserDAO();
User user = new User();
User newuser = new User();
public List<User> getUsers()
{
usersList = userDao.AllUsers();
int count = usersList.size();
return usersList;
}
public void addUser(){
String Remark = newuser.getRemark();
Integer userId=0;
userId= userDao.getId();
newuser.setId(userId);
String Id = Integer.toString(newuser.getId());
newuser.setRecordNo(Integer.toString(userId));
userDao.add(newuser);
System.out.println("User successfully saved.");
FacesMessage message= new FacesMessage(FacesMessage.SEVERITY_INFO, "Save Information","User successfully saved.");
RequestContext.getCurrentInstance().showMessageInDialog(message);
newuser = new User();
}
public void changeUser(User user) {
this.user= user;
}
public void UpdateUser(User user){
String Name = user.getName();
FacesMessage message1= new FacesMessage(FacesMessage.SEVERITY_INFO, "Name",Name);
RequestContext.getCurrentInstance().showMessageInDialog(message1);
userDao.update(user);
System.out.println("User Info successfully saved.");
FacesMessage message= new FacesMessage(FacesMessage.SEVERITY_INFO, "Save Information","User updated successfully .");
RequestContext.getCurrentInstance().showMessageInDialog(message);
user = new User();
}
public void deleteUser(User user){
String Name = user.getName();
//FacesMessage message3= new FacesMessage(FacesMessage.SEVERITY_INFO, "Delete Item",contactName);
// RequestContext.getCurrentInstance().showMessageInDialog(message3);
userDao.delete(user);
FacesMessage message= new FacesMessage(FacesMessage.SEVERITY_INFO, "Delete","Record deleted successfully");
RequestContext.getCurrentInstance().showMessageInDialog(message);
}
public void searchbyRecordno(){
searchByRecordNoList=userDao.SearchByRecordNo(user.getRecordNo());
int count = searchByRecordNoList.size();
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Number of Record Selected:", Integer.toString(count));
RequestContext.getCurrentInstance().showMessageInDialog(message);
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public User getNewuser() {
return newuser;
}
public void setNewuser(User newuser) {
this.newuser = newuser;
}
public List<User> getUsersList() {
return usersList;
}
public void setUsersList(List<User> usersList) {
this.usersList = usersList;
}
public List<User> getSearchList() {
return searchList;
}
public void setSearchList(List<User> searchList) {
this.searchList = searchList;
}
public List<User> getSearchByRecordNoList() {
return searchByRecordNoList;
}
public void setSearchByRecordNoList(List<User> searchByRecordNoList) {
this.searchByRecordNoList = searchByRecordNoList;
}
public void onRowEdit(RowEditEvent event) {
FacesMessage msg = new FacesMessage(" Edited Record No", ((User) event.getObject()).getRecordNo());
FacesContext.getCurrentInstance().addMessage(null, msg);
User editeduser = (User) event.getObject();
userDao.update(editeduser);
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Edit Cancelled");
FacesContext.getCurrentInstance().addMessage(null, msg);
usersList.remove((User) event.getObject());
}
}
Here is the code in UserDAO..
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.dao;
import java.util.List;
import java.util.ArrayList;
import org.hibernate.Query;
import org.hibernate.Session;
import com.util.HibernateUtil;
import com.model.pojo.User;
public class UserDAO {
private User user;
private User newuser;
private List<User> DaoAllUsers;
private List<User> DaoSearchUserList;
//Session session;
public List<User> AllUsers(){
Session session = HibernateUtil.getSessionFactory().openSession();
try{
session.beginTransaction();
DaoAllUsers = session.createCriteria(User.class).list();
int count =DaoAllUsers.size();
// FacesMessage message1 = new FacesMessage(FacesMessage.SEVERITY_INFO, "List Size", Integer.toString(count));//Debugging Purpose
//RequestContext.getCurrentInstance().showMessageInDialog(message1);
session.getTransaction().commit();
}
catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}
session.close();
return DaoAllUsers;
}
public Integer getId (){
Session session = HibernateUtil.getSessionFactory().openSession();
String hql = "select max(U.id) from Users U";
Query query = session.createQuery(hql);
List<Integer> results = query.list();
Integer userId = 1;
if (results.get(0) != null ) {
userId = results.get(0)+1 ;
}
session.flush();
session.close();
return userId;
}
public List<User> SearchByRecordNo(String RecordNo) {
Session session= HibernateUtil.getSessionFactory().openSession();
List<User> daoSearchList = new ArrayList<>();
try{
session.beginTransaction();
Query qu = session.createQuery("From Users U where U.recordNo =:recordNo");//User is the entity not the table
qu.setParameter("recordNo", RecordNo);
daoSearchList=qu.list();
int count = daoSearchList.size();
session.getTransaction().commit();
}
catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}
finally {
session.close();
}
return daoSearchList;
}
public void add(User newuser){
Session session = HibernateUtil.getSessionFactory().openSession();
try{
String Id = Integer.toString(newuser.getId());
// begin a transaction
session.beginTransaction();
session.merge(newuser);
session.flush();
System.out.println("NewUser saved, id: " +
newuser.getId());
session.getTransaction().commit();
}
catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}
session.close();
}
public void delete(User user){
Session session = HibernateUtil.getSessionFactory().openSession();
try{
String name= user.getName();
session.beginTransaction();
session.delete(user);
session.getTransaction().commit();
}
catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}
session.close();
}
public void update(User user){
Session session = HibernateUtil.getSessionFactory().openSession();
try{
session.beginTransaction();
session.update(user);
session.flush();
session.getTransaction().commit();
}
catch(Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}
session.close();
}
}
Here is the code in User Class.
#Entity
#Table(name="users"
,catalog="userinformation"
)
public class User implements java.io.Serializable {
private Integer id;
private String recordNo;
private String name;
private Integer age;
private String sex;
private Date dob;
private String remark;
public User() {
}
public User(String recordNo, String name, Integer age, String sex, Date dob, String remark) {
this.recordNo = recordNo;
this.name = name;
this.age = age;
this.sex = sex;
this.dob = dob;
this.remark = remark;
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="id", unique=true, nullable=false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name="RecordNo", length=20)
public String getRecordNo() {
return this.recordNo;
}
public void setRecordNo(String recordNo) {
this.recordNo = recordNo;
}
#Column(name="Name", length=50)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="Age")
public Integer getAge() {
return this.age;
}
public void setAge(Integer age) {
this.age = age;
}
#Column(name="Sex", length=20)
public String getSex() {
return this.sex;
}
public void setSex(String sex) {
this.sex = sex;
}
#Temporal(TemporalType.DATE)
#Column(name="Dob", length=10)
public Date getDob() {
return this.dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
#Column(name="Remark", length=50)
public String getRemark() {
return this.remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
//This method writes the values of contact object with System.out.println(Emp.toString()) code
#Override
public String toString() {
return "users"
+ "\n\t RecordNo: " + this.recordNo
+ "\n\t EmployeeName: " + this.name
+ "\n\t Age: " + this.age
+ "\n\t Sex: " + this.sex
+ "\n\t Date of Birth: " + this.dob
+ "\n\t Remark: " + this.remark;
}
}
Here is the code HibernateUtil Class .
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
//Annotation based configuration
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("/hibernate.cfg.xml");
System.out.println("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created");
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null) sessionFactory = buildSessionFactory();
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
sessionFactory.close();
}
}
Here is the hibernate.cfg.xml file .
<?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/userinformation?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"/>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.model.pojo.User"/>
<mapping class="com.model.pojo.User"/>
</session-factory>
</hibernate-configuration>
Here is the code in hibernate.revenge.xml file ..
<?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="userinformation"/>
<table-filter match-name="users"/>
</hibernate-reverse-engineering>
Here is the HTML Code .
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<h2><center>All User Information</center></h2>
</h:head>
<h:body>
<h:form>
<p:commandButton action="Search?faces-redirect=true" icon="ui-icon-search" value="Search" />
</h:form>
<p:spacer> </p:spacer>
<h:form id="form1">
<p:dataTable id="dataTable" var="user" paginator="true" rows="5" value="#{userBean.users}">
<p:column headerText="RecordNo">
<h:outputText value="#{user.recordNo}"/>
</p:column>
<p:column headerText="Name" >
<h:outputText value="#{user.name}"/>
</p:column>
<p:column sortBy="#{user.age}" headerText="Age" >
<h:outputText value="#{user.age}"/>
</p:column>
<p:column headerText="Sex">
<h:outputText value="#{user.sex}"/>
</p:column>
<p:column headerText="Date of Birth" >
<h:outputText value="#{user.dob}">
<f:convertDateTime type="date" pattern="dd-MMM-yyyy"/>
</h:outputText>
</p:column>
<p:column headerText="Remark" >
<h:outputText value="#{user.remark}"/>
</p:column>
</p:dataTable>
</h:form>
<h:panelGroup >
<h3>Add User Information</h3>
<h:form>
<p>User Name: <p:inputText value="#{userBean.newuser.name}" /></p>
<p>User Age: <p:inputText value="#{userBean.newuser.age}" />Enter Number Only</p>
<h:panelGrid columns="2" style="margin-bottom:10px" cellpadding="5">
<p>Choose Sex:</p>
<p:selectOneMenu label="Sex:" value="#{userBean.newuser.sex}" id="ulist2">
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItem itemLabel="Male" itemValue="Male"/>
<f:selectItem itemLabel="Female" itemValue="Female"/>
</p:selectOneMenu>
</h:panelGrid>
<p>User Date of Birth: <p:calendar id="dop" value="#{userBean.newuser.dob}" label="DatePosted:"
required="true" pattern="dd/MMM/yyyy" effect="slideDown" requiredMessage="Please Enter Date of Posting!"
navigator="true" showButtonPanel="true" yearRange="c-60:c+60" /> </p>
<p>Remark: <p:inputTextarea value="#{userBean.newuser.remark}" /></p>
<p><p:commandButton icon="ui-icon-plusthick" update=":form1:dataTable" type="submit" value="add" action="#{userBean.addUser()}" /></p>
</h:form>
</h:panelGroup>
</h:body>
</html>
Here is the screen shot when i run the application .
Looks like the MySQL driver can't be found. Some things to check:
Has the driver JAR been deployed to the serverlet container or
application server?
Have the connection details been verified through
the container console?

How to populate the dropdown list using <s:select> tag and hibernate in?

I am working on a project using Struts2 and Hibernate. After employees successfully log on, they will be brought to a new page displaying an event list. This list will be a dropdown select list. I have successfully written and tested my code for logon part, but when I add the second jsp page with tag, they show me the following exception:
message tag 'select', field 'list', name 'yourEvent': The requested list key 'events' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: tag 'select', field 'list', name 'yourEvent': The requested list key 'events' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:555)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:164)
org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:371)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:275)
org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:161)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:563)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
The following is my MemberScreen.jsp with <s:select> tag inside:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Field Passes</title>
<style>
.errorMessage {
color: red;
}
</style>
</head>
<body>
<h1>Field Passes</h1>
<p align="center">Welcome <s:property value="#session['employee'].first_name"/>!</p><br>
<s:form action="FieldPassInput" method="post">
<s:select label="Event" headerKey="-1" headerValue="Select an event:" name="yourEvent" list="events" listKey="evt_dt" listValue="evt_desc" />
</s:form>
</body>
</html>
The following is my action code:
package actions;
import business.Event;
import business.EventDB;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
public class FieldPass extends ActionSupport {
private List<Event> events;
private String yourEvent;
public List<Event> getEventStrings() {
return events;
}
public void setEventStrings(List<Event> events) {
this.events = events;
}
public String getYourEvent() {
return yourEvent;
}
public void setYourEvent(String yourEvent) {
this.yourEvent = yourEvent;
}
public FieldPass() {
events = EventDB.getEvents();
}
#Override
public String execute() throws Exception {
//throw new UnsupportedOperationException("Not supported yet.");
return SUCCESS;
}
}
The following is my code for the Event Entity:
package business;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name = "Events")
public class Event {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long evt_id;
#Temporal(TemporalType.DATE)
private Date evt_date;
private String day_of_week;
private String evt_desc;
private String evt_notes;
private String closed;
private int pass_limit;
private String lg_area;
private String lg_area_name;
public Event() {
evt_date = null;
day_of_week = "";
evt_desc = "";
evt_notes = "";
closed = "";
pass_limit = 0;
lg_area = "";
lg_area_name = "";
}
public long getEvt_id() {
return evt_id;
}
public void setEvt_id(long evt_id) {
this.evt_id = evt_id;
}
public Date getEvt_date() {
return evt_date;
}
public void setEvt_date(Date evt_date) {
this.evt_date = evt_date;
}
public String getDay_of_week() {
return day_of_week;
}
public void setDay_of_week(String day_of_week) {
this.day_of_week = day_of_week;
}
public String getEvt_desc() {
return evt_desc;
}
public void setEvt_desc(String evt_desc) {
this.evt_desc = evt_desc;
}
public String getEvt_notes() {
return evt_notes;
}
public void setEvt_notes(String evt_notes) {
this.evt_notes = evt_notes;
}
public String getClosed() {
return closed;
}
public void setClosed(String closed) {
this.closed = closed;
}
public int getPass_limit() {
return pass_limit;
}
public void setPass_limit(int pass_limit) {
this.pass_limit = pass_limit;
}
public String getLg_area() {
return lg_area;
}
public void setLg_area(String lg_area) {
this.lg_area = lg_area;
}
public String getLg_area_name() {
return lg_area_name;
}
public void setLg_area_name(String lg_area_name) {
this.lg_area_name = lg_area_name;
}
}
The following is my Hibernate data processing code:
package business;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import utility.HibernateUtil;
public class EventDB {
public static List<Event> getEvents() {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = null;
List<Event> events = null;
try {
session = sessionFactory.openSession();
String qS = "from Event";
Query q = session.createQuery(qS);
events = q.list();
} catch (Exception e) {
events = null;
} finally {
if (session != null) {
session.close();
}
}
return events;
}
}
The following code is my struts.xml:
<struts>
<!-- Configuration for the default package. -->
<package name="default" extends="struts-default">
<action name="EmployeeLogon" class="actions.Logon">
<result name="success">/MemberScreen.jsp</result>
<result name="error">/Error.jsp</result>
<result name="input">/Logon.jsp</result>
</action>
<action name="FieldPassInput" class="actions.FieldPass">
<result name="success">/MemberScreen.jsp</result>
<result name="input">/MemberScreen.jsp</result>
</action>
</package>
</struts>
The following is hibernate config:
<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/FIELDPASS?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">sesame</property>
<mapping class="business.Employee"/>
<mapping class="business.Event"/>
</session-factory>
</hibernate-configuration>
For completeness, I also post my logon.jsp and its action codes here:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Employee Logon</title>
<style>
.errorMessage {
color: red;
}
</style>
</head>
<body>
<h1>Welcome to the Field Pass - Please Logon</h1>
<s:form action="EmployeeLogon" method="post">
<table>
<tr>
<s:textfield name="employeeid" id="employeeid" label="Employee ID" required="true"/>
</tr>
<tr>
<s:password name="pattempt" id="pattempt" label="Password" required="true"/>
</tr>
<tr>
<s:submit value="Logon"/>
</tr>
</table>
</s:form>
${msg}
</body>
</html>
package actions;
import business.Employee;
import business.EmployeeDB;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
public class Logon extends ActionSupport implements SessionAware {
private Employee employee;
private String employeeid;
private String pattempt;
private Map session;
public String getEmployeeid() {
return employeeid;
}
public void setEmployeeid(String employeeid) {
this.employeeid = employeeid;
}
public String getPattempt() {
return pattempt;
}
public void setPattempt(String pattempt) {
this.pattempt = pattempt;
}
#Override
public void setSession(Map session) {
this.session = session;
}
public Logon() {
}
#Override
public String execute() throws Exception {
//throw new UnsupportedOperationException("Not supported yet.");
String rval = ERROR, msg = "";
Map request = (Map)ActionContext.getContext().get("request");
employee = EmployeeDB.getEmployee(Integer.parseInt(employeeid));
if (employee != null) {
employee.setPassAttempt(Integer.parseInt(this.pattempt));
if (employee.isAuthenticated()) {
session.put("employee", employee);
msg = "Member authenticated";
rval = SUCCESS;
} else if (!employee.getMsg().isEmpty()) {
msg = employee.getMsg();
rval = INPUT;
}
} else {
msg = "Hibernate returned null member.";
rval = INPUT;
}
request.put("msg", msg);
return rval;
}
#Override
public void validate() {
try {
int pat = Integer.parseInt(this.pattempt);
if (pat <= 0) {
throw new Exception("Bad password");
}
} catch (Exception e) {
addFieldError("pattempt", "Password issue: " + e.getMessage());
}
}
}
package business;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
#Entity
public class Employee {
#Id
private int emp_id;
private String last_name;
private String first_name;
private String middle_initial;
#Temporal(TemporalType.DATE)
private Date hire_date;
private int dept_id;
private int password;
private String admin;
#Transient
private int passattempt;
#Transient
private String msg;
public Employee() {
emp_id = 0;
last_name = "";
first_name = "";
middle_initial = "";
hire_date = null;
dept_id = 0;
password = 0;
passattempt = -1;
msg = "";
}
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getMiddle_initial() {
return middle_initial;
}
public void setMiddle_initial(String middle_initial) {
this.middle_initial = middle_initial;
}
public Date getHire_date() {
return hire_date;
}
public void setHire_date(Date hire_date) {
this.hire_date = hire_date;
}
public int getDept_id() {
return dept_id;
}
public void setDept_id(int dept_id) {
this.dept_id = dept_id;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public String getAdmin() {
return admin;
}
public void setAdmin(String admin) {
this.admin = admin;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public void setPassAttempt(int patt) {
this.passattempt = patt;
}
public boolean isAuthenticated() {
if (this.password > 0) {
if (this.password == this.passattempt) {
return true;
} else {
msg = "Member not authenticated";
}
}
return false;
}
}
package business;
import javax.persistence.NoResultException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import utility.HibernateUtil;
public class EmployeeDB {
public static Employee getEmployee(int emp_id) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = null;
Employee e = null;
try {
String qS = "from Employee e where e.emp_id = :emp_id";
session = sessionFactory.openSession();
Query q = session.createQuery(qS);
q.setParameter("emp_id", emp_id);
e = (Employee)q.uniqueResult();
} catch (NoResultException ex) {
return null;
} finally {
session.close();
}
return e;
}
}
Can any Struts2 expert tell me what's wrong is my code so that I cannot populate data from database into my select dropdown list in MemberScreen.jsp? Thank you for your time and help.

javax.faces.el.EvaluationException: org.hibernate.LazyInitializationException: could not initialize proxy - no Session

i'm working on a project using jsf,spring and hibernate.
i get an exception in one case, but i don't really understand the reason why i'm getting this problem.
can you give me an idea what i did wrong
javax.el.ELException: /views/emissionsa.xhtml #102,171 actionListener="#{emission1Bean.payer()}": org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:147)
eeeeeeeeeeeee
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1015)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1575)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1533)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at net.vo.Salaire_$$_javassist_5.getPersonnel(Salaire_$$_javassist_5.java)
at controller.Emission1Bean.payer(Emission1Bean.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.el.parser.AstValue.invoke(AstValue.java:261)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
... 34 more
25-Jun-2014 23:42:28.209 SEVERE [http-nio-8084-exec-134] com.sun.faces.context.AjaxExceptionHandlerImpl.handlePartialResponseError org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at net.vo.Salaire_$$_javassist_5.getPersonnel(Salaire_$$_javassist_5.java)
at controller.Emission1Bean.payer(Emission1Bean.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.el.parser.AstValue.invoke(AstValue.java:261)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:147)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1015)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1575)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1533)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
emissionsa.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://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title>Facelet Title</title>
<style>
.p tr,.p td
{
border : none;
}
</style>
</h:head>
<h:body style="background-color: #ECF3FD;">
<h:graphicImage value="../../images/header.jpg" style="margin-left: auto;margin-right: auto;"></h:graphicImage>
<ui:include src="menu.xhtml" />
<br/>
<br/>
<h:form id="form">
<p:dataTable id="display" var="listeEmissions" value="#{emission1Bean.listeEmissions}" editable="true" style="margin-bottom:10px" rowKey="#{listeEmissions.dateEmission}" selection="#{emission1Bean.emission}" selectionMode="single">
<f:facet name="header">
Liste des factures émises
</f:facet>
<p:ajax event="rowEdit" listener="#{dtEditView.onRowEdit}" />
<p:ajax event="rowEditCancel" listener="#{dtEditView.onRowCancel}"/>
<p:column headerText="Date Emission">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{listeEmissions.dateEmission}" /></f:facet>
<f:facet name="input"><p:inputText id="modelInput" value="#{listeEmissions.dateEmission}" style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="N° Ordre de paiement">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{listeEmissions.nop}" /></f:facet>
<f:facet name="input"><p:inputText value="#{listeEmissions.nop}" style="width:100%" label="Year"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="N° Bordereau">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{listeEmissions.nbordereau}" /></f:facet>
<f:facet name="input"><p:inputText value="#{listeEmissions.nbordereau}" style="width:100%" label="Year"/></f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:32px" headerText="Modifier">
<p:commandLink styleClass="ui-icon ui-icon-pencil"/>
</p:column>
<p:column style="width:32px" headerText="Supprimer">
<p:commandLink styleClass="ui-icon ui-icon-trash" action="#{emission1Bean.delete()}" process="#this" update=":form:display">
<f:setPropertyActionListener target="#{emission1Bean.emission}" value="#{listeEmissions}" />
</p:commandLink>
</p:column>
</p:dataTable>
<p:commandButton value="Payer le salaire" update="emissionDetail" oncomplete="PF('emissionDialog').show()" />
<p:dialog header="Paiement du salaire" widgetVar="emissionDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false">
<p:panel id="emissionDetail" style="border:none;">
<p:panelGrid columns="2" rendered="#{not empty emission1Bean.emission}" columnClasses="label,value" style="border:none;">
<p:accordionPanel>
    <p:tab title="Payer le salaire">
<h:panelGrid styleClass="p" columns="2" cellpadding="5">
<h:outputText value="Date paiement: " />
<p:inputText value="#{emission1Bean.datePaiement}"/>
<h:outputText value="Compte Bancaire: " />
<p:selectOneMenu value="#{compteBancaireBean.idCompte}" >
<f:selectItem itemValue="#{null}" itemLabel="--Séléctionner un fournisseur" />
<f:selectItems value="#{compteBancaireBean.listeCompteBancaires}" var="compte"
itemValue="#{compte.idCompte}" itemLabel="#{compte.libelleCompte}" />
<f:ajax listener="#{compteBancaireBean.submit()}"/>
</p:selectOneMenu>
<h:outputText value="N° Chèque: " />
<p:inputText value="#{emission1Bean.ncheque}"/>
<h:outputText value="N° Virement: " />
<p:inputText value="#{emission1Bean.nvirement}"/>
<h:outputText value="N° Avis de virement: " />
<p:inputText value="#{emission1Bean.navis}"/>
</h:panelGrid>
</p:tab>
</p:accordionPanel>
</p:panelGrid>
<p:commandButton value="Valider" icon="ui-icon-circle-check" update="display" onclick="emissionDialog.hide();" actionListener="#{emission1Bean.payer()}"/>
<p:commandButton value="Annuler" icon="ui-icon-arrowreturnthick-1-w" onclick="emissionDialog.hide();"/>
</p:panel>
</p:dialog>
</h:form>
</h:body>
</html>
Emission1Bean.java
#Component
#Scope("view")
public class Emission1Bean {
#Autowired
private SalaireMetier salaireMetier;
#Autowired
private EmissionMetier emissionMetier;
#Autowired
private PaiementMetier paiementMetier;
#Autowired
private FactureMetier factureMetier;
#Autowired
private ComptebancaireMetier comptebancaireMetier;
private List<Emission> listeEmissions;
private Emission emission;
private String dateEmission;
private Salaire salaire;
private Integer nop;
private Integer nbordereau;
private int idCompte;
private String datePaiement;
private Comptebancaire comptebancaire;
private Archive archive;
private Integer ncheque;
private Integer nvirement;
private Integer navis;
#PostConstruct
public void init()
{
listeEmissions = emissionMetier.getAllEmissionsSa();
}
public void payer()
{
Emission e = emissionMetier.getEmission(getEmission().getDateEmission());
SalaireId id = new SalaireId(e.getSalaire().getPersonnel().getCin(),e.getSalaire().getMois().getMois());
Salaire s = salaireMetier.getSalaire(id);
Paiement p = new Paiement();
p.setDatePaiement(getDatePaiement());
p.setSalaire(s);
int c = CompteBancaireBean.submit();
Comptebancaire compte = comptebancaireMetier.getComptebancaire(c);
p.setComptebancaire(compte);
p.setNavis(getNavis());
p.setNcheque(getNcheque());
p.setNvirement(getNvirement());
paiementMetier.insert(p);
}
public int submit()
{
System.out.println(idCompte);
return idCompte;
}
public void delete(){
Emission e = emissionMetier.getEmission(getEmission().getDateEmission());
emissionMetier.delete(getEmission().getDateEmission());
listeEmissions.remove(emission);
emission = null;
SalaireId id1 = new SalaireId(e.getSalaire().getPersonnel().getCin(),e.getSalaire().getMois().getMois());
Salaire sa = salaireMetier.getSalaire(id1);
sa.setEtatSalaire("engage");
salaireMetier.update(sa);
}
public Salaire getSalaire() {
return salaire;
}
public void setSalaire(Salaire salaire) {
this.salaire = salaire;
}
public ComptebancaireMetier getComptebancaireMetier() {
return comptebancaireMetier;
}
public void setComptebancaireMetier(ComptebancaireMetier comptebancaireMetier) {
this.comptebancaireMetier = comptebancaireMetier;
}
public PaiementMetier getPaiementMetier() {
return paiementMetier;
}
public void setPaiementMetier(PaiementMetier paiementMetier) {
this.paiementMetier = paiementMetier;
}
public FactureMetier getFactureMetier() {
return factureMetier;
}
public void setFactureMetier(FactureMetier factureMetier) {
this.factureMetier = factureMetier;
}
public int getIdCompte() {
return idCompte;
}
public void setIdCompte(int idCompte) {
this.idCompte = idCompte;
}
public String getDatePaiement() {
return datePaiement;
}
public void setDatePaiement(String datePaiement) {
this.datePaiement = datePaiement;
}
public Comptebancaire getComptebancaire() {
return comptebancaire;
}
public void setComptebancaire(Comptebancaire comptebancaire) {
this.comptebancaire = comptebancaire;
}
public Archive getArchive() {
return archive;
}
public void setArchive(Archive archive) {
this.archive = archive;
}
public Integer getNcheque() {
return ncheque;
}
public void setNcheque(Integer ncheque) {
this.ncheque = ncheque;
}
public Integer getNvirement() {
return nvirement;
}
public void setNvirement(Integer nvirement) {
this.nvirement = nvirement;
}
public Integer getNavis() {
return navis;
}
public void setNavis(Integer navis) {
this.navis = navis;
}
public Emission getEmission() {
return emission;
}
public void setEmission(Emission emission) {
this.emission = emission;
}
public List<Emission> getListeEmissions() {
return listeEmissions;
}
public void setListeEmissions(List<Emission> listeEmissions) {
this.listeEmissions = listeEmissions;
}
public EmissionMetier getEmissionMetier() {
return emissionMetier;
}
public void setEmissionMetier(EmissionMetier emissionMetier) {
this.emissionMetier = emissionMetier;
}
public String getDateEmission() {
return dateEmission;
}
public void setDateEmission(String dateEmission) {
this.dateEmission = dateEmission;
}
public Integer getNop() {
return nop;
}
public void setNop(Integer nop) {
this.nop = nop;
}
public Integer getNbordereau() {
return nbordereau;
}
public void setNbordereau(Integer nbordereau) {
this.nbordereau = nbordereau;
}
}
i know that the problem i get is because of this line but i don't know what to do to fix it
SalaireId id = new SalaireId(e.getSalaire().getPersonnel().getCin(),e.getSalaire().getMois().getMois());
edit
EmissionDao.java
package dao;
import java.util.List;
import net.vo.Emission;
public interface EmissionDao {
public List getAllEmissions();
public List getAllEmissionsSa(Integer id,Integer m);
public Emission getEmission(String date);
public void insert(Emission emission);
public void update(Emission emission);
public void delete(String date);
}
EmissionHibernateDao
package dao;
import java.util.List;
import net.vo.Emission;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
#Repository
public class EmissionHibernateDao implements EmissionDao{
private List<Emission> listeEmissions;
private Emission emission;
public void init()
{
System.out.println("Méthode d'initiation");
}
/*#Override
public List<Object> getAllEmissions() {
Session session=HibernateUtil.getSession();
try
{
session.beginTransaction();
Query q = session.createQuery("select f.idFacture,f.dateFacture,f.montantFacture,f.etatFacture,e.dateEmission,e.nop,e.nbordereau from Facture f,Emission e where e.facture = f.idFacture and f.etatFacture='émise'");
listeEmissions = q.list();
return listeEmissions;
}
catch(HibernateException e)
{
throw e;
}
finally
{
session.close();
}
}*/
#Override
public List getAllEmissions() {
Session session=HibernateUtil.getSession();
try
{
session.beginTransaction();
Query q = session.createQuery("from Emission as e left join fetch e.facture as f where f.etatFacture = 'emise'");
listeEmissions = q.list();
return listeEmissions;
}
catch(HibernateException e)
{
throw e;
}
finally
{
session.close();
}
}
#Override
public List getAllEmissionsSa(Integer id,Integer m) {
Session session=HibernateUtil.getSession();
try
{
session.beginTransaction();
Query q = session.createQuery("from Emission as e left join fetch e.salaire as s left join fetch s.personnel left join fetch s.mois as m where m.annee.annee =:annee and m.mois =:mois and s.etatSalaire = 'emis' ");
q.setParameter("mois", m);
q.setParameter("annee",id);
listeEmissions = q.list();
return listeEmissions;
}
catch(HibernateException e)
{
throw e;
}
finally
{
session.close();
}
}
#Override
public Emission getEmission(String date) {
Session session = HibernateUtil.getSession();
try
{ System.out.println("eeeeeeeeeeeee");
session.beginTransaction();
Query q = session.createQuery("from Emission as em where em.dateEmission='" + date +"'");
return (Emission) q.uniqueResult();
}
finally
{
session.close();
}
}
#Override
public void insert(Emission emission) {
Session session = HibernateUtil.getSession();
Transaction tx=null;
try
{
tx = session.beginTransaction();
session.save(emission);
tx.commit();
}
catch(RuntimeException e)
{
if(tx != null)
{
tx.rollback();
}
throw e;
}
finally
{
session.close();
}
}
#Override
public void update(Emission emission) {
Session session = HibernateUtil.getSession();
Transaction tx=null;
try
{
tx=session.beginTransaction();
session.update(emission);
tx.commit();
}
catch(RuntimeException e)
{
if(tx != null)
{
tx.rollback();
}
throw e;
}
finally
{
session.close();
}
}
#Override
public void delete(String date) {
Session session = HibernateUtil.getSession();
Transaction tx = null;
try
{
tx=session.beginTransaction();
emission = (Emission) session.get(Emission.class,date);
session.delete(emission);
tx.commit();
}
catch(RuntimeException e)
{
if(tx != null)
{
tx.rollback();
}
throw e;
}
finally
{
session.close();
}
}
}
This is an Hibernate problem. The entity has fields declared to be lazy loaded but the entity is not attached to a valid Hibernate Session to fire the proxies to retrieve the data lazily. From the stacktrace, I cannot be sure if this error is thrown by e.getSalaire().getPersonnel().getCin() or .getSalaire().getMois().getMois() (or maybe both).
I don't know how you configured the session management, probably Spring is handling it. To solve this, you should re attach the entity to a valid Hibernate Session. You can do this by using HibernateTemplate#refresh method from the Spring Hibernate integration classes.

Integration jsf, spring, hibernate. How to inject Spring beans into JSF managed beans?

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>
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:
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/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:
Bean properties are shared across different sessions
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.
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:
You initialize anneeMetier by calling the setAnneeMetier before you use getListeAnnees
You implement a constructor for your AnneeBean class where you initialize anneeMetier
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.

<h:selectOneMenu> NullPointerException getAsObject method [duplicate]

This question already has answers here:
How to inject #EJB, #PersistenceContext, #Inject, #Autowired, etc in #FacesConverter?
(5 answers)
Closed 7 years ago.
I'm using netbean 7.0.1, glassfish 3.1, primefaces 2.2.1.
This is view
<ui:define name="content">
<h:form enctype="multipart/form-data">
<p:wizard>
<p:tab title="Tab 01">
<p:panel header="This is tab 01">
<h:messages errorStyle="color:red"/>
<h:panelGrid>
<h:selectOneMenu value="#{sellerController.currentCity}">
<f:selectItems value="#{cityController.listCity}" var="obj" itemLabel="#{obj.name}" itemValue="#{obj}"/>
</h:selectOneMenu>
</h:panelGrid>
</p:panel>
</p:tab>
<p:tab title="Tab 02">
<p:panel header="This is tab 02">
<h:panelGrid>
<p:commandButton value="Save" action="#{sellerController.addProperty()}"/>
</h:panelGrid>
</p:panel>
</p:tab>
</p:wizard>
</h:form>
</ui:define>
also try with
<h:selectOneMenu value="#{sellerController.currentCity}">
<f:selectItems value="#{cityController.itemsAvailableSelectOne}"/>
</h:selectOneMenu>
When i click next button on tab 01 and save button on tab 02, sellerController.currentCity return null value. Save button still call : "addProperty()". I got this error
INFO: java.lang.NullPointerException
java.lang.NullPointerException
at my.controller.CityController$CityControllerConverter.getAsObject(CityController.java:67)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:171)
at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectOneValue(MenuRenderer.java:202)
at com.sun.faces.renderkit.html_basic.MenuRenderer.getConvertedValue(MenuRenderer.java:319)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1030)
at javax.faces.component.UIInput.validate(UIInput.java:960)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1233)
at javax.faces.component.UIInput.processValidators(UIInput.java:698)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at org.primefaces.component.wizard.Wizard.processValidators(Wizard.java:216)
at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:508)
at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1589)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1600)
at javax.faces.component.UIForm.visitTree(UIForm.java:344)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1600)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1600)
at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:376)
at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:252)
at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:183)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1170)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
i have two controller, this is CityController :
#Named(value = "cityController")
#SessionScoped
public class CityController implements Serializable {
#EJB
CityModel cityModel;
List<City> listCity;
/** Creates a new instance of CityController */
public CityController() {
}
public List<City> getListCity(){
if (listCity==null) {
listCity = new ArrayList<City>();
listCity = cityModel.findAll();
}
return listCity;
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(cityModel.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(cityModel.findAll(), true);
}
#FacesConverter(forClass = City.class)
public static class CityControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return "";
}
CityController controller = (CityController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "customerController");
return controller.cityModel.find(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof City) {
City o = (City) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + CityController.class.getName());
}
}
}
}
This is SellerController
#Named(value = "sellerController")
#SessionScoped
public class SellerController implements Serializable {
#EJB
CityModel cityModel;
private City currentCity;
/** Creates a new instance of SellerController */
public SellerController() {
}
public City getCurrentCity() {
if (currentCity==null) {
currentCity = new City();
}
return currentCity;
}
public void setCurrentCity(City currentCity) {
this.currentCity = currentCity;
}
public void addProperty(){
System.out.println("Call from Save button ?? ");
}
}
This is JsfUtil class
public class JsfUtil {
public static SelectItem[] getSelectItems(List<?> entities, boolean selectOne) {
int size = selectOne ? entities.size() + 1 : entities.size();
SelectItem[] items = new SelectItem[size];
int i = 0;
if (selectOne) {
items[0] = new SelectItem("", "---");
i++;
}
for (Object x : entities) {
items[i++] = new SelectItem(x, x.toString());
}
return items;
}
}
Because of CityController. when i use
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name = "cityController")
#SessionScoped
It's work !
Considering this "cityController"-
#Named(value = "cityController")
#SessionScoped
public class CityController implements Serializable {
Is "customerController" right in the following -
CityController controller = (CityController) facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(), null, "customerController");
Change it to "cityController" as follows -
FacesContext fc = FacesContext.getCurrentInstance();
ELResolver elr = fc.getApplication().getELResolver();
ELContext elc = fc.getELContext();
CityController cc = (CityController) elr.getValue(elc, null, "cityController");
I think your cityModel is NULL. Is your EJB injection configured right?

Categories

Resources