I've recently started working with the back end of Java coming from learning Ruby last year. I'm trying to do a simple "post" action saving a contact to a MySQL database. (Please forgive the newbie question).
I'm using Stripes, JPA & Hibernate. I've been following the Stripes book on setting up an environment for MVC and I'm a little stuck on the following error I was hoping someone could point me in the right direction. I know the error says I have an unhandled exception but I'm new enough, I'm not sure if this is the true cause of the error and I'm not sure if it is a Hibernate, Java or Stripes issue. I'm sure I'm missing something, I'm just not sure what. I'm posting the error along with some of my code.
Thanks for the help
Error:
Feb 19, 2013 6:13:38 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [StripesDispatcher] in context with path [] threw exception [Unhandled exception in exception handler.] with root cause
java.lang.NullPointerException
at veexterior.DAO.impl.BaseDaoImpl.save(BaseDaoImpl.java:46)
at veexterior.action.ContactActionBean.save(ContactActionBean.java:36)
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 net.sourceforge.stripes.controller.DispatcherHelper$6.intercept(DispatcherHelper.java:456)
at net.sourceforge.stripes.controller.ExecutionContext.proceed(ExecutionContext.java:158)
at net.sourceforge.stripes.controller.BeforeAfterMethodInterceptor.intercept(BeforeAfterMethodInterceptor.java:113)
at net.sourceforge.stripes.controller.ExecutionContext.proceed(ExecutionContext.java:155)
at net.sourceforge.stripes.controller.ExecutionContext.wrap(ExecutionContext.java:74)
at net.sourceforge.stripes.controller.DispatcherHelper.invokeEventHandler(DispatcherHelper.java:454)
at net.sourceforge.stripes.controller.DispatcherServlet.invokeEventHandler(DispatcherServlet.java:278)
at net.sourceforge.stripes.controller.DispatcherServlet.service(DispatcherServlet.java:160)
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 net.sourceforge.stripes.controller.StripesFilter.doFilter(StripesFilter.java:260)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
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:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
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:680)
BaseDAOImpl
package veexterior.DAO.impl;
import org.stripesstuff.stripersist.Stripersist;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import javax.persistence.NonUniqueResultException;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import java.util.List;
import veexterior.DAO.Dao;
import veexterior.models.Contact;
public abstract class BaseDaoImpl<T,ID extends Serializable>
implements Dao<T,ID>
{
private Class<T> entityClass;
#SuppressWarnings("unchecked")
public BaseDaoImpl() {
entityClass = (Class<T>)
((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
}
/* methods... */
#SuppressWarnings("unchecked")
public List<T> read() {
return Stripersist.getEntityManager()
.createQuery("from " + entityClass.getName())
.getResultList();
}
public T read(ID id) {
return Stripersist.getEntityManager().find(entityClass, id);
}
#SuppressWarnings("unchecked")
public void save(T object) {
Stripersist.getEntityManager().persist(object);
}
public void delete(T object) {
Stripersist.getEntityManager().remove(object);
}
public void commit() {
Stripersist.getEntityManager().getTransaction().commit();
}
#SuppressWarnings("unchecked")
public T findBy(String fieldName, Object value) {
Query query = Stripersist.getEntityManager()
.createQuery(getQuery(fieldName, null))
.setParameter(fieldName, value);
return getSingleResult(query);
}
private String getQuery(String fieldName, Contact contact){
String query =
"from " + entityClass.getName() + " t " +
"where t." + fieldName + " = :" + fieldName;
if (contact == null) {
return query;
}
return query + " and t.user = :user";
}
#SuppressWarnings("unchecked")
private T getSingleResult(Query query) {
try {
return (T) query.getSingleResult();
}
catch (NonUniqueResultException exc) {
return (T) query.getResultList().get(0);
}
catch (NoResultException exc) {
return null;
}
}
}
ContactActionBean
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package veexterior.action;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
//import net.sourceforge.stripes.action.SimpleMessage;
import veexterior.models.Contact;
/**
*
* #author dave
*/
public class ContactActionBean extends BaseActionBean {
private static final String FORM="/WEB-INF/contactus.jsp";
private Contact contact;
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
#DefaultHandler
public Resolution form() {/* (1) */
return new ForwardResolution(FORM);
}
public Resolution save() {
Contact contact = getContact();
contactDao.save(contact);
contactDao.commit();
return new RedirectResolution(ContactActionBean.class);
}
}
The Form being used to submit
<stripes:form beanclass="veexterior.action.ContactActionBean">
<div class="control-group">
<!-- <label class="control-label" for="inputEmail">Email</label>-->
<div class="controls">
<input type="text" id="inputEmail" placeholder="Email" name="contact.email">
</div>
</div>
<div class="control-group">
<!-- <label class="control-label" for="inputName">Name</label>-->
<div class="controls">
<input type="text" id="inputName" placeholder="Full Name" name="contact.name">
</div>
</div>
<div class="control-group">
<!-- <label class="control-label" for="inputName">Company</label>-->
<div class="controls">
<input type="text" id="inputName" placeholder="Company" name="contact.company">
</div>
</div>
<div class="control-group">
<textarea rows="5" class="input-xlarge" id="contactusmessage" name="contact.message" placeholder="Enter your message details."></textarea>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn" name="save">Send it</button>
</div>
</div>
</stripes:form>
Some of the Code from the book I've been following
package stripesbook.dao.impl.stripersist;
import org.stripesstuff.stripersist.Stripersist;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.persistence.NonUniqueResultException;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import stripesbook.dao.Dao;
import stripesbook.model.User;
public abstract class BaseDaoImpl<T,ID extends Serializable>
implements Dao<T,ID>
{
private Class<T> entityClass;
#SuppressWarnings("unchecked")
public BaseDaoImpl() {
entityClass = (Class<T>)
((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
}
/* methods... */
#SuppressWarnings("unchecked")
public List<T> read() {
return Stripersist.getEntityManager()
.createQuery("from " + entityClass.getName())
.getResultList();
}
public T read(ID id) {
return Stripersist.getEntityManager().find(entityClass, id);
}
#SuppressWarnings("unchecked")
public void save(T object) {
Stripersist.getEntityManager().persist(object);
}
public void delete(T object) {
Stripersist.getEntityManager().remove(object);
}
public void commit() {
Stripersist.getEntityManager().getTransaction().commit();
}
#SuppressWarnings("unchecked")
public T findBy(String fieldName, Object value) {
Query query = Stripersist.getEntityManager()
.createQuery(getQuery(fieldName, null))
.setParameter(fieldName, value);
return getSingleResult(query);
}
#SuppressWarnings("unchecked")
public T findBy(String fieldName, Object value, User user) {
Query query = Stripersist.getEntityManager()
.createQuery(getQuery(fieldName, user))
.setParameter(fieldName, value)
.setParameter("user", user);
return getSingleResult(query);
}
private String getQuery(String fieldName, User user){
String query =
"from " + entityClass.getName() + " t " +
"where t." + fieldName + " = :" + fieldName;
if (user == null) {
return query;
}
return query + " and t.user = :user";
}
#SuppressWarnings("unchecked")
private T getSingleResult(Query query) {
try {
return (T) query.getSingleResult();
}
catch (NonUniqueResultException exc) {
return (T) query.getResultList().get(0);
}
catch (NoResultException exc) {
return null;
}
}
}
XML File
<?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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>MyAppsNAme</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<display-name>Stripes Filter</display-name>
<filter-name>StripesFilter</filter-name>
<filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class>
<init-param>
<param-name>ActionResolver.Packages</param-name>
<param-value>veexterior</param-value>
</init-param>
<init-param>
<param-name>Extension.Packages</param-name>
<param-value>org.stripesstuff.stripersist</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>StripesFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>StripesFilter</filter-name>
<servlet-name>StripesDispatcher</servlet-name>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<servlet>
<servlet-name>StripesDispatcher</servlet-name>
<servlet-class>net.sourceforge.stripes.controller.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>StripesDispatcher</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
Persistence.xml File
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="persistence" transaction-type="RESOURCE_LOCAL">
<!-- Tell JPA to use Hibernate -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<!-- Autodetect entity classes -->
<property name="hibernate.archive.autodetection" value="class"/>
<!-- Automatically create the SQL schema -->
<property name="hibernate.hbm2ddl.auto" value="update"/>
<!-- Tell Hibernate to use MySQL -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.connection.username" value=""/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="Local MySQL Address"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<!-- Configure the connection pool -->
<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="3000"/>
</properties>
</persistence-unit>
</persistence>
Did you add the Stripersist package (org.stripesstuff.stripersist) to the Extension.Packages list in web.xml? Omitting that would account for the NPE.
Do you have a valid persistence.xml? You need it to configure the data source. In the end, it must be located in /WEB-INF/classes/META-INF/persistence.xml to correctly enable Java Persistence.
Related
I am trying to run a sample code for simple form registration using spring hibernate and jsp. However, when I try to run the code in eclipse I get the following error. Thanks for the help!
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'con' defined in class path resource [config/spring-hibernate.xml]: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:997)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:943)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at com.student.dao.StudentDaoImpl.addStudent(StudentDaoImpl.java:27)
at com.student.controller.RegisterServlet.doPost(RegisterServlet.java:57)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ExceptionInInitializerError
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 org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:76)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:990)
... 31 more
Caused by: org.hibernate.exception.SQLGrammarException: Error calling Driver#connect
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:118)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:140)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:75)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1930)
at com.student.bean.DBOperation.<clinit>(DBOperation.java:12)
... 38 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'spring'
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 com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:910)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3923)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1273)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2031)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:718)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
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 com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55)
DBOperation.java
package com.student.bean;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class DBOperation {
private static SessionFactory factory;
private Session session;
static{
factory=new Configuration().configure("config/hibernate.cfg.xml").buildSessionFactory();
}
public Session getConnection(){
if(session==null || !session.isOpen()){
session=factory.openSession();
}
return session;
}
}
Student.java
package com.student.bean;
import java.io.Serializable;
public class Student implements Serializable {
private int rollNo;
private String name;
private String address;
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
RegisterServlet.java
package com.student.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher ;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.student.bean.Student;
import com.student.dao.StudentDaoImpl;
/**
* Servlet implementation class RegisterServlet
*/
public class RegisterServlet extends HttpServlet {
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String page = request.getParameter("page");
RequestDispatcher rd = null;
if (page != null && page.equals("update")) {
String id = request.getParameter("roll");
int roll = 0;
if (id != null)
roll = Integer.parseInt(id);
String name = request.getParameter("name");
String address = request.getParameter("address");
Student student = new Student();
student.setRollNo(roll);
student.setName(name);
student.setAddress(address);
boolean flag = new StudentDaoImpl().updateStudent(student);
if (flag == true)
rd = request.getRequestDispatcher("update.jsp?status=sucess");
else
rd = request.getRequestDispatcher("update.jsp?status=fail");
} else {
String id = request.getParameter("roll");
int roll = 0;
if (id != null)
roll = Integer.parseInt(id);
String name = request.getParameter("name");
String address = request.getParameter("address");
Student student = new Student();
student.setRollNo(roll);
student.setName(name);
student.setAddress(address);
boolean flag = new StudentDaoImpl().addStudent(student);
if (flag == true)
rd = request.getRequestDispatcher("register.jsp?status=sucess");
else
rd = request.getRequestDispatcher("register.jsp?status=fail");
}
if (rd != null)
rd.forward(request, response);
}
}
StudentDao.java
package com.student.dao;
import com.student.bean.Student;
public interface StudentDao {
boolean addStudent(Student student);
boolean updateStudent(Student student);
Student viewStudent(int roll);
boolean deleteStudent(int roll);
}
StudentDaoImpl.java
package com.student.dao;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.student.bean.DBOperation;
import com.student.bean.Student;
public class StudentDaoImpl implements StudentDao {
private static Resource resource;
private static BeanFactory factory;
private Session session;
private Transaction transaction;
static{
resource=new ClassPathResource("config/spring-hibernate.xml");
factory=new XmlBeanFactory(resource);
}
public boolean addStudent(Student student) {
if(session==null || !session.isOpen())
session=((DBOperation)factory.getBean("con")).getConnection();
if(session!=null && session.isOpen()){
transaction=session.beginTransaction();
int id=(Integer)session.save(student);
if(id>0){
transaction.commit();
session.close();
return true;
}
}
return false;
}
public boolean updateStudent(Student student) {
if(session==null || !session.isOpen())
session=((DBOperation)factory.getBean("con")).getConnection();
if(session!=null && session.isOpen()){
transaction=session.beginTransaction();
Query query=session.createQuery("update Student set name=?,address=? where id=?");
query.setParameter(0, student.getName());
query.setParameter(1, student.getAddress());
query.setParameter(2, student.getRollNo());
int count=query.executeUpdate();
if(count>0){
System.out.println("student updated");
transaction.commit();
session.close();
return true;
}
}
return false;
}
public Student viewStudent(int roll) {
System.out.println("finding student :"+roll);
if(session==null || !session.isOpen())
session=((DBOperation)factory.getBean("con")).getConnection();
if(session!=null && session.isOpen()){
Student student=(Student)session.get(Student.class, roll);
if(student!=null){
System.out.println("student found");
return student;
}
}
return null;
}
public boolean deleteStudent(int roll) {
if(session==null || !session.isOpen())
session=((DBOperation)factory.getBean("con")).getConnection();
if(session!=null && session.isOpen()){
transaction=session.beginTransaction();
Query query=session.createQuery("delete from Student where id=?");
query.setParameter(0, roll);
int count=query.executeUpdate();
if(count>0){
System.out.println("student deleted");
transaction.commit();
session.close();
return true;
}
}
return false;
}
}
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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="mapping/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
student.hibernate.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="std" class="com.student.bean.Student">
<property name="rollNo" value=""></property>
<property name="name" value=""></property>
<property name="address" value=""></property>
</bean>
<bean id="con" class="com.student.bean.DBOperation">
</bean>
</beans>
register.jsp
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<table>
<tr><td colspan="4"><center>Employee</center></td></tr>
<tr><td>Register</td>
<td>View</td>
<td>Update</td>
<td>Delete</td>
</tr>
<tr><td colspan="4">
<center><br>
<%if(request.getParameter("status")!=null && request.getParameter("status").equals("sucess")){ %>
<font color="green">Student Registered successfully</font>
<%}else if(request.getParameter("status")!=null && request.getParameter("status").equals("fail")){ %>
<font color="red">Student not Registered </font>
<%} %>
<br>
<form action="Student.register" method="post">
<table>
<tr><td colspan="2"><center>Register Employee</center><br> <hr></td></tr>
<tr><td>Student Roll :</td><td><input type="text" name="roll" required="required"></td></tr>
<tr><td>Student Name :</td><td><input type="text" name="name" required="required"></td></tr>
<tr><td>Student Address :</td><td><input type="text" name="address" required="required"></td></tr>
<tr><td colspan="2"><center><input type="submit" value="Register"></center></td></tr>
</table>
</form>
</center>
</td></tr>
</table>
</center>
</body>
</html>
It is complaining that a 'spring' database doesn't exist in mysql. Perhaps you have to create it before running the sample. It comes from the line:
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring</property>
In your hibernate.cfg.xml file. If you have a database with a different name you can change it there. Perhaps the sample comes with some script that you are meant to run which creates and populates the db.
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
I am trying to configure Spring Security with hibernate but i am getting this error.
INFO: Starting Coyote HTTP/1.1 on http-8080
Sep 11, 2014 5:12:54 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet mvc-dispatcher threw exception
org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:988)
at com.mytravly.travlyweb.dao.AbstractHibernateDAO.getCurrentSession(AbstractHibernateDAO.java:52)
at com.mytravly.travlyweb.dao.AbstractHibernateDAO.findAll(AbstractHibernateDAO.java:30)
at com.mytravly.travlyweb.service.UserService.getAll(UserService.java:35)
at com.mytravly.travlyweb.controller.MainController.defaultPage(MainController.java:35)
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 org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:722)
web.xml
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>TravlyWeb</display-name>
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-database.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
spring-database.xml
<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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/travlywebdb" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="validationQuery" value="SELECT 1" />
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<array>
<value>com.mytravly.travlyweb</value>
</array>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean>
<!--
<bean id="userDao" class="com.mytravly.travlyweb.dao.UserDaoImpl">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
<bean id="myUserDetailsService" class="com.mytravly.travlyweb.service.MyUserDetailsService">
<property name="userDao" ref="userDao" />
</bean> -->
<!-- Hibernate Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- Enable #Controller annotation support -->
<mvc:annotation-driven />
<context:component-scan base-package="com.mytravly.travlyweb" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" 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.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
<!-- access denied page -->
<access-denied-handler error-page="/403" />
<form-login login-page="/login" default-target-url="/welcome"
authentication-failure-url="/login?error" username-parameter="username"
password-parameter="password" />
<logout logout-success-url="/login?logout" />
<!-- enable csrf protection -->
<csrf />
</http>
<!--
<authentication-manager>
<authentication-provider user-service-ref="myUserDetailsService">
<password-encoder hash="plaintext" />
</authentication-provider>
</authentication-manager> -->
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="myDataSource"
users-by-username-query="select username,password from user where username = ?"
authorities-by-username-query="select username,authority from authorities where username = ?" />
</authentication-provider>
</authentication-manager>
</beans:beans>
controller
package com.mytravly.travlyweb.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
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;
import com.mytravly.travlyweb.bean.User;
import com.mytravly.travlyweb.service.UserService;
#Controller
#Transactional(propagation = Propagation.REQUIRES_NEW)
public class MainController {
#Autowired
UserService service;
#RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
public ModelAndView defaultPage() {
List<User> list = service.getAll();
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security + Hibernate Example");
model.addObject("message", list.get(0).getUsername());
model.setViewName("hello");
return model;
}
#RequestMapping(value = "/admin**", method = RequestMethod.GET)
public ModelAndView adminPage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security + Hibernate Example");
model.addObject("message", "This page is for ROLE_ADMIN only!");
model.setViewName("admin");
return model;
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "logout", required = false) String logout, HttpServletRequest request) {
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", getErrorMessage(request, "SPRING_SECURITY_LAST_EXCEPTION"));
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("login");
return model;
}
// customize the error message
private String getErrorMessage(HttpServletRequest request, String key) {
Exception exception = (Exception) request.getSession().getAttribute(key);
String error = "";
if (exception instanceof BadCredentialsException) {
error = "Invalid username and password!";
} else if (exception instanceof LockedException) {
error = exception.getMessage();
} else {
error = "Invalid username and password!";
}
return error;
}
// for 403 access denied page
#RequestMapping(value = "/403", method = RequestMethod.GET)
public ModelAndView accesssDenied() {
ModelAndView model = new ModelAndView();
// check if user is login
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
UserDetails userDetail = (UserDetails) auth.getPrincipal();
System.out.println(userDetail);
model.addObject("username", userDetail.getUsername());
}
model.setViewName("403");
return model;
}
/*#Autowired
UserService userService;
#Autowired
TestBl bl;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model) {
return "signin";
}
#RequestMapping(value = "/signup", method = RequestMethod.GET)
public String signup(Model model) {
return "signup";
}
#RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public String dashboard(Model model) {
return "blank";
}*/
}
Service
package com.mytravly.travlyweb.service;
import java.io.Serializable;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.mytravly.travlyweb.bean.User;
import com.mytravly.travlyweb.dao.AbstractHibernateDAO;
import com.mytravly.travlyweb.dao.IGenericDAO;
#Service
#Transactional(propagation = Propagation.MANDATORY)
public class UserService {
public UserService() {
// TODO Auto-generated constructor stub
}
AbstractHibernateDAO<User> dao;
#Autowired
public void setDao(final AbstractHibernateDAO<User> userDao) {
dao = userDao;
dao.setClazz(User.class);
}
public List<User> getAll()
{
return dao.findAll();
}
}
AbstractHibernateDAO
package com.mytravly.travlyweb.dao;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class AbstractHibernateDAO<T extends Serializable> {
private Class<T> clazz;
#Autowired
SessionFactory sessionFactory;
public void setClazz(final Class<T> clazzToSet) {
clazz = clazzToSet;
}
public T getById(final Long id) {
return (T) getCurrentSession().get(clazz, id);
}
public List<T> findAll() {
return getCurrentSession().createQuery("from " + clazz.getName())
.list();
}
public void save(final T entity) {
getCurrentSession().persist(entity);
}
public void update(final T entity) {
getCurrentSession().merge(entity);
}
public void delete(final T entity) {
getCurrentSession().delete(entity);
}
public void deleteById(final Long entityId) {
final T entity = getById(entityId);
delete(entity);
}
protected Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
}
The error is letting you know that there is no open transaction when you are calling you DAO method and hitting the database. That means that the transaction management of the UserService is wrong.
I would try to change the transaction management of the UserService to create a transaction if there isn't already an existing:
#Service
#Transactional(propagation = **Propagation.REQUIRED**)
public class UserService {
If this works, the problem could be with the constructing of the spring xmls.
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.