This question already has an answer here:
javax.naming.NameNotFoundException: Name [servlet.TestEJB/meuEJB] is not bound in this Context. Unable to find [servlet.TestEJB]
(1 answer)
Closed 7 years ago.
Making a program that saves users a database I get the following error.
The program begins with a index.html, wherein there is a button qual to which tightens it goes to addUser servlet that executes the method.
Error:
SEVERE: Servlet.service() for servlet [servlet.TestEJB] in context with path [/activitat] threw exception
java.lang.NullPointerException
at servlet.TestEJB.doPost(TestEJB.java:40)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1517)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1474)
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)
Servlet:
#WebServlet("/TestEJB")
public class TestEJB extends HttpServlet{
private static final long serialVersionUID = 1L;
MissatgesEJB meuEJB;
/* (non-Javadoc)
* #see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = resp.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet TestEJB</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Proves Whatsapp</h1>");
Usuaris usuari = new Usuaris("robert_1994", "Paucasals33", "Bruch");
out.println("Insertant Usuari... " + meuEJB.insertarUsuari(usuari) + "<br/>");
out.println("</body>");
out.println("</html>");
}
}
}
Method:
public class MissatgesEJB {
#PersistenceUnit
EntityManagerFactory emf;
public String insertarUsuari(Usuaris u) {
EntityManager em = emf.createEntityManager();
try {
// Excriu a la BD.
em.persist(u);
// Forçem a que escrigui ara ala BD.
em.flush();
return "ok";
} catch (Exception ex) {
return ex.getMessage();
} finally {
em.close();
}
}
}
Persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="JPA-1" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>beans.Historial</class>
<class>beans.Missatges</class>
<class>beans.Usuaris</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/bdwhatsapp" />
<property name="javax.persistence.jdbc.user" value="marti" />
<property name="javax.persistence.jdbc.password" value="Paucasals33" />
<property name="javax.persistence.schema-generation.database.action"
value="none" />
</properties>
</persistence-unit>
</persistence>
In your servlet, you need to initialize or inject somehow meuEJB. Since you didn't initialized it, you are getting NullPointerException while executing below line:
out.println("Insertant Usuari... " + meuEJB.insertarUsuari(usuari) + "<br/>");
Object meuEJB of type MissatgesEJB is not initialized and you are trying to call insertarUsuari in line
out.println("Insertant Usuari... " + meuEJB.insertarUsuari(usuari) + "<br/>");
You probably want to use #Inject annotation like this to initialize meuEJB:
#Inject
MissatgesEJB meuEJB;
Related
This is picture of the error wich the browser returns after trying to submit the user:
1
Here is my Create method for Users also i use Repository for holding this methods.
private EntityManager entityManager = EntityManagerUtil.getEntityManager();
public String createUser(String account, String password) {
Users user = new UsersEntity(account, password);
entityManager.getTransaction().begin();
Query queryAccount = entityManager.createNativeQuery("Select * From Users Where Account = '" + account + "' ;",
UsersEntity.class);
List<Users> accountVerification = queryAccount.getResultList();
Query queryPassword = entityManager
.createNativeQuery("Select * From Users Where Password = '" + password + "' ;", UsersEntity.class);
List<Users> passwordVerification = queryPassword.getResultList();
if (accountVerification.size() != 0) {
return "This username is already used! Try with another one!";
} else if (passwordVerification.size() != 0) {
return "This password is already used! Try with another one!";
} else {
entityManager.persist(user);
entityManager.getTransaction().commit();
}
entityManager.close();
return "Sucessfull reccord!";
}
Here is my Controller:
#Controller
public class LibraryHelloWorld {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView loginGet() {
return new ModelAndView("LogInForm");
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView loginPost(HttpServletRequest request, #RequestParam(value = "firstname") String account,
#RequestParam(value = "lastname") String password) {
JPAUsersRepository userrep = new JPAUsersRepository();
userrep.createUser(account.toString(), password.toString());
return new ModelAndView("Sucessfull");
}
In normal class creating of users is working fine but in this #Controller servlet in post method it throws exceptions :
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Initial SessionFactory creation failed.javax.persistence.PersistenceException: [PersistenceUnit: test] Unable to build EntityManagerFactory
Apr 29, 2017 12:10:09 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [library] in context with path [/Library] threw exception [Handler processing failed; nested exception is java.lang.ExceptionInInitializerError] with root cause
java.lang.ClassNotFoundException: Could not load requested class : com.microsoft.sqlserver.jdbc.SQLServerDriver
at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:319)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:149)
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:76)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:160)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:132)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:223)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:89)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:76)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:160)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:132)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1818)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1776)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:899)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:59)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at com.infoleven.utility.EntityManagerUtil.<clinit>(EntityManagerUtil.java:11)
at com.infoleven.controller.LibraryHelloWorld.loginPost(LibraryHelloWorld.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at 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:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
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:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
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:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1533)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1489)
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)
Apr 29, 2017 12:10:24 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
Here is also and my persistence.xml file:
<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_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:sqlserver://localhost:1433;databaseName=Library" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="notgame2" />
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect" />
<property name="show_sql" value="true" />
<property name="hibernate.temp.use_jdbc_metadata_defaults"
value="false" />
</properties>
</persistence-unit>
</persistence>
For DB i use local SQL Server. Create method is working correctly but not and in the current #Controller servler
Make sure you have correct JAR file in your CLASSPATH for com.microsoft.sqlserver.jdbc.SQLServerDriver
JAR file for that would be sqljdbc41.jar, if this is not in your CLASSPATH, then you have to add it. Hibernate will not provide 3rd party JAR files for JDBC Drivers.
The following error(full description below):
com.sun.faces.lifecycle.InvokeApplicationPhase execute WARNING: #{testeHibernate.save}: java.lang.NullPointerException javax.faces.FacesException: #{testeHibernate.save}
This happens when I upload the register button, won't let me enter the values in the database.
Class
UtilizadorDAO.java
package DAO;
import Classhiber.Utilizador;
import java.util.List;
public interface UtilizadorDAO {
public void addutilizador (Utilizador ut);
public List<Utilizador> findallutilizador();
}
UtilizadorDaoimpl.java
package Impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import Classhiber.Utilizador;
import DAO.UtilizadorDAO;
public class UtilizadorDAOimpl implements UtilizadorDAO {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void addutilizador(Utilizador ut) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.persist(ut);
tx.commit();
session.close(); }
public List<Utilizador> findallutilizador() {
Session session = this.sessionFactory.openSession();
List<Utilizador> Utilizadorlist = session.createQuery("from Utilizador").list();
session.close();
return Utilizadorlist;
}
}
testeHibernate.java
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import Classhiber.Utilizador;
import DAO.UtilizadorDAO;
import Impl.UtilizadorDAOimpl;
#ManagedBean
#SessionScoped
public class TesteHibernate {
public UtilizadorDAO utdao;
private Utilizador utiliza;
public TesteHibernate()
{
utdao = new UtilizadorDAOimpl();
utiliza = new Utilizador();
}
public UtilizadorDAO getUtilizadorDAO() {
return utdao;
}
public void setUtiliza(UtilizadorDAOimpl ut) {
this.utdao = ut;
}
public Utilizador getUtiliza() {
return utiliza;
}
public void setUtiliza(Utilizador utz) {
this.utiliza = utz;
}
public void save() {
// Calling Business Service
utiliza.setIdUt(12);
System.out.println(utiliza.getUser());
System.out.println(utiliza.getPass());
System.out.println(utiliza.getTip());
utdao.addutilizador(utiliza);
}
}
Spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3307/xp" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>Classhiber.Utilizador</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="UtilizadorDAOimpl" class="Impl.UtilizadorDAOimpl">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</bean>
</beans>
index.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<script name="jquery/jquery.js" library="primefaces"></script>
<title>Register Utilizador</title>
</h:head>
<h:form>
<p:growl id="messages"></p:growl>
<p:panelGrid columns="2">
<p:outputLabel value="Enter Utilizdor User:"></p:outputLabel>
<p:inputText value="#{testeHibernate.utiliza.user}"></p:inputText>
<p:outputLabel value="Enter Utilizador Pass:"></p:outputLabel>
<p:inputText value="#{testeHibernate.utiliza.pass}"></p:inputText>
<p:outputLabel value="Enter Utilizador tip"></p:outputLabel>
<p:inputText value="#{testeHibernate.utiliza.tip}"></p:inputText>
</p:panelGrid>
<p:commandButton value="Register" action="#{testeHibernate.save}" ></p:commandButton>
</h:form>
</html>
Error
Ago 28, 2015 6:23:44 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: #{testeHibernate.save}: java.lang.NullPointerException
javax.faces.FacesException: #{testeHibernate.save}: java.lang.NullPointerException
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java: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.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:957)
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:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 26 more
Caused by: java.lang.NullPointerException
at Impl.UtilizadorDAOimpl.addutilizador(UtilizadorDAOimpl.java:21)
at TesteHibernate.save(TesteHibernate.java:46)
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:606)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 27 more
1245
Ago 28, 2015 6:23:44 PM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
SEVERE: javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java: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.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:957)
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:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at Impl.UtilizadorDAOimpl.addutilizador(UtilizadorDAOimpl.java:21)
at TesteHibernate.save(TesteHibernate.java:46)
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:606)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 27 more
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5" metadata-complete="true">
<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>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
Thank you. (Excuse me if you have any programming error severe But I am learning)
Since you are using CDI you should initialize your stuff in a method that is annotated with #PostConstruct
so you could replace the constructor in testeHibernate.java with
#PostConstruct
public void init() {
utdao = new UtilizadorDAOimpl();
utiliza = new Utilizador();
}
There is also an annotation for when a class is teared down in CDI, which is #PreDestroy
Also it might come in handy to stick to coding conventions and name the files equally to your class name using a capital letter at the beginning.
I got an error about SessionFactory.
CrudController.java
#Controller
public class CrudController {
#Autowired
private AlbumBo albumBo;
#RequestMapping(value = "/addAlbum")
#ResponseBody
public void addAlbum(
#RequestParam("NameRecordCompany") String nameRecordCompany,
#RequestParam("NameAlbum") String nameAlbum,
#RequestParam("YearName") String yearAlbum,
#RequestParam("NameArtist") String nameArtist,
#RequestParam("NameCategory") String nameCategory,
#RequestParam("SongList") String songList) throws JSONException {
Song temp = new Song();
ArrayList<Song> listaCanzoni = new ArrayList();
String songs = "{" + "\"songs\":" + songList + "}";
JSONObject jsonObjectSongList = new JSONObject(songs);
JSONArray jsonArraySongList = (JSONArray) jsonObjectSongList.get("songs");
for (int i = 0; i < jsonArraySongList.length(); i++) {
temp.setName((String) jsonArraySongList.getJSONObject(i).get("songName"));
temp.setDuration((String) jsonArraySongList.getJSONObject(i).get("songDuration"));
listaCanzoni.add(new Song(temp.getName(), temp.getDuration()));
}
Artist artist = new Artist(nameArtist);
Category category = new Category(nameCategory);
Album album = new Album(nameAlbum, yearAlbum);
album.setArtist(artist);
album.setCategory(category);
try {
albumBo.save(album); //line 67
JOptionPane.showMessageDialog(null, "albumDao.save(album) eseguita");
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
AlbumDaoImpl.java
public class AlbumDaoImpl implements AlbumDao {
#Autowired
SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory factory) {
this.sessionFactory = factory;
}
#Override
public void save(Album album) throws Exception {
Session session = sessionFactory.openSession(); //line 38
Transaction tx = null;
try {
tx = session.beginTransaction();
session.saveOrUpdate(album);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
} else {
e.printStackTrace();
}
} finally {
session.close();
}
}
}
AlbumBoImpl.java
public class AlbumBoImpl implements AlbumBo{
private AlbumDao albumDao;
static final Logger logger = Logger.getLogger(AlbumBoImpl.class);
public AlbumDao getAlbumDao() {
return albumDao;
}
public void setAlbumDao(AlbumDao albumDao) {
this.albumDao = albumDao;
}
#Override
public void save(Album album) throws Exception {
try{
albumDao.save(album); //line 35
}catch(Exception e){
logger.error(e);
throw e;
}
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
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-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"/>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>it.davidefruci.casadiscografica2.beans.Album</value>
<value>it.davidefruci.casadiscografica2.beans.Artist</value>
<value>it.davidefruci.casadiscografica2.beans.Song</value>
<value>it.davidefruci.casadiscografica2.beans.RecordCompany</value>
<value>it.davidefruci.casadiscografica2.beans.Category</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- DAO -->
<bean id="albumDao" class="it.davidefruci.casadiscografica2.daoImpl.AlbumDaoImpl"/>
<bean id="artistDao" class="it.davidefruci.casadiscografica2.daoImpl.ArtistDaoImpl"/>
<bean id="categoryDao" class="it.davidefruci.casadiscografica2.daoImpl.CategoryDaoImpl"/>
<bean id="recordCompanyDao" class="it.davidefruci.casadiscografica2.daoImpl.RecordCompanyDaoImpl"/>
<bean id="songDao" class="it.davidefruci.casadiscografica2.daoImpl.SongDaoImpl"/>
<!-- BO -->
<bean id="albumBo" class="it.davidefruci.casadiscografica2.boImpl.AlbumBoImpl">
<property name="albumDao" ref="albumDao"></property>
</bean>
<bean id="artistBo" class="it.davidefruci.casadiscografica2.boImpl.ArtistBoImpl">
<property name="artistDao" ref="artistDao"></property>
</bean>
<bean id="categoryBo" class="it.davidefruci.casadiscografica2.boImpl.CategoryBoImpl">
<property name="categoryDao" ref="categoryDao"></property>
</bean>
<bean id="recordCompanyBo" class="it.davidefruci.casadiscografica2.boImpl.RecordCompanyBoImpl">
<property name="recordCompanyDao" ref="recordCompanyDao"></property>
</bean>
<bean id="songBo" class="it.davidefruci.casadiscografica2.boImpl.SongBoImpl">
<property name="songDao" ref="songDao"></property>
</bean>
I have a JSP where I add the datas that I want to save into my db.
When I click on the submit button, an Ajax call is invoked. This call invokes the CrudController, who should save data on my db with addAlbum method.
When the CrudController is invoked Tomcat tells me:
java.lang.NullPointerException
at it.davidefruci.casadiscografica2.daoImpl.AlbumDaoImpl.save(AlbumDaoImpl.java:38)
at it.davidefruci.casadiscografica2.boImpl.AlbumBoImpl.save(AlbumBoImpl.java:35)
at it.davidefruci.casadiscografica2.controllers.CrudController.addAlbum(CrudController.java:67)
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:221)
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.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
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.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
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)
I wrong something with the sessionFactory initialization?
<bean id="personDao"class="com.studytrails.tutorials.springhibernatesessionfactory.PersonDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
You will need to inject session factory in DAO you are using which will help you do CRUD operations on your Object either you can configure this in XML or using annotation.
Also please help your self by going through the given like below
Example of spring hibernate integration
Two things you can do, one is change to inject the SessionFactory to Dao by yourself.
<!-- DAO -->
<bean id="albumDao" class="it.davidefruci.casadiscografica2.daoImpl.AlbumDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
You can do this for all DAOs.
Or
put a component scan on the applicationContext.xml XML configuration so that the SessionFactory will get Autowired.
<context:component-scan base-package="it.davidefruci.casadiscografica2"/>
I want to implements simple login with spring mvc and jdbc template. but I am getting null pointer exception. I have included spring-core.jar,spring-jdbc.jar,spring-txn.jar,spring-web.jar..
****Complete stack trace:****
May 17, 2015 6:54:54 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [login] in context with path [/MVCWithJDBC] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.mvc.dao.LoginDAOImpl.getLoginDetails(LoginDAOImpl.java:25)
at com.mvc.controller.LoginController.handleRequest(LoginController.java:30)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:563)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
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:504)
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:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
**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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>MVCMultpleActions</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>*.ak</url-pattern>
</servlet-mapping>
</web-app>
**login-servlet.xml:**
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean name="/login.ak" class="com.mvc.controller.LoginController"> </bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="mysql" />
</bean>
<bean id="logindao" class="com.mvc.dao.LoginDAOImpl">
<property name="dataSource" ref="ds"></property>
</bean>
</beans>
**DAO Classes:**
package com.mvc.dao;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import com.mvc.mapper.*;
import com.mvc.dto.LoginDTO;
public class LoginDAOImpl extends JdbcDaoSupport implements LoginDAO {
#Override
public LoginDTO getLoginDetails(String userName) {
// TODO Auto-generated method stub
System.out.println("userName:"+userName);
String query="select password from Login where userName=?";
System.out.println("query"+query);
return getJdbcTemplate.queryForObject(query,new Object[]{userName},new LoginMapper());
}
}
**Controller:**
package com.mvc.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import com.mvc.dao.LoginDAOImpl;
import com.mvc.dto.LoginDTO;
public class LoginController implements Controller{
#Override
public ModelAndView handleRequest(HttpServletRequest req,
HttpServletResponse res) throws Exception {
// TODO Auto-generated method stub
String name=req.getParameter("userName");
String password=req.getParameter("password");
LoginDAOImpl login=new LoginDAOImpl();
LoginDTO loginDto=new LoginDTO();
loginDto.setUserName(name);
loginDto.setPassword(password);
System.out.println("pw:"+password);
String pw=login.getLoginDetails("admin").getPassword();
System.out.println("dao pw:"+pw);
if(password.equalsIgnoreCase(pw))
{
String message = "HELLO "+name;
return new ModelAndView("hellopage", "message", message);
}
else{
return new ModelAndView("errorpage", "message","Sorry, username or password error");
}
}
}
You can simply extend JdbcDaoSupport
public class LoginDAOImpl extends JdbcDaoSupport implements LoginDAO {
//codes
}
while jdbcTemplate setter method can be removed from this implementation class.
And you can also see this tutorial for the reference of my answer.
I'm trying create a generic class for automate the creation of jpacontainer in my project but doesn't work and returns some errors. The errors refer No EntityProvider has been set.
I'm trying this.
/** class init jpacontainer */
public class PersistJPAContainer<T> extends JPAContainer<T>{
private static final long serialVersionUID = 1L;
private static final String PERSISTENCE_UNITNAME = "ps_unitname";
public PersistJPAContainer(Class<T> entityClass) {
super(entityClass);
JPAContainer<?> container = JPAContainerFactory.make(entityClass, PERSISTENCE_UNITNAME);
}
}
/** my app UI */
public class AcademiaonlineUI extends UI {
private final JPAContainer<Empresa> datasource = new PersistJPAContainer<Empresa>(Empresa.class);
#Override
protected void init(VaadinRequest request) {
Table tabela = new Table("Empresa", datasource);
VerticalLayout vLayout = new VerticalLayout();
vLayout.addComponent(tabela);
setContent(vLayout);
}
}
/** errors */
Mar 17, 2014 11:14:30 AM com.vaadin.server.DefaultErrorHandler doDefault
SEVERE:
java.lang.IllegalStateException: No EntityProvider has been set
at com.vaadin.addon.jpacontainer.JPAContainer.doGetEntityProvider(JPAContainer.java:313)
at com.vaadin.addon.jpacontainer.JPAContainer.size(JPAContainer.java:912)
at com.vaadin.ui.AbstractSelect.size(AbstractSelect.java:762)
at com.vaadin.ui.Table.refreshRenderedCells(Table.java:1654)
at com.vaadin.ui.Table.attach(Table.java:4171)
at com.vaadin.server.AbstractClientConnector.attach(AbstractClientConnector.java:583)
at com.vaadin.ui.AbstractComponent.attach(AbstractComponent.java:572)
at com.vaadin.ui.AbstractComponent.setParent(AbstractComponent.java:479)
at com.vaadin.ui.AbstractSingleComponentContainer.setContent(AbstractSingleComponentContainer.java:137)
at com.vaadin.ui.UI.setContent(UI.java:1162)
at br.com.academiaonline.AcademiaonlineUI.init(AcademiaonlineUI.java:24)
at com.vaadin.ui.UI.doInit(UI.java:614)
at com.vaadin.server.communication.UIInitHandler.getBrowserDetailsUI(UIInitHandler.java:223)
at com.vaadin.server.communication.UIInitHandler.synchronizedHandleRequest(UIInitHandler.java:73)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:37)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1382)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:238)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
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:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:724)
//persistence.xml
<?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="ps_unitname" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>br.com.academiaonline.beans.Empresa</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:~/AODB"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value="master"/>
<!-- Cria a base de dados automaticamente -->
<property name="eclipselink.ddl-generation" value="create-or-extend-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
<!-- Exibe log de erros no console do eclipse -->
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
</persistence>
Any idea ?
Try some thing like this in your Constructor
public class CustomJPA extends JPAContainer {
private static final long serialVersionUID = -1752491307148335890L;
private static final String PU_UNIT="ps_unitname";
public CustomJPA(Class<T> entityClass, String persitenceUnitName) {
super(entityClass);
EntityManager entityManager = JPAContainerFactory.createEntityManagerForPersistenceUnit(persitenceUnitName);
setEntityProvider(new CachingMutableLocalEntityProvider<T>(entityClass,entityManager));
}
public CustomJPA(Class<T> entityClass) {
super(entityClass);
EntityManager entityManager =JPAContainerFactory.createEntityManagerForPersistenceUnit(PU_UNIT);
setEntityProvider(new CachingMutableLocalEntityProvider<T>(entityClass,entityManager));
}
}
Where ever I have to initalise my Container, I do it some thing like this
JPAContainer<Bean> myBean= new CustomJPA<Bean>(Bean.class);
Hope this helps. I feel that you are writing some redundant code.
NOTE:
I have not tested this snippet of code.
Try to use appropriate class as your EnityProvider, I used the
default one in this example
BTW, is this what you are expecting??
now works...after some tests finally works.
I did so.
public class PersistJPAContainer<T> extends JPAContainer<T>{
private static final long serialVersionUID = 1L;
private static final String PERSISTENCE_UNITNAME = "ps_unitname";
public PersistJPAContainer(Class<T> entityClass) {
super(entityClass);
EntityManager em = JPAContainerFactory.createEntityManagerForPersistenceUnit(PERSISTENCE_UNITNAME);
setEntityProvider(new CachingMutableLocalEntityProvider<T>(entityClass, em));
}
}
public class AcademiaonlineUI extends UI {
private final PersistJPAContainer<Empresa> datasource = new PersistJPAContainer<Empresa>(Empresa.class);
And works !