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?
Related
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?
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.
I did some coding : converter, dropdown list, List, ...
I get a NullPointerException though I am sure that ALL USED OBJECT have been initialized.
Below are the new edited beens ans jsf (the converter is in the Fil_M_B bean and M_B stands for Managed Bean)
Could you please help me figure out whats going wrong now ?
Fil_M_B bean
#Named(value = "fil_M_B")
#SessionScoped
public class Fil_M_B implements Serializable {
#EJB
private FiliereFacadeLocal filiereFacade;
public FiliereFacadeLocal getFiliereFacade() {
return filiereFacade;
}
private List<Filiere> list_fil;
public List<Filiere> getList_fil() {
return list_fil;
}
#PostConstruct
public void list(){
list_fil = filiereFacade.findAll();
}
// NOW THE CONVERTER
#FacesConverter(forClass = Filiere.class)
public static class FiliereControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
Fil_M_B controller = (Fil_M_B) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "Fil_M_B");
return controller.filiereFacade.find(getKey(value));
}
java.lang.String getKey(String value) {
java.lang.String key;
key = value;
return key;
}
String getStringKey(java.lang.String value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Filiere) {
Filiere o = (Filiere) object;
return getStringKey(o.getNomFiliere());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Filiere.class.getName());
}
}
}
/**
* Creates a new instance of Fil_M_B
*/
public Fil_M_B() {
}
Spec_M_B
#Named(value = "spec_M_B")
#SessionScoped
public class Spec_M_B implements Serializable{
#EJB
private SpecialiteFacadeLocal specialiteFacade;
Specialite spec = new Specialite();
public Specialite getSpec() {
return spec;
}
public void setSpec(Specialite spec) {
this.spec = spec;
}
public void ADD(){
specialiteFacade.create(spec);
}
/**
* Creates a new instance of Spec_M_B
*/
public Spec_M_B() {
}
}
Jsf page
<f:view>
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="Specialite" for="nomSpec" />
<h:inputText id="nomSpec" value="#{spec_M_B.spec.nomSpec}" title="Nom Specialite" required="true" requiredMessage="Required!"/>
<h:outputLabel value="Filiere" for="nomFiliere" />
<h:selectOneMenu id="nomFiliere" value="#{spec_M_B.spec.nomFiliere}" title="Nom Filiere" required="true" requiredMessage="Required !">
<f:selectItems value="#{fil_M_B.list_fil}"/>
</h:selectOneMenu>
</h:panelGrid>
<h:commandButton value="ADD" action="#{spec_M_B.ADD()}"/>
</h:form>
</f:view>
Could you please help me figure out whats going wrong ?
Stack trace Below is the stack trace I I see in my browser afetr clicking the ADD button
java.lang.NullPointerException
at TEST_3.Fil_M_B.access$000(Fil_M_B.java:27)
at TEST_3.Fil_M_B$FiliereControllerConverter.getAsObject(Fil_M_B.java:59)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:171)
at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectOneValue(MenuRenderer.java:201)
at com.sun.faces.renderkit.html_basic.MenuRenderer.getConvertedValue(MenuRenderer.java:318)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1045)
at javax.faces.component.UIInput.validate(UIInput.java:975)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1248)
at javax.faces.component.UIInput.processValidators(UIInput.java:712)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIForm.processValidators(UIForm.java:253)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1195)
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:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
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:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
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:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
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:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
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:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
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.
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();
}
}
}