I'm following this Struts2 tutorial to integrate the Struts2 project it proposes with hibernate:
https://www.tutorialspoint.com/struts_2/struts_hibernate.htm
I followed the instructions step by step, the only thing I changed was the libraries, since i'm using more updated libraries.
When I try to execute my action, I'm getting a NullPointerException in my DAO class. For some reason my Session object is always null.
Here is my bean class:
package com.fabioSarmiento.hibernate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student")
public class Student {
#Id
#GeneratedValue
private int id;
#Column(name="last_name")
private String lastName;
#Column(name="first_name")
private String firstName;
private int marks;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
}
Here is my DAO:
package com.fabioSarmiento.hibernate;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
public class StudentDAO {
#SessionTarget
Session session;
#TransactionTarget
Transaction transaction;
#SuppressWarnings({ "unchecked", "deprecation" })
public List<Student> getStudents() {
List<Student> students = new ArrayList<Student>();
try {
students = session.createQuery("from student").list();
} catch (Exception e) {
e.printStackTrace();
}
return students;
}
public void addStudent(Student student) {
session.save(student);
}
}
My hibernate config file:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/mydb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<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.fabioSarmiento.hibernate.Student" />
</session-factory>
</hibernate-configuration>
And my struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="myhibernate" extends="hibernate-default">
<action name="addStudent" method="execute"
class="com.fabioSarmiento.struts2.AddStudentAction">
<result name="success" type="redirect">
listStudents
</result>
</action>
<action name="listStudents" method="listStudents"
class="com.fabioSarmiento.struts2.AddStudentAction">
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
My web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
And this is the stack trace i'm getting:
java.lang.NullPointerException
at com.fabioSarmiento.hibernate.StudentDAO.getStudents(StudentDAO.java:21)
at com.fabioSarmiento.struts2.AddStudentAction.listStudents(AddStudentAction.java:29)
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:497)
at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:873)
at ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1539)
at ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68)
at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethodWithDebugInfo(XWorkMethodAccessor.java:96)
at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethod(XWorkMethodAccessor.java:88)
at ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1615)
at ognl.ASTMethod.getValueBody(ASTMethod.java:91)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.Ognl.getValue(Ognl.java:467)
at ognl.Ognl.getValue(Ognl.java:431)
at com.opensymphony.xwork2.ognl.OgnlUtil$3.execute(OgnlUtil.java:351)
at com.opensymphony.xwork2.ognl.OgnlUtil.compileAndExecuteMethod(OgnlUtil.java:403)
at com.opensymphony.xwork2.ognl.OgnlUtil.callMethod(OgnlUtil.java:349)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:436)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:177)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.doIntercept(ConversionErrorInterceptor.java:139)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:133)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:192)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:88)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:248)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:99)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:139)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:105)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:253)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:155)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:120)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:174)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:171)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:195)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:193)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.factory.StrutsActionProxy.execute(StrutsActionProxy.java:54)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:564)
at org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:81)
at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:143)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Is this a good tutorial on how to make the integration?
I've been researching and there's a lot of differences in the implementations i've found. But this tutorial was very useful to learn the struts part and I didn't have any issues, and now I can't finish this lesson.
How could I resolve this issue?
Thank you for your help and patience, i'm new to hibernate and i'm trying to learn on my own.
When using createQuery, I believe the Model object class is case sensitive.
Try to change line 21 to with upper case Student:
students = session.createQuery("from Student").list();
Ok it works now!
I used the libraries that #shokulei provided (Link in his answer). After that I had to change my web.xml to use org.apache.struts2.dispatcher.FilterDispatcher as a filter class. Finally, I had to disable a parameter in MySQL to get SSL connection optional.
Thank you all for your help!!
Related
I'm trying to develop a simple web application using Spring and Hibernate JPA on Glassfish 4.1.1 server.
I have an entity class:
package entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "USERS")
public class User {
#Id
#GeneratedValue
#Column(name = "ID")
private long id;
private String firstName;
private String lastName;
private String email;
private String login;
private String password;
public User() {
}
public User(long id, String firstName, String lastName, String email, String login, String password) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.login = login;
this.password = password;
}
getters and setters...
}
Then controller class:
package controller;
import ...
#Controller
public class LoginController {
#Autowired
private UserService userService;
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView executeLogin(HttpServletRequest request, HttpServletResponse response, #ModelAttribute("user") User user) {
userService.addUser(new User(20, "a", "b", "dgsd", "sfadf", "sdfsdf"));
}
}
UserService:
package service;
import dao.UserDao;
import entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class UserService {
#Autowired
UserDao userDao;
public void addUser(User user) {
userDao.insert(user);
}
}
UserDao:
package dao;
import entity.User;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
#Repository("userDao")
public class UserDao {
#PersistenceContext
private EntityManager entityManager;
public void insert(User user) {
entityManager.persist(user);
}
}
This is my persistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="LibraryPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:app/library</jta-data-source>
</persistence-unit>
</persistence>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
dispatcher-servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<context:component-scan base-package="service, controller, dao" />
</beans>
When I'm trying to deploy the app, I've got a lot of exceptions. First is:
Warning: Exception while dispatching an event
java.lang.NullPointerException
at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.getStatus(JtaStatusHelper.java:76)
at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.isActive(JtaStatusHelper.java:118)
at org.hibernate.engine.transaction.internal.jta.CMTTransaction.join(CMTTransaction.java:149)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.joinTransaction(AbstractEntityManagerImpl.java:1602)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.postInit(AbstractEntityManagerImpl.java:210)
at org.hibernate.jpa.internal.EntityManagerImpl.<init>(EntityManagerImpl.java:91)
at org.hibernate.jpa.internal.EntityManagerFactoryImpl.internalCreateEntityManager(EntityManagerFactoryImpl.java:345)
at org.hibernate.jpa.internal.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:313)
at org.glassfish.persistence.jpa.JPADeployer$2.visitPUD(JPADeployer.java:451)
at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:510)
at org.glassfish.persistence.jpa.JPADeployer.iterateInitializedPUsAtApplicationPrepare(JPADeployer.java:492)
at org.glassfish.persistence.jpa.JPADeployer.event(JPADeployer.java:398)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:131)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:487)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
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)
What am I doing wrong? Thanks for helping!
Your code attempts to create a JTA-capable entity-manager, because you configured your persistence unit to be JTA-enabled:
<persistence-unit name="LibraryPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:app/library</jta-data-source>
</persistence-unit>
But JTA-capable EMs are normally not to be created by webapps.
If you are really aiming for a simple webapp, you should most likely go for a simple persistence-unit. If you follow the link above (Chapter: Valid RESOURCE_LOCAL Unit usage) you will see what is the difference. A simple configuration could look like this for example:
<persistence>
<persistence-unit name="manager1" transaction-type="RESOURCE_LOCAL">
<class>org.hibernate.ejb.test.Cat</class>
<class>org.hibernate.ejb.test.Distributor</class>
<class>org.hibernate.ejb.test.Item</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:."/>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/
<property name="hibernate.max_fetch_depth" value="3"/>
<!-- cache configuration -->
<property name="hibernate.ejb.classcache.org.hibernate.ejb.test.Item" value="read-write"/>
<property name="hibernate.ejb.collectioncache.org.hibernate.ejb.test.Item.distributors" value="read-write, RegionName"/>
<!-- alternatively to <class> and <property> declarations, you can use a regular hibernate.cfg.xml file -->
<!-- property name="hibernate.ejb.cfgfile" value="/org/hibernate/ejb/test/hibernate.cfg.xml"/ -->
</properties>
</persistence-unit>
</persistence>
I am beginner in spring mvc, I want to create simple example but I am getting exception im my service layer here is the exception
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/haybet] threw exception `enter code here`[Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at org.proffart.bet.controller.BetController.registerUser(BetController.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:177)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:446)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:434)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
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: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(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I am getting exception when clicking on register button in register.jsp, I guess that the problem is with hibernate and mysql connection, please help me to find the problem.
Here are my files
Controller
package org.proffart.bet.controller;
import java.io.IOException;
import javax.validation.Valid;
import org.proffart.bet.domain.User;
import org.proffart.bet.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class BetController {
UserService service;
//private static final Logger log = Logger.getLogger(BetController.class);
#RequestMapping(value="register", method = RequestMethod.GET)
public String showRegisterForm(ModelMap model){
User user = new User();
model.addAttribute("user",user );
return "register";
}
#RequestMapping(value="/register", method = RequestMethod.POST)
public String registerUser(#Valid User user, BindingResult result,
ModelMap model){
System.out.println(user.getNickName());
System.out.println(user.getNickName());
System.out.println(user);
user.setBalance((double) 1);
user.setEmail("aaa");
user.setId(1);
if (result.hasErrors()){
return "register";
}
service.saveUser(user);
return "success";
}
}
DAO classes
package org.proffart.bet.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class AbstractDAO {
#Autowired
private SessionFactory sessionFactory;
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
public void persist(Object entity) {
getSession().persist(entity);
}
}
UserDao class
package org.proffart.bet.dao;
import java.util.List;
import org.proffart.bet.domain.User;
public interface UserDAO {
public void addUser(User user);
public void deleteUser(Integer id);
public List<User> getUsers();
}
UserDAOImpl
package org.proffart.bet.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.proffart.bet.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class UserDAOImpl extends AbstractDAO implements UserDAO{
#Autowired
private SessionFactory sessionFactory;
public void addUser(User user) {
persist(user);
}
public void deleteUser(Integer id) {
}
public List<User> getUsers() {
}
}
Service classes
UserService
package org.proffart.bet.service;
import javax.transaction.Transactional;
import org.proffart.bet.dao.UserDAO;
import org.proffart.bet.dao.UserDAOImpl;
import org.proffart.bet.domain.User;
#Transactional
public class UserService {
UserDAO dao;
public void saveUser(User user){
dao.addUser(user);
}
}
Doamin layer
User
package org.proffart.bet.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="users")
public class User {
#Id
#Column(name="id")
#GeneratedValue
private Integer id;
#Column(name="nic_name")
private String nickName;
#Column(name="email")
private String email;
#Column(name="password")
private String password;
#Column(name="balance")
private Double balance;
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getNickName(){
return nickName;
}
public void setNickName(String nickName){
this.nickName = nickName;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password = password;
}
public Double getBalance(){
return balance;
}
public void setBalance(Double balance){
this.balance = balance;
}
public Integer getId(){
return id;
}
public void setId(int id){
this.id = id;
}
}
Reguister.jsp
<%# page session="true" %>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page isELIgnored="false" %>
<html>
<head>
</head>
<body>
<h3>Welcome To Virtual bettings</h3>
<form:form method="POST" modelAttribute="user">
<table>
<tr>
<td><label for="nickName">Login: </label> </td>
<td><form:input path="nickName" id="nickName"/></td>
</tr>
<tr>
<td><label for="password">Password: </label> </td>
<td><form:input path="password" id="password"/></td>
</tr>
<tr>
<td><input type="submit" value="register"/></td>
</tr>
</table>
</form:form>
</body>
</html>
And finally config files in xml
web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml /WEB-INF/hibernateDataAccessContext.xml</param- value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
hibernateDataAccessContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<!-- Auto-detect DAOs -->
<context:component-scan base-package="org.proffart.bet.dao"/>
<context:property-placeholder location="WEB-INF/jdbc.properties"/>
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"
p:maxActive="${dbcp.maxActive}"
p:maxIdle="${dbcp.maxIdle}"
p:maxWait="${dbcp.maxWait}"/>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configurationClass="org.hibernate.cfg.AnnotationConfiguration"
p:packagesToScan="org.proffart.bet.domain">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
</props>
</property>
<property name="eventListeners">
<map>
<entry key="merge">
<bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/>
</entry>
</map>
</property>
</bean>
<!-- Allow declarative transaction management using the #Transactional annotation -->
<tx:annotation-driven transaction-manager="txnManager"/>
<!-- Transaction manager for the Hibernate SessionFactory -->
<bean id="txnManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
<!-- Apply persistence exception translation on #Repository classes -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>
And dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="org.proffart.bet.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
jdbc.properties
hibernate.generate_statistics=true
hibernate.show_sql=true
jpa.showSql=true
hibernate.dialect=org.hibernate.dialect.HSQLDialect
jpa.databasePlatform=org.springframework.samples.petclinic.toplink.EssentialsHSQLPlatformWithNativeSequence
jpa.database=HSQL
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/bet
jdbc.username=root
jdbc.password=
Your exception shows a NullPointerException on line 47 of BetController. However there is nothing at this line in the class you posted. My guess is that your UserService is not injected in your controller. Add the #Autowired annotation:
#Controller
public class BetController {
#Autowired
UserService service;
I think you miss autowire Userservice object in to controller layer
Please add #autowire top of Userservice object It will sovles your problem.
#Autowire
UserService service;
If its give any problem just google how to autowire service object,
Also you have done one mistake while creating service object you need to create Userservice as Interface and one concert implementation of Userservice like UserServiceImpl
Thanks,
Himanshu
Put #Service annotation on UserService class,and #Autowired on the below line in BetController class.
#Autowired
UserService service;
And i see you setted component scanning to controller package only,how ever you need to set it to below.
<context:component-scan base-package="org.proffart.bet.*"/>
This is the best example for Spring mvc crud operation using JQuery Ajax. You may find maven as well in this.
Site: Spring MVC With Hibernate CRUD
Or You may visit YouTube Channel: Spring MVC with Hibernate CRUD VIDEO
Im trying to implement a struts 2 and hibernate login application following this tutorial:
Link to the tutorial
When I push login bottton I have an exeption :
GRAVE: Servlet.service() for servlet [default] in context with path [/Test] threw exception [L''exécution du filtre (Filter) a lancé une exception] with root cause
java.lang.ClassNotFoundException: org.jboss.logging.BasicLogger
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2918)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1174)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1669)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:192)
at org.aymen.slimi.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:10)
at org.aymen.slimi.util.HibernateUtil.<clinit>(HibernateUtil.java:5)
at org.aymen.slimi.utilisateur.UserAction.<init>(UserAction.java:22)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:151)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:182)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:171)
at com.opensymphony.xwork2.factory.DefaultActionFactory.buildAction(DefaultActionFactory.java:22)
at com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:141)
at com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:297)
at com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:397)
at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:194)
at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:37)
at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:552)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
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: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:100)
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:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
mai 04, 2014 6:26:37 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [default] in context with path [/Test] threw exception [L''exécution du filtre (Filter) a lancé une exception] with root cause
java.lang.NoClassDefFoundError: Could not initialize class org.aymen.slimi.utilisateur.UserService
at org.aymen.slimi.utilisateur.UserAction.<init>(UserAction.java:22)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:151)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:182)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:171)
at com.opensymphony.xwork2.factory.DefaultActionFactory.buildAction(DefaultActionFactory.java:22)
at com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:141)
at com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:297)
at com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:397)
at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:194)
at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:37)
at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:552)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
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: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:100)
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:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
The index.jsp:
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="sj" uri="/struts-jquery-tags" %>
<%# taglib prefix="sb" uri="/struts-bootstrap-tags" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Struts2 Bootstrap Plugin Showcase - <s:text name="showcase.version"/> - Client Validation</title>
<meta charset="utf-8"/>
<meta name="keywords" content="struts2, twitter, bootstrap, plugin, showcase" />
<meta name="description" content="A Showcase for the Struts2 Bootstrap Plugin" />
<!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<sj:head jqueryui="false"/>
<sb:head includeScripts="true" includeScriptsValidation="true"/>
<style type="text/css">
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<a class="brand" href="#" style="margin-left:-2px" >Welcome to Aymen Slimi Server</a>
<!--/.nav-collapse -->
</div>
</div>
The User.java:
package org.aymen.slimi.utilisateur;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="user")
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1020834391383853442L;
private String userId;
private String password;
private String firtName;
private String lastName;
#Id
#Column(name="user_name")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Column(name="user_password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name="first_name")
public String getFirtName() {
return firtName;
}
public void setFirtName(String firtName) {
this.firtName = firtName;
}
#Column(name="last_name")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
The UserService.java:
package org.aymen.slimi.utilisateur;
import java.util.ArrayList;
import java.util.List;
import org.aymen.slimi.util.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
public class UserService extends HibernateUtil{
public boolean verifyAccess(User user) {
User userDB = this.getUser(user.getUserId());
if (userDB!=null){
if(user.getUserId().equals(userDB.getUserId()) && user.getPassword().equals(userDB.getPassword())) {
return true;
}
}
return false;
}
public User add(User user) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
return user;
}
public User delete(String username) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
User user = (User) session.load(User.class, username);
if(null != user) {
session.delete(user);
}
session.getTransaction().commit();
return user;
}
public User getUser(String username){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
User user = null;
Query query = session
.createQuery("select * from user where username = :username");
query.setString("username", username);
user = (User) query.uniqueResult();
return user;
}
#SuppressWarnings("unchecked")
public List<User> list() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<User> user = null;
try {
user = ((List<User>)session.createQuery("from user").list());
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
if(user != null) {
return user;
}
return new ArrayList<User>();
}
}
The struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation"
value="false" />
<!--constant name="struts.devMode" value="false" /-->
<!--constant name="struts.custom.i18n.resources"
value="resources" /-->
<include file="struts-login.xml"></include>
<!--include file="struts-security.xml"></include-->
<package name="default" namespace="/" extends="struts-default" >
<action name="/*">
<result>/WEB-INF/jsp/index.jsp</result>
</action>
</package>
</struts>
The struts-login.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="login" namespace="/" extends="struts-default" >
<interceptors>
<interceptor name="login" class="org.aymen.slimi.utilisateur.LoginInterceptor"></interceptor>
<interceptor-stack name="loggingStack">
<interceptor-ref name="login" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<action name="login" class="org.aymen.slimi.utilisateur.UserAction" method="verifyLogin">
<result name="success">/WEB-INF/jsp/main.jsp</result>
<result name="input">/WEB-INF/jsp/index.jsp</result>
</action>
</package>
</struts>
The HibernateUtil.java:
package org.aymen.slimi.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
The web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts2 Application</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
The list of jar:
Add the JBoss Logging jar to your classpath. If you use Maven, it will add this and any other required jars to the classpath
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>
The solution was changing the HibernateUtil.java:
import org.hibernate.*;
import org.hibernate.cfg.*;
#SuppressWarnings("deprecation")
public class HibernateUtil {
public static final SessionFactory sessionFactory;
static {
try {
// Création de la SessionFactory à partir de hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
} 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);
}
}
#SuppressWarnings("rawtypes")
public static final ThreadLocal session = new ThreadLocal();
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
And the jar liste is:
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.
I need to initialize hibernate session in Filter for spring mvc, I know I need to add ContextListner in web.xml but I have no Idea of what to write in applicationContext.xml file.please guide to some tutorial or example ...
detailed explaination: I need to prepopulate my form using spring form tag, for that I need HibernateSession open in jsp lifecycle execution. I created a HibernateSessionFilter to enable hibernate session in jsp. Now again for that I need to initialize my hibernate session. see the
sf = //don't know what to write ;
in code below. I dont know how I can get hibernate sessionFactory there. I know it can be done via applicationContext.xml but can't get to the exact configuration needed.
edit1*****
now again back to same exception where I started:
org.springframework.beans.InvalidPropertyException: Invalid property 'firstname' of bean class [net.viralpatel.contact.form.Contact_$$_javassist_0]: Getter for property 'firstname' threw exception; nested exception is java.lang.reflect.InvocationTargetException
at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:845)
at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:721)
at org.springframework.validation.AbstractPropertyBindingResult.getActualFieldValue(AbstractPropertyBindingResult.java:99)
at org.springframework.validation.AbstractBindingResult.getFieldValue(AbstractBindingResult.java:219)
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:120)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:178)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:198)
at org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
at org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
at org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:89)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
at org.apache.jsp.WEB_002dINF.jsp.contact_005fedit_jsp._jspx_meth_form_005flabel_005f0(contact_005fedit_jsp.java:255)
at org.apache.jsp.WEB_002dINF.jsp.contact_005fedit_jsp._jspx_meth_form_005fform_005f0(contact_005fedit_jsp.java:177)
at org.apache.jsp.WEB_002dINF.jsp.contact_005fedit_jsp._jspService(contact_005fedit_jsp.java:126)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
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.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:262)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1180)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:950)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
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:224)
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:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:761)
... 55 more
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:167)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:215)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
at net.viralpatel.contact.form.Contact_$$_javassist_0.getFirstname(Contact_$$_javassist_0.java)
... 60 more
Sep 16, 2012 4:36:12 PM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet jsp threw exception
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:167)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:215)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
at net.viralpatel.contact.form.Contact_$$_javassist_0.getFirstname(Contact_$$_javassist_0.java)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:761)
at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:721)
at org.springframework.validation.AbstractPropertyBindingResult.getActualFieldValue(AbstractPropertyBindingResult.java:99)
at org.springframework.validation.AbstractBindingResult.getFieldValue(AbstractBindingResult.java:219)
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:120)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:178)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:198)
at org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
at org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
at org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:89)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
at org.apache.jsp.WEB_002dINF.jsp.contact_005fedit_jsp._jspx_meth_form_005flabel_005f0(contact_005fedit_jsp.java:255)
at org.apache.jsp.WEB_002dINF.jsp.contact_005fedit_jsp._jspx_meth_form_005fform_005f0(contact_005fedit_jsp.java:177)
at org.apache.jsp.WEB_002dINF.jsp.contact_005fedit_jsp._jspService(contact_005fedit_jsp.java:126)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
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.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:262)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1180)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:950)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
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:224)
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:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Sep 16, 2012 4:36:12 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [spring] in context with path [/Spring3HibernateMaven] threw exception [org.springframework.beans.InvalidPropertyException: Invalid property 'firstname' of bean class [net.viralpatel.contact.form.Contact_$$_javassist_0]: Getter for property 'firstname' threw exception; nested exception is java.lang.reflect.InvocationTargetException] with root cause
my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3-Hibernate</display-name>
<welcome-file-list>
<welcome-file>list.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
my Contact Class:
package net.viralpatel.contact.form;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="CONTACTS")
public class Contact {
#Id
#Column(name="ID")
#GeneratedValue
private Integer id;
#Column(name="FIRSTNAME")
private String firstname;
#Column(name="LASTNAME")
private String lastname;
#Column(name="EMAIL")
private String email;
#Column(name="TELEPHONE")
private String telephone;
public String getEmail() {
return email;
}
public String getTelephone() {
return telephone;
}
public void setEmail(String email) {
this.email = email;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
My Application filter:
private static Log log = LogFactory.getLog(HibernateSessionRequestFilter.class);
private SessionFactory sf;
public void init(FilterConfig filterConfig) throws ServletException {
log.debug("Initializing filter...");
sf = //don't know what to write ;
}
}
My ContactDAO
#Repository
public class ContactDAOImpl implements ContactDAO {
#Autowired
private SessionFactory sessionFactory;
public void addContact(Contact contact) {
sessionFactory.getCurrentSession().save(contact);
}
public List<Contact> listContact() {
return sessionFactory.getCurrentSession().createQuery("from Contact")
.list();
}
public void removeContact(Integer id) {
Contact contact = (Contact) sessionFactory.getCurrentSession().load(
Contact.class, id);
if (null != contact) {
sessionFactory.getCurrentSession().delete(contact);
}
}
public Contact editContact(Integer id) {
Contact contact = (Contact) sessionFactory.getCurrentSession().load(
Contact.class, id);
System.out.println("contact: "+contact);
if (null != contact) {
sessionFactory.getCurrentSession().update(contact);
}
return contact;
}
public Contact getContact(Integer id) {
Contact contact = (Contact) sessionFactory.getCurrentSession().load(
Contact.class, id);
return contact;
}
}
Controller render method for edit page:
#RequestMapping(value = "/edit/{contactId}", method = RequestMethod.GET)
public ModelAndView edit(#PathVariable("contactId") Integer contactId,
HttpServletRequest request) {
Contact contact = contactService.getContact(contactId);
Map<String, Object> model = new HashedMap();
model.put("contact", contact);
return new ModelAndView("contact_edit", model);
}
#RequestMapping(value = "/doedit/{contactId}", method = RequestMethod.POST)
public String editContact(#PathVariable("contactId") Integer contactId) {
contactService.editContact(contactId);
return "redirect:/index";
}
I have found one major bug in your code and one minor.
The major bug is that you have configured TWO Hibernate Session Factories (this cases the stange exception) on in applicationContext.xml (correct) and on in spring-servlet.xml (this must be removed). (some more details as comment in the xml)
The updated spring-servlet.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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="net.viralpatel.contact" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<!--
Already defined in the inner spring context, you do not need it twice
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
-->
<!--
ONLY one session factory per application!!
You have configured them already in applicationContext.xml
Spring mvc application have two spring contexts, an other and an inner context.
The inner context is created by ContextLoaderListener and in your case it is described in applicationContext.xml.
The outer context is created by DispatcherServelet and in your case it is described in spring-servlet.xml.
Filters can access only the inner context, therefore the OpenSessionInViewFilter requires that the inner context contain all the hibernate stuff
The outer context can beans access the inner context.
The outer context has access to all the web stuff (not like the inner context) therefore the #Controller Beans can be only instanceated in the outer context.
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
-->
<tx:annotation-driven />
<!-- JSR-303 support will be detected on classpath and enabled automatically -->
<mvc:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
The minor bug ins in your contact_edit.jsp
Instead of <form:form method="post" action="add.html" commandName="contact"> use:
<c:url var="updateUrl" value="/doedit/${contact.id}"/>
<form:form method="post" action="${updateUrl}" commandName="contact">
And after this modification of your editContact I was able to modify the first name
/**
* This is only prove that it works.
* You should not update the contact directly in the controller (this is only a shortcut in for the example).
* If you load and update the contact in an method that is #Transactional, than you can remove the #Transactional from this
* controller method.
*/
#Transactional
#RequestMapping(value = "/doedit/{contactId}", method = RequestMethod.POST)
public String editContact(#PathVariable("contactId") final Integer contactId, final Contact editedContact) {
//contactService.editContact(contactId);
Contact contact = contactService.getContact(contactId);
contact.setFirstname(editedContact.getFirstname()); //only first name for the example
return "redirect:/index";
}