0

I am trying to make a maven login application using hibernate to persist the data onto a mysql database. I am deploying the application on a glassfish server. I am able to start the server and fill in data on the html form but once I submit the form, I get the following error logs:

2016-11-21T22:40:05.371-0500|Info: HHH000412: Hibernate Core {5.2.4.Final} 2016-11-21T22:40:05.379-0500|Info: HHH000206: hibernate.properties not found 2016-11-21T22:40:05.385-0500|Info: HHH000021: Bytecode provider name : javassist 2016-11-21T22:40:05.471-0500|Warning: StandardWrapperValve[RegisterServlet]:Servlet.service() for servlet RegisterServlet threw exception java.lang.ExceptionInInitializerError at model.RegisterService.isExistingUser(RegisterService.java:8) at model.RegisterServlet.doPost(RegisterServlet.java:59) at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283) at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571) at java.lang.Thread.run(Thread.java:745) Caused by: org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [C:\Users\marvi\workspace1\LoginApp\hibernate.cfg.xml] at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:53) at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163) at org.hibernate.cfg.Configuration.configure(Configuration.java:258) at model.HibernateUtil.<clinit>(HibernateUtil.java:15) ... 32 more 

I have moved the location of the hibernate.cfg.xml file from root folder, to the resource folder and also into the resource folder but problem prevails I have also added path of the cfg.xml file to the .configure() method, but did not work. I have looked at all the previously asked questions: ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml] in project root folder 2

Hibernate ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml] IntelliJ 1

org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [/HibernateTest/src/hibernate.cfg.xml] 1

HTTP Status 500 - org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]

but non of the solutions given fix my problem.

image of Project structure

Below is my code for my entity class.

package model; import javax.persistence.Entity; import javax.persistence.Id; import org.hibernate.annotations.NamedQueries; import org.hibernate.annotations.NamedQuery; @Entity @NamedQueries({ @NamedQuery(name="getUserByUserNameAndPassword", query="SELECT u FROM User u WHERE u.userName = :uname AND u.password = :pword") }) public class User{ @Id private Long userId; private String firstName; private String lastName; private String userName; private String password; public User() { } //Getters and setters } 

Below is by hibernate util class.

package model; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class HibernateUtil { private static final SessionFactory sessionFactory; private static final ServiceRegistry serviceRegistry; static { Configuration conf = new Configuration(); conf.configure(); serviceRegistry = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build(); try { sessionFactory = conf.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("Initial SessionFactory creation failed." + e); throw new ExceptionInInitializerError(e); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } 

Below is my 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/test</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">password</property> <property name="show_sql">true</property> <mapping resource="User.hbm.xml"></mapping> </session-factory> </hibernate-configuration> 

My servlet class

package model; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class RegisterServlet */ @WebServlet("/register") public class RegisterServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public RegisterServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String fName = request.getParameter("firstName"); String uName = request.getParameter("userName"); String lName = request.getParameter("lastName"); String password = request.getParameter("password"); User user = new User(); user.setFirstName(fName); user.setLastName(lName); user.setUserName(uName); user.setPassword(password); RegisterService rs = new RegisterService(); if (!rs.isExistingUser(user.getUserName())) {//if user does NOT exist, then we register them rs.registerUser(user);//register the user first out.println("<h1>Registration Successful</h1>"); out.println("To login with new UserId and Password<a href=login.jsp>Click here</a>"); out.println("</center>"); out.println("</body>"); out.println("</html>"); out.close(); }else{//if user already exist out.println("<h1>Username Exists!!</h1>"); out.println("To try again<a href=register.jsp>Click here</a>"); //RequestDispatcher d = request.getRequestDispatcher("index.jsp"); //d.forward(request, response); } //doGet(request, response); } } 

My service class:

package model; import org.hibernate.Session; public class RegisterService { public boolean isExistingUser(String uname) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); User user = (User) session.getNamedQuery("getUser").setParameter("uname", uname).uniqueResult(); session.getTransaction().commit(); session.close(); if (user.getUserName() != uname) { return false; } return true; } public void registerUser(User user) { if (!isExistingUser(user.getUserName())) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.saveOrUpdate(user); session.getTransaction().commit(); session.close(); } } } 

and finally my pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.marv.servelet</groupId> <artifactId>LoginApp</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>LoginApp Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.4.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.5</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin --> <dependency> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> </dependency> </dependencies> <build> <finalName>LoginApp</finalName> </build> </project> 
0

1 Answer 1

0

Put your Hibernate.cfg.xml in src folder of your project and update the code as below and check if it works. SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); This will automatically fetch the .cfg file without mentioning it.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.