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:
Related
I'm following this Struts2 tutorial to integrate the Struts2 project it proposes with hibernate:
https://www.tutorialspoint.com/struts_2/struts_hibernate.htm
I followed the instructions step by step, the only thing I changed was the libraries, since i'm using more updated libraries.
When I try to execute my action, I'm getting a NullPointerException in my DAO class. For some reason my Session object is always null.
Here is my bean class:
package com.fabioSarmiento.hibernate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student")
public class Student {
#Id
#GeneratedValue
private int id;
#Column(name="last_name")
private String lastName;
#Column(name="first_name")
private String firstName;
private int marks;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
}
Here is my DAO:
package com.fabioSarmiento.hibernate;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
public class StudentDAO {
#SessionTarget
Session session;
#TransactionTarget
Transaction transaction;
#SuppressWarnings({ "unchecked", "deprecation" })
public List<Student> getStudents() {
List<Student> students = new ArrayList<Student>();
try {
students = session.createQuery("from student").list();
} catch (Exception e) {
e.printStackTrace();
}
return students;
}
public void addStudent(Student student) {
session.save(student);
}
}
My hibernate config file:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/mydb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.fabioSarmiento.hibernate.Student" />
</session-factory>
</hibernate-configuration>
And my struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="myhibernate" extends="hibernate-default">
<action name="addStudent" method="execute"
class="com.fabioSarmiento.struts2.AddStudentAction">
<result name="success" type="redirect">
listStudents
</result>
</action>
<action name="listStudents" method="listStudents"
class="com.fabioSarmiento.struts2.AddStudentAction">
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
My web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
And this is the stack trace i'm getting:
java.lang.NullPointerException
at com.fabioSarmiento.hibernate.StudentDAO.getStudents(StudentDAO.java:21)
at com.fabioSarmiento.struts2.AddStudentAction.listStudents(AddStudentAction.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:873)
at ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1539)
at ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68)
at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethodWithDebugInfo(XWorkMethodAccessor.java:96)
at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethod(XWorkMethodAccessor.java:88)
at ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1615)
at ognl.ASTMethod.getValueBody(ASTMethod.java:91)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.Ognl.getValue(Ognl.java:467)
at ognl.Ognl.getValue(Ognl.java:431)
at com.opensymphony.xwork2.ognl.OgnlUtil$3.execute(OgnlUtil.java:351)
at com.opensymphony.xwork2.ognl.OgnlUtil.compileAndExecuteMethod(OgnlUtil.java:403)
at com.opensymphony.xwork2.ognl.OgnlUtil.callMethod(OgnlUtil.java:349)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:436)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:177)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.doIntercept(ConversionErrorInterceptor.java:139)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:133)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:192)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:88)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:248)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:99)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:139)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:105)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:253)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:155)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:120)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:174)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:171)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:195)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:193)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.factory.StrutsActionProxy.execute(StrutsActionProxy.java:54)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:564)
at org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:81)
at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:143)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Is this a good tutorial on how to make the integration?
I've been researching and there's a lot of differences in the implementations i've found. But this tutorial was very useful to learn the struts part and I didn't have any issues, and now I can't finish this lesson.
How could I resolve this issue?
Thank you for your help and patience, i'm new to hibernate and i'm trying to learn on my own.
When using createQuery, I believe the Model object class is case sensitive.
Try to change line 21 to with upper case Student:
students = session.createQuery("from Student").list();
Ok it works now!
I used the libraries that #shokulei provided (Link in his answer). After that I had to change my web.xml to use org.apache.struts2.dispatcher.FilterDispatcher as a filter class. Finally, I had to disable a parameter in MySQL to get SSL connection optional.
Thank you all for your help!!
I am trying to implement simple fileupload using Spring 4.2.3 and HTML form.
I have controller class which handles whole action, simple wrapper class for file, validator and simple view with form in HTML & Thymeleaf.
Almost everything is running fine, mapping works properly and view is appearing. But when I select file from disk and press upload button I have NullPointerException. Can anyone have a look and give some tips please? I have to mention that I am novice in Spring.
Controller:
#Controller
public class FileUploadController {
private static String UPLOAD_LOCATION = "C:/Temp/";
#Autowired
FileValidator fileValidator;
#InitBinder("file")
protected void initBinderFileBucket(WebDataBinder binder) {
binder.setValidator(fileValidator);
}
#RequestMapping(value = "/upload", method = RequestMethod.GET)
public String getSingleUploadPage(ModelMap model) {
FileBucket fileModel = new FileBucket();
model.addAttribute("fileBucket", fileModel);
return "views/fileUploader";
}
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String singleFileUpload(#Valid FileBucket file, BindingResult result, ModelMap model)
throws IOException {
if (result.hasErrors()) {
System.out.println("File Uploader validation error");
return "views/fileUploader";
} else {
System.out.println("Fetching file"); //prints out in console
MultipartFile multipartFile = file.getFile();
System.out.println(multipartFile.getName()); //NullPointer here
return "views/success";
}
}
}
File wrapper:
public class FileBucket {
private MultipartFile file;
//getters & setters + soon other stuff
}
Validator:
#Component
public class FileValidator implements Validator {
public boolean supports(Class<?> clazz) {
return FileBucket.class.isAssignableFrom(clazz);
}
public void validate(Object obj, Errors errors) {
FileBucket file = (FileBucket) obj;
if(file.getFile()!=null){
if (file.getFile().getSize() == 0) {
errors.rejectValue("file", "missingfile");
}
}
}
}
View:
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org"
layout:decorator="templates/baseTemplate">
<head>
<title>Upload Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div layout:fragment="contentPanel" class="form-container">
<h1>Simple upload</h1>
<form method="POST" enctype="multipart/form-data" action="upload" >
<input type="file" name="file" /> <br />
<input type="submit" value="Upload" />
</form>
</div>
Demo
</body>
</html>
Stacktrace:
INFO: Starting ProtocolHandler ["http-bio-8080"]
Fetching file
kwi 23, 2016 12:39:36 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [spring] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at web.controllers.FileUploadController.singleFileUpload(FileUploadController.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
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.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
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:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Okay I found out what's causing the problem.
After correcting name in #InitBinder to match argument in controller it was necessary to rename bean responsible for multipart resolving.
From:
#Bean public CommonsMultipartResolver commonsMultipartResolver() {
return new CommonsMultipartResolver();
}
To:
#Bean public CommonsMultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
Otherwise it doesn't work.
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'm working on a Java EE project using frameworks JSF 2.1, Spring 3.1.1.Release, hibernate 3.2.1. now i'm in the phase of integrating the three of them.
the build succeeded, i use tomcat server 7. but i get this exception on the the front page.
Etat HTTP 500 -
type Rapport d''exception
message
description Le serveur a rencontré une erreur interne qui l''a empêché de satisfaire la requête.
exception
javax.servlet.ServletException
javax.faces.webapp.FacesServlet.service(FacesServlet.java:422)
cause mère
java.lang.NullPointerException
controller.AnneeBean.getListeAnnees(AnneeBean.java:15)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
javax.el.BeanELResolver.getValue(BeanELResolver.java:87)
com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
org.apache.el.parser.AstValue.getValue(AstValue.java:183)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
javax.faces.component.UIData.getValue(UIData.java:731)
javax.faces.component.UIData.getDataModel(UIData.java:1798)
javax.faces.component.UIData.setRowIndexWithoutRowStatePreserved(UIData.java:484)
javax.faces.component.UIData.setRowIndex(UIData.java:473)
com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:81)
javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:820)
javax.faces.component.UIData.encodeBegin(UIData.java:1118)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1754)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:410)
note La trace complète de la cause mère de cette erreur est disponible dans les fichiers journaux de Apache Tomcat/7.0.42.
Hibernate
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/base?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<mapping resource="net/vo/Annee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernate.reveng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
<schema-selection match-catalog="base"/>
<table-filter match-name="annee"/>
</hibernate-reverse-engineering>
AnneeDao.java
package dao;
import java.util.List;
import net.vo.Annee;
public interface AnneeDao {
public List getAllAnnees();
public Annee getAnnee(Integer id);
public void insert(Annee annee);
public void update(Annee annee);
public void delete(Integer id);
}
AnneeHibernateDao.java
package dao;
import java.util.List;
import net.vo.Annee;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class AnneeHibernateDao implements AnneeDao{
private List<Annee> listeAnnees;
private Annee annee;
public void init()
{
System.out.println("Méthode d'initiation");
}
#Override
public List getAllAnnees() {
Session session=HibernateUtil.getSession();
try
{
session.beginTransaction();
listeAnnees = session.createQuery("from Annee").list();
return listeAnnees;
}
catch(HibernateException e)
{
throw e;
}
finally
{
session.close();
}
}
#Override
public Annee getAnnee(Integer id) {
Session session = HibernateUtil.getSession();
try
{
session.beginTransaction();
Query q = session.createQuery("from Annee as a where a.annee=" + id);
return (Annee) q.uniqueResult();
}
finally
{
session.close();
}
}
#Override
public void insert(Annee annee) {
Session session = HibernateUtil.getSession();
Transaction tx=null;
try
{
tx = session.beginTransaction();
session.save(annee);
tx.commit();
}
catch(RuntimeException e)
{
if(tx != null)
{
tx.rollback();
}
throw e;
}
finally
{
session.close();
}
}
#Override
public void update(Annee annee) {
Session session = HibernateUtil.getSession();
Transaction tx=null;
try
{
tx=session.beginTransaction();
session.update(annee);
tx.commit();
}
catch(RuntimeException e)
{
if(tx != null)
{
tx.rollback();
}
throw e;
}
finally
{
session.close();
}
}
#Override
public void delete(Integer id) {
Session session = HibernateUtil.getSession();
Transaction tx = null;
try
{
tx=session.beginTransaction();
annee = (Annee) session.get(Annee.class,id);
session.delete(annee);
tx.commit();
}
catch(RuntimeException e)
{
if(tx != null)
{
tx.rollback();
}
throw e;
}
finally
{
session.close();
}
}
}
HibernateUtil.java
package dao;
import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
/**
* Hibernate Utility class with a convenient method to get Session Factory
* object.
*
* #author images
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static Session getSession() {
return sessionFactory.openSession();
}
}
Pojo file
Annee.java
package net.vo;
public class Annee implements java.io.Serializable {
private int annee;
public Annee() {
}
public Annee(int annee) {
this.annee = annee;
}
public int getAnnee() {
return this.annee;
}
public void setAnnee(int annee) {
this.annee = annee;
}
}
Mapping file : Annee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 13 mai 2014 18:23:22 by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="net.vo.Annee" table="annee" catalog="base">
<id name="annee" type="int">
<column name="annee" />
<generator class="assigned" />
</id>
</class>
</hibernate-mapping>
Spring
AnneeMetier.java
package model.services;
import java.util.List;
public interface AnneeMetier {
public List getAllAnnees();
}
AnneeMetierImpl.java
package model.services;
import dao.AnneeDao;
import java.util.List;
import net.vo.Annee;
public class AnneeMetierImpl implements AnneeMetier{
private AnneeDao anneeDao;
#Override
public List getAllAnnees() {
return anneeDao.getAllAnnees();
}
public void setAnneeDao(AnneeDao anneeDao) {
this.anneeDao = anneeDao;
}
public AnneeDao getAnneeDao() {
return anneeDao;
}
}
JSF AnneeBean.java
package controller;
import java.util.List;
import model.services.AnneeMetier;
import net.vo.Annee;
public class AnneeBean {
private AnneeMetier anneeMetier;
private List<Annee> listeAnnees;
public List getListeAnnees() {
listeAnnees = anneeMetier.getAllAnnees();
return listeAnnees;
}
public void setListeAnnees(List listeAnnees) {
this.listeAnnees = listeAnnees;
}
public AnneeMetier getAnneeMetier() {
return anneeMetier;
}
public void setAnneeMetier(AnneeMetier anneeMetier) {
this.anneeMetier = anneeMetier;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>WEB-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"
xmlns:context="http://www.springframework.org/schema/context/spring-context-3.1.xsd"
xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/aop/spring-aop-3.1.xsd/spring-spring-aop-3.1.xsd-3.1.1.RELEASE.xsd
http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/context/spring-context-3.1.xsd/spring-spring-context-2.5.xsd-3.1.1.RELEASE.xsd
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/tx/spring-tx-3.1.xsd/spring-spring-tx-3.1.xsd-3.1.1.RELEASE.xsd
">
<bean id="anneeDao" class="dao.AnneeHibernateDao"></bean>
<bean id="anneeMetier" class="model.services.AnneeMetierImpl">
<property name="anneeDao" ref="anneeDao"/>
</bean>
</beans>
faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<!-- =========== FULL CONFIGURATION FILE ================================== -->
<faces-config version="2.1"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd">
<application>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
</application>
<managed-bean>
<managed-bean-name>anneeBean</managed-bean-name>
<managed-bean-class>controller.AnneeBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</faces-config>
index.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:dataTable var="annees" value="#{anneeBean.listeAnnees}">
<p:column headerText="Annee">
<h:outputText value="#{annee.annees}"/>
</p:column>
</h:dataTable>
</h:body>
</html>
please could you help me, i will appreciate it a lot
edit :
this is the stacktrace updated
mai 14, 2014 1:14:41 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/testJSF_Spring_Hibernate] threw exception [Erreur lors de linjection de ressources dans le bean géré anneeBean] with root cause
java.lang.NullPointerException
at model.services.AnneeMetierImpl.getAllAnnees(AnneeMetierImpl.java:17)
at controller.AnneeBean.init(AnneeBean.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.faces.vendor.WebContainerInjectionProvider.invokeAnnotatedMethod(WebContainerInjectionProvider.java:117)
at com.sun.faces.vendor.WebContainerInjectionProvider.invokePostConstruct(WebContainerInjectionProvider.java:99)
at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:223)
at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:105)
at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.faces.el.ChainAwareVariableResolver.resolveVariable(ChainAwareVariableResolver.java:107)
at org.springframework.web.jsf.DelegatingVariableResolver.resolveOriginal(DelegatingVariableResolver.java:123)
at org.springframework.web.jsf.DelegatingVariableResolver.resolveVariable(DelegatingVariableResolver.java:108)
at com.sun.faces.el.VariableResolverChainWrapper.getValue(VariableResolverChainWrapper.java:115)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:72)
at org.apache.el.parser.AstValue.getValue(AstValue.java:161)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIData.getValue(UIData.java:731)
at javax.faces.component.UIData.getDataModel(UIData.java:1798)
at javax.faces.component.UIData.setRowIndexWithoutRowStatePreserved(UIData.java:484)
at javax.faces.component.UIData.setRowIndex(UIData.java:473)
at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:81)
at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:820)
at javax.faces.component.UIData.encodeBegin(UIData.java:1118)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1754)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:410)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
edit 2 :
this is the AnneeBean Class
package controller;
import java.util.List;
import javax.annotation.PostConstruct;
import model.services.AnneeMetier;
import model.services.AnneeMetierImpl;
import net.vo.Annee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
#Component
#Scope("view")
public class AnneeBean {
#Autowired
private AnneeMetier anneeMetier;
private List<Annee> listeAnnees;
#PostConstruct
public void init() {
anneeMetier = new AnneeMetierImpl();
listeAnnees = anneeMetier.getAllAnnees();
}
public List getListeAnnees() {
listeAnnees = anneeMetier.getAllAnnees();
return listeAnnees;
}
public void setListeAnnees(List listeAnnees) {
this.listeAnnees = listeAnnees;
}
public AnneeMetier getAnneeMetier() {
return anneeMetier;
}
public void setAnneeMetier(AnneeMetier anneeMetier) {
this.anneeMetier = anneeMetier;
}
}
edit 3 :
index.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<p:dataTable var="listeAnnees" value="#{anneeBean.listeAnnees}">
<p:column headerText="Annee">
<h:outputText value="#{listeAnnees.annee}"/>
</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>
The naive solution for non-JSF developers would be to simply initialize the variables inside the getter to resolve the null value in the attributes. This is:
public List getListeAnnees() {
listeAnnees = getAnneeMetier().getAllAnnees();
return listeAnnees;
}
public AnneeMetier getAnneeMetier() {
if (anneeMetier == null) {
anneeMetier = new AnneeMetierImpl();
}
return anneeMetier;
}
But this may generate lot of overhead from server in case AnneeMetier#getAllAnnees() retrieves the data from database. This is explained here: Why JSF calls getters multiple times
To solve this, you do two things:
Define the right scope of your bean.
Initialize the necessary data for work using #PostConstruct annotated method.
And this would result in:
Defining the scope as #ViewScoped (explained in the link above).
Initializing listeAnnees in #PostConstruct method.
Remove any business logic from getters/setters
So the code would look like this:
#ManagedBean
#ViewScoped
public class AnneeBean {
private AnneeMetier anneeMetier;
private List<Annee> listeAnnees;
#PostConstruct
public void init() {
anneeMetier = new AnneeMetierImpl();
listeAnnees = anneeMetier.getAllAnnees();
}
public List getListeAnnees() {
return listeAnnees;
}
public void setListeAnnees(List listeAnnees) {
this.listeAnnees = listeAnnees;
}
public AnneeMetier getAnneeMetier() {
return anneeMetier;
}
public void setAnneeMetier(AnneeMetier anneeMetier) {
this.anneeMetier = anneeMetier;
}
}
BUT since you're trying to integrate JSF with Spring, you have to take into account that Spring has not yet full support of JSF 2 #ViewScoped annotation. For this case, you have/need to implement it yourself. There are plenty examples on the net about this, and looks that the most popular is from Cagatay's. In this way, you'll be able to gain power from both sides. And your bean will look like this:
#Component
#Scope("view")
public class AnneeBean {
#Autowired
private AnneeMetier anneeMetier;
private List<Annee> listeAnnees;
#PostConstruct
public void init() {
listeAnnees = anneeMetier.getAllAnnees();
}
public List getListeAnnees() {
return listeAnnees;
}
public void setListeAnnees(List listeAnnees) {
this.listeAnnees = listeAnnees;
}
}
More info:
Bean properties are shared across different sessions
Since you're learning Spring, the best bet would be to enable component scan and use annotations to configure your spring beans. Do the following:
Remove any bean configuration in applicationContext.xml.
Add this configuration to enable bean scan annotations:
<!--
These will enable component scan by annotation configuration
rather than XML configuration. One per package
-->
<context:component-scan base-package="dao" />
<context:component-scan base-package="model.services" />
Or if all your classes are inside one root package.
<!--
Assuming there's a root package for your packages like this
<context:component-scan base-package="com.myproject.dao" />
<context:component-scan base-package="com.myproject.model.services" />
-->
<context:component-scan base-package="com.myproject" />
Start configuring your Spring managed beans by annotations:
#Repository
public class AnneeHibernateDao implements AnneeDao{
//...
}
#Service
public class AnneeMetierImpl implements AnneeMetier{
#Autowired
private AnneeDao anneeDao;
//...
}
Compile your project and run it.
You are using getListeAnnees where you intend to call a method of your private object called anneeMetier, which is not initialized yet. You initialize that object through your setAnneeMetier method, which is never initialized in your code, therefore it is null. You can solve your problem by doing one of the following:
You initialize anneeMetier by calling the setAnneeMetier before you use getListeAnnees
You implement a constructor for your AnneeBean class where you initialize anneeMetier
You modify your getter (getListeAnnees) to be such as follows:
public List getListeAnnees() {
if (anneeMetier == null) {
return new ArrayList<Annee>();
}
listeAnnees = anneeMetier.getAllAnnees();
return listeAnnees;
}
EDIT: pL4GU33's comment might be useful, so I add his comment's idea to the answer:
public List getListeAnnees() {
if (anneeMetier == null) {
return Collections.emptyList();
}
listeAnnees = anneeMetier.getAllAnnees();
return listeAnnees;
}
His solution is more type-agnostic, so I upvote his comment.
I'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.