I'm trying to follow a tutorial to make a simple web application using PostgreSQL as db with Hibernate, Tomcat as server and Eclipse as IDE.
The user should enter name, surname and country to a simple form
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>My first Web App</title>
</head>
<body>
<h1>Let's create a new user</h1>
<form method="POST" action = "CreateUser.do">
First Name <input type = "text" size = "40" maxlength = "40" name = "firstname" /><br/>
Last Name <input type = "text" size = "40" maxlength = "40" name = "lastname" /><br/>
Country <input type = "text" size = "40" maxlength = "40" name = "country" /><br/>
<input type = "submit" value = "create" >
</form>
</body>
</html>
Then I have AddUser.java as Controller in the Model View Controller pattern
package controller;
import java.io.IOException;
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;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import model.User;
/**
* Servlet implementation class AddUser
*/
#WebServlet(description = "Create new user Servlet", urlPatterns = {"/CreateUser.do"})
public class AddUser extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
RequestDispatcher view = request.getRequestDispatcher("useradd.jsp");
view.forward(request, response);
*/
Configuration config = new Configuration().configure();
ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
SessionFactory factory = config.buildSessionFactory(servReg);
Session session = factory.openSession();
session.beginTransaction();
User u = new User(request.getParameter("firstname"),
request.getParameter("lastname"),
request.getParameter("country"));
session.save(u);
session.getTransaction().commit();
session.close();
RequestDispatcher view = request.getRequestDispatcher("useradd.jsp");
view.forward(request, response);
}
}
And User.java as Model
package model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table( name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="user_id", nullable=false, unique=true)
private int id;
#Column(name="firstname", length=40, nullable=false)
private String firstname;
#Column(name="lastname", length=40, nullable=false)
private String lastname;
#Column(name="country", length=40, nullable=true)
private String country;
public User(String firstName, String lastName, String country) {
firstname = firstName;
lastname = lastName;
this.country = country;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstname;
}
public void setFirstName(String firstName) {
this.firstname = firstName;
}
public String getLastName() {
return lastname;
}
public void setLastName(String lastName) {
this.lastname = lastName;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Lastly, useradd.jsp acts as view and should show the data written in the DB.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My first Web App - New User Created!</title>
</head>
<body>
<h1>New User Created</h1>
<p>
First Name: <% String fName = request.getParameter("firstname"); out.print(fName); %> <br/>
Last Name: <% String lName = request.getParameter("lastname"); out.print(lName); %> <br/>
Country: <% String country = request.getParameter("country"); out.print(country); %> <br/>
</p>
</body>
</html>
I've also made the hibernate.cfg.xml file in the /src folder
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/firstapp</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">admin</property>
<property name="show_sql">false</property>
<mapping class="model.User"/>
</session-factory>
</hibernate-configuration>
I can run the application, type in first name/last name/country but, when I press create, it shows this error: HTTP Status 500 - Unknown entity: model.User
Of course it doesn't write anything to the DB.
This is what the console shows:
mag 13, 2016 7:20:44 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
AVVERTENZA: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:2 - Hibernate' did not find a matching property.
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Server version: Apache Tomcat/8.0.33
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Server built: Mar 18 2016 20:31:49 UTC
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Server number: 8.0.33.0
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: OS Name: Windows 10
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: OS Version: 10.0
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Architecture: x86
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Java Home: C:\Program Files (x86)\Java\jre1.8.0_91
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: JVM Version: 1.8.0_91-b14
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: JVM Vendor: Oracle Corporation
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: CATALINA_BASE: C:\Users\Antonio\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: CATALINA_HOME: C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.0
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Command line argument: -Dcatalina.base=C:\Users\Antonio\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Command line argument: -Dcatalina.home=C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.0
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Command line argument: -Dwtp.deploy=C:\Users\Antonio\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Command line argument: -Djava.endorsed.dirs=C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.0\endorsed
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Command line argument: -Dfile.encoding=Cp1252
mag 13, 2016 7:20:44 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFORMAZIONI: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files (x86)\Java\jre1.8.0_91\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files (x86)/Java/jre1.8.0_91/bin/client;C:/Program Files (x86)/Java/jre1.8.0_91/bin;C:/Program Files (x86)/Java/jre1.8.0_91/lib/i386;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Users\Antonio\Desktop\eclipse;;.
mag 13, 2016 7:20:44 PM org.apache.coyote.AbstractProtocol init
INFORMAZIONI: Initializing ProtocolHandler ["http-nio-8080"]
mag 13, 2016 7:20:44 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFORMAZIONI: Using a shared selector for servlet write/read
mag 13, 2016 7:20:44 PM org.apache.coyote.AbstractProtocol init
INFORMAZIONI: Initializing ProtocolHandler ["ajp-nio-8009"]
mag 13, 2016 7:20:44 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFORMAZIONI: Using a shared selector for servlet write/read
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.Catalina load
INFORMAZIONI: Initialization processed in 1448 ms
mag 13, 2016 7:20:44 PM org.apache.catalina.core.StandardService startInternal
INFORMAZIONI: Starting service Catalina
mag 13, 2016 7:20:44 PM org.apache.catalina.core.StandardEngine startInternal
INFORMAZIONI: Starting Servlet Engine: Apache Tomcat/8.0.33
mag 13, 2016 7:20:45 PM org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
INFORMAZIONI: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [199] milliseconds.
mag 13, 2016 7:20:46 PM org.apache.jasper.servlet.TldScanner scanJars
INFORMAZIONI: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
mag 13, 2016 7:20:46 PM org.apache.coyote.AbstractProtocol start
INFORMAZIONI: Starting ProtocolHandler ["http-nio-8080"]
mag 13, 2016 7:20:46 PM org.apache.coyote.AbstractProtocol start
INFORMAZIONI: Starting ProtocolHandler ["ajp-nio-8009"]
mag 13, 2016 7:20:46 PM org.apache.catalina.startup.Catalina start
INFORMAZIONI: Server startup in 1935 ms
mag 13, 2016 7:21:06 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
mag 13, 2016 7:21:06 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
mag 13, 2016 7:21:06 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
mag 13, 2016 7:21:07 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
mag 13, 2016 7:21:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
mag 13, 2016 7:21:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/firstapp]
mag 13, 2016 7:21:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=postgres, password=****}
mag 13, 2016 7:21:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
mag 13, 2016 7:21:08 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
mag 13, 2016 7:21:08 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
mag 13, 2016 7:21:09 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
mag 13, 2016 7:21:09 PM org.hibernate.type.BasicTypeRegistry register
INFO: HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#bfbdad
mag 13, 2016 7:21:10 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [controller.AddUser] in context with path [/2_-_Hibernate] threw exception
org.hibernate.MappingException: Unknown entity: model.User
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1533)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
at controller.AddUser.doPost(AddUser.java:48)
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: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:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
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:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
I've been stuck for hours and cannot find any solution.
Hope you guys can help me. Thanks in advance!
If you are using Hiberanate 5, please create Session factory in this way:
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
instead of
Configuration config = new Configuration().configure();
ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
SessionFactory factory = config.buildSessionFactory(servReg);
Related
I'm trying to implement a simple registration form using hibernate. My data is successfully being inserted into my database, but the webpage is not being redirected to another jsp file (after registration).
package codegals.project.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="users")
public class User implements Serializable{
private static final long serialVersionUID=1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "user_name")
private String username;
#Column(name = "password")
private String password;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package codegals.project.dao;
import org.hibernate.Session;
import org.hibernate.Transaction;
import codegals.project.model.User;
import codegals.project.util.HibernateUtil;
public class UserDao {
public void saveUser(User user) {
Transaction transaction=null;
try(Session session=HibernateUtil.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
session.save(user);
transaction.commit();
} catch(Exception e) {
if(transaction!=null) {
transaction.rollback();
}
e.printStackTrace();
}
}
}
package codegals.project.util;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import codegals.project.model.User;
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if(sessionFactory==null) {
try {
Configuration configuration = new Configuration();
Properties settings = new Properties();
settings.put(Environment.DRIVER, "com.mysql.jdbc.Driver");
settings.put(Environment.URL, "jdbc:mysql://localhost:3307/codegals?useSSL=true");
settings.put(Environment.USER, "root");
settings.put(Environment.PASS, "namya18#DataBase");
settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.HBM2DDL_AUTO, "update");
configuration.setProperties(settings);
configuration.addAnnotatedClass(User.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Java Config serviceRegistry created");
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch(Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
}
package codegals.project.web;
import java.io.IOException;
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;
import codegals.project.dao.UserDao;
import codegals.project.model.User;
#WebServlet("/register")
public class UserController extends HttpServlet
{
private static final long serialVersionUID=1L;
private UserDao userDao;
public void init() {
userDao = new UserDao();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
register(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("register.jsp");
}
private void register(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = new User();
user.setFirstName(firstName);
user.setLastName(lastName);
user.setUsername(username);
user.setPassword(password);
userDao.saveUser(user);
RequestDispatcher dispatcher = request.getRequestDispatcher("register-success.jsp");
dispatcher.forward(request, response);
}
}
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registration page</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row text-center" style="color: tomato;">
<h2>User Registration with JSP, Servlet and Hibernate</h2>
</div>
<hr>
<div class="row col-md-10 col-md-offset-3">
<div class="card card-body">
<h2>User Register Form</h2>
<div class="col-md-8 col-md-offset-3">
<form action="<%=request.getContextPath()%>/register" method="post">
<div class="form-group">
<label for="uname">First Name:</label> <input type="text"
class="form-control" id="uname" placeholder="First Name"
name="firstName" required>
</div>
<div class="form-group">
<label for="uname">Last Name:</label> <input type="text"
class="form-control" id="uname" placeholder="last Name"
name="lastName" required>
</div>
<div class="form-group">
<label for="uname">User Name:</label> <input type="text"
class="form-control" id="username" placeholder="User Name"
name="username" required>
</div>
<div class="form-group">
<label for="uname">Password:</label> <input type="password"
class="form-control" id="password" placeholder="Password"
name="password" required>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registered successfully!</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row col-md-10 col-md-offset-3">
<div class="card card-body">
<h1>User successfully registered!</h1>
</div>
</div>
</div>
</body>
</html>
Error log:
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version name: Apache Tomcat/9.0.48
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built: Jun 10 2021 09:22:01 UTC
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version number: 9.0.48.0
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name: Windows 10
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version: 10.0
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture: amd64
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home: C:\Users\namya\.p2\pool\plugins\org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_15.0.2.v20210201-0955\jre
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version: 15.0.2+7-27
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor: Oracle Corporation
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE: C:\Users\namya\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME: C:\Program Files\apache-tomcat-9.0.48
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\namya\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Program Files\apache-tomcat-9.0.48
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\namya\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -XX:+ShowCodeDetailsInExceptionMessages
Jul 26, 2021 12:04:48 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: Loaded Apache Tomcat Native library [1.2.30] using APR version [1.7.0].
Jul 26, 2021 12:04:48 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true], UDS [true].
Jul 26, 2021 12:04:48 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
Jul 26, 2021 12:04:48 PM org.apache.catalina.core.AprLifecycleListener initializeSSL
INFO: OpenSSL successfully initialized [OpenSSL 1.1.1k 25 Mar 2021]
Jul 26, 2021 12:04:48 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Jul 26, 2021 12:04:48 PM org.apache.catalina.startup.Catalina load
INFO: Server initialization in [619] milliseconds
Jul 26, 2021 12:04:48 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Catalina]
Jul 26, 2021 12:04:48 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet engine: [Apache Tomcat/9.0.48]
Jul 26, 2021 12:04:50 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jul 26, 2021 12:04:50 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Jul 26, 2021 12:04:50 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in [1968] milliseconds
Jul 26, 2021 12:05:03 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.3.7.Final}
Jul 26, 2021 12:05:03 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Hibernate Java Config serviceRegistry created
Jul 26, 2021 12:05:03 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
Jul 26, 2021 12:05:03 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Jul 26, 2021 12:05:03 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3307/codegals?useSSL=true]
Jul 26, 2021 12:05:03 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=root}
Jul 26, 2021 12:05:03 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jul 26, 2021 12:05:03 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jul 26, 2021 12:05:04 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Jul 26, 2021 12:05:06 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#57799d58] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into users (first_name, last_name, password, user_name, id) values (?, ?, ?, ?, ?)
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into users (first_name, last_name, password, user_name, id) values (?, ?, ?, ?, ?)
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into users (first_name, last_name, password, user_name, id) values (?, ?, ?, ?, ?)
Folder structure:
https://drive.google.com/file/d/1lslxQ8C7-tkV9SFbfx7DLMsgxfoc-qQp/view?usp=sharing
I can't embed images in my answers yet, so I've sent a link
I'm a newbie to this and can't figure what went wrong. Any suggestions that might help?
Your .jsp files are under the /WEB-INF directory, so, your RequestDispatcher should include it when doing the forward.
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/register-success.jsp");
dispatcher.forward(request, response);
This also means that your UserController.doGet() doesn't work correctly either. If you make a GET request by directly accessing the servlet URL http://localhost:8080/registration/register, it should throw a 404 error too.
But, changing the sendRedirect() code to
response.sendRedirect("/WEB-INF/register.jsp");
will NOT help in this case because sendRedirect() does a client-side redirection i.e. the browser makes a fresh new request and anything under /WEB-INF is NOT directly accessible from outside the web app.
Move the register.jsp to /src/main/webapp and the doGet() will start working as it is.
I develop basic user management project using Servlet-JSP-MongoDB.My codes are bellow.After I run project on Tomcat ,I take exception on console as follows.
Why is this problem,please help me?
package com.fatih.controller;
import java.io.IOException;
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;
import com.fatih.dao.UserDAO;
import com.fatih.model.User;
import com.mongodb.MongoClient;
/**
* Servlet implementation class AddUser
*/
#WebServlet("/addUser")
public class AddUser extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public AddUser() {
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 {
String name=request.getParameter("name");
String email=request.getParameter("emailId");
String password=request.getParameter("password");
if( (name==null || name.equals(""))||
(email==null || email.equals(""))||
(password==null || password.equals(""))){
request.setAttribute("error", "All fields are required!");
RequestDispatcher dispatcher=getServletContext().getRequestDispatcher("/users.jsp");
dispatcher.forward(request, response);
}else{
User user=new User();
user.setName(name);
user.setEmail(email);
user.setPassword(password);
MongoClient mongoClient=(MongoClient) request.getServletContext().getAttribute("MONGO_CLIENT");
UserDAO userDAO=new UserDAO(mongoClient);
userDAO.createUser(user);
request.setAttribute("success", "User added");
RequestDispatcher dispatcher=getServletContext().getRequestDispatcher("/users.jsp");
dispatcher.forward(request, response);
}
System.out.println("name: "+name+"\nemail: "+email+"\npassword: "+password);
}
}
.......................................................................
package com.fatih.conventer;
import org.bson.types.ObjectId;
import com.fatih.model.User;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBObject;
public class UserConventer {
public static DBObject toDBObject(User user) {
BasicDBObjectBuilder builder=BasicDBObjectBuilder.start()
.append("name", user.getName())
.append("email", user.getEmail())
.append("password", user.getPassword());
if(user.getId()!=null){
builder=builder.append("_id", new ObjectId(user.getId()));
}
return builder.get();
}
}
..........................................................................
package com.fatih.dao;
import org.bson.types.ObjectId;
import com.fatih.conventer.UserConventer;
import com.fatih.model.User;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
public class UserDAO {
private DBCollection dbCollection;
public UserDAO(MongoClient mongoClient) {
this.dbCollection=mongoClient.getDB("usersDB").getCollection("users");
}
public User createUser(User user){
DBObject dbObject=UserConventer.toDBObject(user);
this.dbCollection.insert(dbObject);
ObjectId id=(ObjectId) dbObject.get("_id");
user.setId(id.toString());
return user;
}
}
..........................................................
package com.fatih.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import com.mongodb.MongoClient;
#WebListener
public class MongoDBListener implements ServletContextListener{
#Override
public void contextDestroyed(ServletContextEvent sce) {
MongoClient mongoClient=(MongoClient) sce.getServletContext().getAttribute("MONGO_CLIENT");
mongoClient.close();
}
#Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext context=sce.getServletContext();
MongoClient mongoClient=new MongoClient(context.getInitParameter("MONGO_HOST"),Integer.parseInt(context.getInitParameter("MONGO_PORT")));
sce.getServletContext().setAttribute("MONGO_CLIENT", mongoClient);
}
}
......................................................................
package com.fatih.model;
public class User {
private String id;
private String name;
private String email;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>KullaniciYonetimSistemiMongoDB</display-name>
<context-param>
<param-name>MONGO_HOST</param-name>
<param-value>localhost</param-value>
</context-param>
<context-param>
<param-name>MONGO_PORT</param-name>
<param-value>27017</param-value>
</context-param>
<welcome-file-list>
<welcome-file>users.jsp</welcome-file>
</welcome-file-list>
</web-app>
Consol output is bellow:
Kas 26, 2016 4:53:23 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:KullaniciYonetimSistemiMongoDB' did not find a matching property.
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version: Apache Tomcat/8.0.36
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built: Jun 9 2016 13:55:50 UTC
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number: 8.0.36.0
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name: Windows 7
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version: 6.1
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture: amd64
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home: C:\Program Files\Java\jre1.8.0_111
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version: 1.8.0_111-b14
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor: Oracle Corporation
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE: C:\javaTools\apache-tomcat-8.0.36
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME: C:\javaTools\apache-tomcat-8.0.36
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\javaTools\apache-tomcat-8.0.36
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\javaTools\apache-tomcat-8.0.36
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\javaTools\apache-tomcat-8.0.36\wtpwebapps
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\javaTools\apache-tomcat-8.0.36\endorsed
Kas 26, 2016 4:53:23 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1254
Kas 26, 2016 4:53:23 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre1.8.0_111\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre1.8.0_111/bin/server;C:/Program Files/Java/jre1.8.0_111/bin;C:/Program Files/Java/jre1.8.0_111/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Java\jdk1.8.0_101\bin;C:\Program Files\Git\cmd;C:\Program Files (x86)\MySQL\MySQL Fabric 1.5 & MySQL Utilities 1.5\;C:\Program Files (x86)\MySQL\MySQL Fabric 1.5 & MySQL Utilities 1.5\Doctrine extensions for PHP\;C:\Program Files\nodejs\;C:\Program Files (x86)\Skype\Phone\;C:\Program Files (x86)\Calibre2\;C:\Program Files (x86)\scala\bin;C:\Program Files\Java\jdk1.8.0_101\bin\;C:\Users\mypc\AppData\Roaming\npm;C:\adb; C:\maven\apache-maven-3.3.9\bin;C:\maven\apache-maven-3.3.9\bin;C:\Users\mypc\AppData\Roaming\npm;%M2%;C:\Program Files\MongoDB\Server\3.2\bin;;C:\Users\mypc\Downloads\programlar\eclipse;;.
Kas 26, 2016 4:53:24 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Kas 26, 2016 4:53:24 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Kas 26, 2016 4:53:24 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Kas 26, 2016 4:53:24 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Kas 26, 2016 4:53:24 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2248 ms
Kas 26, 2016 4:53:24 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Kas 26, 2016 4:53:24 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.36
Kas 26, 2016 4:53:26 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Kas 26, 2016 4:53:26 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\docs
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deployment of web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\docs has finished in 35 ms
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\examples
Kas 26, 2016 4:53:27 PM org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized()
Kas 26, 2016 4:53:27 PM org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextInitialized()
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deployment of web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\examples has finished in 586 ms
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\host-manager
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deployment of web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\host-manager has finished in 64 ms
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\manager
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deployment of web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\manager has finished in 58 ms
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\ROOT
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deployment of web application directory C:\javaTools\apache-tomcat-8.0.36\webapps\ROOT has finished in 33 ms
Kas 26, 2016 4:53:27 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Kas 26, 2016 4:53:27 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Kas 26, 2016 4:53:27 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 2953 ms
Kas 26, 2016 4:53:28 PM com.mongodb.diagnostics.logging.JULLogger log
**INFO: Exception in monitor thread while connecting to server localhost:27017
com.mongodb.MongoSocketOpenException: Exception opening socket**
at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:116)
at java.lang.Thread.run(Unknown Source)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
... 3 more
**Kas 26, 2016 4:53:37 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by WritableServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]}. Waiting for 30000 ms before timing out**
**Kas 26, 2016 4:54:07 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.fatih.controller.AddUser] in context with path [/KullaniciYonetimSistemiMongoDB] threw exception
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches WritableServerSelector. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]**
at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:375)
at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:104)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71)
at com.mongodb.binding.ClusterBinding.getWriteConnectionSource(ClusterBinding.java:68)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:221)
at com.mongodb.operation.BaseWriteOperation.execute(BaseWriteOperation.java:134)
at com.mongodb.operation.BaseWriteOperation.execute(BaseWriteOperation.java:61)
at com.mongodb.Mongo.execute(Mongo.java:827)
at com.mongodb.Mongo$2.execute(Mongo.java:810)
at com.mongodb.DBCollection.executeWriteOperation(DBCollection.java:333)
at com.mongodb.DBCollection.insert(DBCollection.java:328)
at com.mongodb.DBCollection.insert(DBCollection.java:319)
at com.mongodb.DBCollection.insert(DBCollection.java:289)
at com.mongodb.DBCollection.insert(DBCollection.java:255)
at com.mongodb.DBCollection.insert(DBCollection.java:192)
at com.fatih.dao.UserDAO.createUser(UserDAO.java:23)
at com.fatih.controller.AddUser.doPost(AddUser.java:69)
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: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:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
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:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
***IN WEB BROWSER:***
**HTTP Status 500 - Timed out after 30000 ms while waiting for a server that matches WritableServerSelector. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]**
**type Exception report
message Timed out after 30000 ms while waiting for a server that matches WritableServerSelector. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
description The server encountered an internal error that prevented it from fulfilling this request.
exception
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches WritableServerSelector. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:375)
com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:104)
com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75)
com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71)
com.mongodb.binding.ClusterBinding.getWriteConnectionSource(ClusterBinding.java:68)
com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:221)
com.mongodb.operation.BaseWriteOperation.execute(BaseWriteOperation.java:134)
com.mongodb.operation.BaseWriteOperation.execute(BaseWriteOperation.java:61)
com.mongodb.Mongo.execute(Mongo.java:827)
com.mongodb.Mongo$2.execute(Mongo.java:810)
com.mongodb.DBCollection.executeWriteOperation(DBCollection.java:333)
com.mongodb.DBCollection.insert(DBCollection.java:328)
com.mongodb.DBCollection.insert(DBCollection.java:319)
com.mongodb.DBCollection.insert(DBCollection.java:289)
com.mongodb.DBCollection.insert(DBCollection.java:255)
com.mongodb.DBCollection.insert(DBCollection.java:192)
com.fatih.dao.UserDAO.createUser(UserDAO.java:23)
com.fatih.controller.AddUser.doPost(AddUser.java:69)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.36 logs.**
I solve this problem;I change mongodb java driver version from 3.0.1 to 2.13.3 in pom.xml.Project run succesfully.
I am trying to retrieve data from hibernate. I inserted following data in the Users table in the Database.
userId=2
userName=kiko
password=kareem
Now I want to retrieve them again but I don't know the right cast for List<> , because when i tried to retrieve from users1 object, it is now found by the code :
out.println(users1.getUserName());
Here's my code
login.java (servlet)
package Controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import HibernateClasses.Users;
/**
* Servlet implementation class login
*/
#WebServlet("/login")
public class login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public login() {
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
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String name = request.getParameter("username");
String password = request.getParameter("password");
out.println("your name is " + name);
// Users users = new Users();
SessionFactory sessionfactory = new Configuration().configure()
.buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
Query query = session.getNamedQuery("Users.IdPass");
query.setString(0, name);
query.setString(1, password);
List<Users> users1 = query.list();
Users users = (Users) query.list();
session.getTransaction().commit();
session.close();
System.out.println(users.getUserName());
}
}
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div>
<form action="login" method="POST">
<ul>
<li>User <input type="text" name="username"><br></li>
<li>Password <input type="password" name="password"></li>
<input type="submit" value="Submit" />
</ul>
</form>
</div>
</body>
</html>
Users.java
package HibernateClasses;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
#Entity
#NamedNativeQueries({
#NamedNativeQuery(name = "Users.byId", query = "Select * from users where userId=?", resultClass = Users.class),
#NamedNativeQuery(name = "Users.all", query = "Select * from users ", resultClass = Users.class),
#NamedNativeQuery(name = "Users.IdPass", query = "Select * from users where userName=? and password=? ", resultClass = Users.class) })
public class Users {
#Id
private int userId;
private String userName;
private String password;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
console
Feb 11, 2016 12:48:19 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Archive System' did not find a matching property.
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version: Apache Tomcat/7.0.67
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built: Dec 7 2015 13:07:11 UTC
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number: 7.0.67.0
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name: Windows 8.1
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version: 6.3
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture: amd64
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home: C:\Program Files\Java\jre7
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version: 1.7.0_79-b15
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor: Oracle Corporation
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE: C:\kiko\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME: C:\Program Files\Apache Software Foundation\Tomcat 7.0
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\kiko\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Program Files\Apache Software Foundation\Tomcat 7.0
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\kiko\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Program Files\Apache Software Foundation\Tomcat 7.0\endorsed
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Feb 11, 2016 12:48:19 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Hewlett-Packard\SimplePass\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;.
Feb 11, 2016 12:48:19 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8081"]
Feb 11, 2016 12:48:19 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 637 ms
Feb 11, 2016 12:48:19 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Feb 11, 2016 12:48:19 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.67
Feb 11, 2016 12:48:20 PM org.apache.catalina.startup.TldConfig execute
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Feb 11, 2016 12:48:20 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8081"]
Feb 11, 2016 12:48:20 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Feb 11, 2016 12:48:20 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 920 ms
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Feb 11, 2016 12:48:28 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Controller.login] in context with path [/Archive_System] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: javax.persistence.EntityListeners
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1856)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1705)
at org.hibernate.cfg.annotations.reflection.JPAMetadataProvider.getDefaults(JPAMetadataProvider.java:96)
at org.hibernate.annotations.common.reflection.java.JavaReflectionManager.getDefaults(JavaReflectionManager.java:226)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1385)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1856)
at Controller.login.doPost(login.java:58)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
This line
java.lang.ClassNotFoundException: javax.persistence.EntityListeners
indicate that you miss some jar file to include in your class path or project.
You may add dependency jar file using below Maven code :
<!-- for JPA, use hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
You should change this code
#NamedNativeQueries({
#NamedNativeQuery(name = "Users.byId", query = "Select * from users where userId=?", resultClass = Users.class),
#NamedNativeQuery(name = "Users.all", query = "Select * from users ", resultClass = Users.class),
#NamedNativeQuery(name = "Users.IdPass", query = "Select * from users where userName=? and password=? ", resultClass = Users.class) })
to
#NamedQueries({
#NamedQuery(name = "Users.byId", query = "from Users u where u.userId=?"),
#NamedQuery(name = "Users.all", query = "from Users"),
#NamedQuery(name = "Users.IdPass", query = "from Users u where u.userName=? and u.password=? ") })
See example of using #NamedQuery annotation Hibernate Named Query
The Hibernate named query is way to use any query by some meaningful
name. It is like using alias names. The Hibernate framework provides
the concept of named queries so that application programmer need not
to scatter queries to all the java code.
There are two ways to define the named query in hibernate:
by annotation
by mapping file.
Hibernate Named Query by annotation
If you want to use named query in Hibernate, you need to have
knowledge of #NamedQueries and #NamedQuery annotations.
#NameQueries annotation is used to define the multiple named queries.
#NameQuery annotation is used to define the single named query.
Let's see the example of using the named queries:
#NamedQueries({
#NamedQuery(
name = "findEmployeeByName",
query = "from Employee e where e.name = :name"
)
})
About list cast: the list() returns objects like it's used in the from clause. For example in above query it returns List<Employee> that doesn't require additional casts.
I've tried to implement JPA entityManager provided by Hibernate and update my database.
I use MySQL 5.7 server, where username is "tutorial" and password is just "password". I've done some configurations and tried to simply insert a row into the "country" table with columns: id(int)(pk)(auto_inc) and country(varchar), but it don't affect my database.
In country table are already 4 rows: (1, "Poland"), (2,"Slovakia"), (3, "Ukraine") and (4, "Czech Republic").
Controller:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import pl.hibernate.basics.daos.CustomersDetailsDAO;
import pl.hibernate.basics.model.Country;
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
private CustomersDetailsDAO customersDetailsDAO;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home() {
Country country = new Country();
country.setCountry("Lithuania");
logger.info("Country Entity: " + country);
customersDetailsDAO.insertCountry(country);
return "home";
}
}
CustomersDetailsDAOImpl:
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import pl.hibernate.basics.model.Country;
#Transactional
#Component
public class CustomersDetailsDAOImpl implements CustomersDetailsDAO {
#PersistenceContext
private EntityManager em;
#Override
public void insertCountry(Country country) {
em.persist(country);
}
}
Entity Class:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="country")
public class Country {
#Id
#GeneratedValue
private int id;
#Column
private String country;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Override
public String toString() {
return "Country [id=" + id + ", country=" + country + "]";
}
}
persistence.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: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/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<tx:annotation-driven />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="tutorial" />
<property name="password" value="password" />
</bean>
<bean id="emFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="pl.hibernate.basics" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
Console output (Note logger info at the end):
sty 29, 2016 2:31:27 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:JPA Hibernate Spring WebMVC Application' did not find a matching property.
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version: Apache Tomcat/8.0.23
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built: May 19 2015 14:58:38 UTC
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number: 8.0.23.0
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name: Windows 10
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version: 10.0
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture: amd64
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home: C:\Program Files\Java\jre1.8.0_60
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version: 1.8.0_60-b27
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor: Oracle Corporation
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE: C:\Users\Adrian\Desktop\eclipse\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME: C:\Users\Adrian\Desktop\apache-tomcat-8.0.23-windows-x64\apache-tomcat-8.0.23
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\Adrian\Desktop\eclipse\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Users\Adrian\Desktop\apache-tomcat-8.0.23-windows-x64\apache-tomcat-8.0.23
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\Adrian\Desktop\eclipse\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Users\Adrian\Desktop\apache-tomcat-8.0.23-windows-x64\apache-tomcat-8.0.23\endorsed
sty 29, 2016 2:31:27 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1250
sty 29, 2016 2:31:27 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre1.8.0_60\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_60/bin/server;C:/Program Files/Java/jre1.8.0_60/bin;C:/Program Files/Java/jre1.8.0_60/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\xampp\php;;C:\Program Files (x86)\MySQL\MySQL Server 5.1\bin;C:\Program Files\MySQL\MySQL Server 5.5\bin;C:\Users\Adrian\Desktop\eclipse;;.
sty 29, 2016 2:31:27 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
sty 29, 2016 2:31:28 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
sty 29, 2016 2:31:28 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
sty 29, 2016 2:31:28 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
sty 29, 2016 2:31:28 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1372 ms
sty 29, 2016 2:31:28 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
sty 29, 2016 2:31:28 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.23
sty 29, 2016 2:31:31 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
sty 29, 2016 2:31:31 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
sty 29, 2016 2:31:32 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Fri Jan 29 14:31:32 CET 2016]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/root-context.xml]
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/persistence.xml]
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Bean 'dataSource' of type [class org.springframework.jdbc.datasource.DriverManagerDataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Bean 'org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter#e956be6' of type [class org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
WARN : org.hibernate.ejb.HibernatePersistence - HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Bean 'emFactory' of type [class org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#6441d7e2: defining beans [homeController,customersDetailsDAOImpl,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,dataSource,emFactory,transactionManager,persistenceExceptionTranslationPostProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 6254 ms
sty 29, 2016 2:31:38 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'appServlet'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'appServlet-servlet': startup date [Fri Jan 29 14:31:38 CET 2016]; parent: Root WebApplicationContext
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#472f3baa: defining beans [mvcContentNegotiationManager,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,homeController,customersDetailsDAOImpl,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,org.springframework.web.servlet.view.InternalResourceViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory#6441d7e2
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String pl.hibernate.basics.controllers.HomeController.home()
INFO : org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization completed in 1362 ms
sty 29, 2016 2:31:39 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
sty 29, 2016 2:31:39 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
sty 29, 2016 2:31:39 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 11657 ms
INFO : pl.hibernate.basics.controllers.HomeController - Country Entity: Country [id=0, country=Lithuania]
UPDATE
Now i'm able parse document clicking the link 'Next'. But only the second time the file is parsed.
I have two actions in which first i'll load the file then by clicking next button it should process parse the content from the word document. I'm using apache poi to extract contents.
Struts.xml
<package name="parsing" extends="struts-default">
<action name="moveNext" class="tryupload.NextFileParser" method="execute">
<result name="success">/parser.jsp</result>
</action>
</package>
ParsingDOCAction
package tryupload;
import java.io.File;
import java.io.FileInputStream;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletContext;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
import sun.misc.ExtensionInstallationProvider;
public class NextFileParser extends ActionSupport implements ServletContextAware{
/**
*
*/
private static final long serialVersionUID = 1678420053045158846L;
POIFSFileSystem fs = null;
ParseDocBean pdb=new ParseDocBean();
//private File[] fileList;
static int i=0;
private ServletContext servletContext;
private ArrayList<ParseDocBean> list=new ArrayList<ParseDocBean>();
public ServletContext getServletContext() {
return servletContext;
}
#Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
public String execute(){
String fileServerpath=getServletContext().getRealPath("/doc/");
System.out.println(fileServerpath);
File f=new File(fileServerpath);
File[] docs=f.listFiles();
//System.out.println(docs.length);
if(parseNext(docs))
System.out.println("parsed");
System.out.println("inside execute method");
//NextFileParser nfp=new NextFileParser();
//nfp.setFileList(docs);
//nfp.setFileList(docs);
//NextFileParser.parseNext(docs);
i++;
return SUCCESS;
}
public boolean parseNext(File[] fileList){
System.out.println(fileList.length);
System.out.println(i);
String Content=null;
try{
if(i==fileList.length){
//msg="Finished";
pdb.setMsg("Finished");
list.add(pdb);
return false;
}
else{
String fname=fileList[i].getName();
System.out.println(fname);
String basename=FilenameUtils.getBaseName(fname);
//String extension=FilenameUtils.getExtension(fname);
if(checkAlreadyExists(basename))
{
//addFieldError("content", "Already Parsed");
//str="No new Files";
pdb.setStr("No new Files");
list.add(pdb);
return false;
}
else{
try
{
fs = new POIFSFileSystem(new FileInputStream(fileList[i]));
HWPFDocument doc = new HWPFDocument(fs);
WordExtractor we = new WordExtractor(doc);
// content= we.getText();//if the extension is .doc
ParseDocBean pdb=new ParseDocBean();
System.out.println(we.getText());
pdb.setContent(we.getText());
list.add(pdb);
/*pdb.setFinishMsg("Finished");*/
we.close();
System.out.println(i);
}
catch (Exception e)
{
e.getStackTrace();
e.getMessage();
System.out.println("document file cant be parsed");
}
}
}
}
catch (Exception e) {
e.getMessage();
}
return true;
/* if(!Content.equals("")){
System.out.println(Content);}
return Content;
*/
}
public static boolean checkAlreadyExists(String basename){
boolean status=false;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/resume","root","root");
if(con!=null){
System.out.println("Connection ok");
}
String query="{call checkFileAlreadyExists(?,?)}";
CallableStatement st;
st=con.prepareCall(query);
st.setString(1, basename);
st.registerOutParameter(2, java.sql.Types.INTEGER);
st.execute();
int id=st.getInt(2);
if(id!=0){
status=true;
}
else
{
status=false;
}
con.close();
st.close();
}
catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
if(status){
System.out.println("All ready parsed");
return true;
}
else
{
return false;
}
}
}
I'm inserting some data from the extracted contents into the database and i'm checking weather the file is already parsed in the above class using the method checkAlreadyExists()
parser.jsp
<body>
<fieldset>
<s:form action="parsedoc" method="post" theme="xhtml">
<s:textfield name="cname" label="Candidate Name*"></s:textfield>
<s:textfield name="cemail" label="Email*"></s:textfield>
<s:textfield name="cNo" label="Contact No*"></s:textfield>
<s:textfield name="DOB" label="DOB*"></s:textfield>
<s:textfield name="gender" label="Gender*"></s:textfield>
<s:textfield name="mStatus" label="Marital Status*"></s:textfield>
<s:textfield name="qualification" label="Qualification*"></s:textfield>
<s:textfield name="marks" label="Score(if any)"></s:textfield>
<s:div style="display:block">
<s:reset ></s:reset><s:submit ></s:submit>
</s:div>
</s:form>
</fieldset>
<%# include file="extracted.jsp" %>
</body>
extracted.jsp
<body>
<s:div style="display:block;">
<s:if test="%{list!=null && list.size>0}">
<s:iterator value="listName">
<%-- <s:textarea name="content"><s:property value="content"/> </s:textarea> --%>
<s:div><p><s:property value="content"/></p></s:div>
<p><s:property value="str"/></p>
<p><s:property value="msg"/></p>
</s:iterator>
</s:if>
<s:else>No files found</s:else>
<s:a href="moveNext">Next<%-- <s:submit type="button" name="Next" value="Next"></s:submit> --%></s:a>
<%-- <s:text name="finishMsg"><s:property value="finishMsg"/></s:text> --%>
</s:div>
</body>
the output i'm gettin when i click the next button is as below.I want to show the the extracted contents in the parser.jsp page. But i'm not getting it.
Nov 05, 2015 10:15:08 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:tryupload' did not find a matching property.
Nov 05, 2015 10:15:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version: Apache Tomcat/8.0.24
Nov 05, 2015 10:15:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built: Jul 1 2015 20:19:55 UTC
Nov 05, 2015 10:15:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number: 8.0.24.0
Nov 05, 2015 10:15:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name: Windows 7
Nov 05, 2015 10:15:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version: 6.1
Nov 05, 2015 10:15:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture: amd64
Nov 05, 2015 10:15:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home: C:\Program Files\Java\jdk1.7.0_25\jre
Nov 05, 2015 10:15:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version: 1.7.0_25-b17
Nov 05, 2015 10:15:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor: Oracle Corporation
Nov 05, 2015 10:15:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE: E:\work space\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Nov 05, 2015 10:15:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME: C:\java\apache-tomcat-8.0.24
Nov 05, 2015 10:15:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=E:\work space\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Nov 05, 2015 10:15:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\java\apache-tomcat-8.0.24
Nov 05, 2015 10:15:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=E:\work space\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
Nov 05, 2015 10:15:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\java\apache-tomcat-8.0.24\endorsed
Nov 05, 2015 10:15:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Nov 05, 2015 10:15:08 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.7.0_25\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jdk1.7.0_25/bin/../jre/bin/server;C:/Program Files/Java/jdk1.7.0_25/bin/../jre/bin;C:/Program Files/Java/jdk1.7.0_25/bin/../jre/lib/amd64;C:\Program Files\Java\jdk1.7.0_25\bin;c:\Program Files (x86)\Microsoft SQL Server\90\Tools\binn\;c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\MySQL\MySQL Server 5.1\bin;F:\soft\soft\soft\eclipse-jee-mars-R-win32-x86_64\eclipse;;.
Nov 05, 2015 10:15:09 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8081"]
Nov 05, 2015 10:15:09 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Nov 05, 2015 10:15:09 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Nov 05, 2015 10:15:09 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Nov 05, 2015 10:15:09 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 753 ms
Nov 05, 2015 10:15:09 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Nov 05, 2015 10:15:09 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.24
Nov 05, 2015 10:15:11 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Nov 05, 2015 10:15:11 PM com.opensymphony.xwork2.config.providers.XmlConfigurationProvider info
INFO: Parsing configuration file [struts-default.xml]
Nov 05, 2015 10:15:11 PM com.opensymphony.xwork2.config.providers.XmlConfigurationProvider info
INFO: Parsing configuration file [struts-plugin.xml]
Nov 05, 2015 10:15:11 PM com.opensymphony.xwork2.config.providers.XmlConfigurationProvider info
INFO: Parsing configuration file [struts.xml]
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.ObjectFactory)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.factory.ActionFactory)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.factory.ResultFactory)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.factory.ConverterFactory)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.factory.InterceptorFactory)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.factory.ValidatorFactory)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.factory.UnknownHandlerFactory)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.FileManagerFactory)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.impl.XWorkConverter)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.impl.CollectionConverter)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.impl.ArrayConverter)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.impl.DateConverter)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.impl.NumberConverter)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.impl.StringConverter)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.ConversionPropertiesProcessor)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.ConversionFileProcessor)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.ConversionAnnotationProcessor)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.TypeConverterCreator)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.TypeConverterHolder)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.TextProvider)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.LocaleProvider)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.ActionProxyFactory)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.ObjectTypeDeterminer)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (org.apache.struts2.dispatcher.mapper.ActionMapper)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (jakarta) for (org.apache.struts2.dispatcher.multipart.MultiPartRequest)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (org.apache.struts2.views.freemarker.FreemarkerManager)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (org.apache.struts2.components.UrlRenderer)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.validator.ActionValidatorManager)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.util.ValueStackFactory)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.util.reflection.ReflectionProvider)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.util.reflection.ReflectionContextFactory)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.util.PatternMatcher)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (org.apache.struts2.util.ContentTypeMatcher)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (org.apache.struts2.dispatcher.StaticContentLoader)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.UnknownHandlerManager)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (org.apache.struts2.views.util.UrlHelper)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.util.TextParser)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (org.apache.struts2.dispatcher.DispatcherErrorHandler)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.security.ExcludedPatternsChecker)
Nov 05, 2015 10:15:11 PM org.apache.struts2.config.AbstractBeanSelectionProvider info
INFO: Choosing bean (struts) for (com.opensymphony.xwork2.security.AcceptedPatternsChecker)
Nov 05, 2015 10:15:12 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8081"]
Nov 05, 2015 10:15:12 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Nov 05, 2015 10:15:12 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3033 ms
Nov 05, 2015 10:15:23 PM org.apache.struts2.components.ServletUrlRenderer warn
WARNING: No configuration found for the specified action: 'parsedoc' in namespace: ''. Form action defaulting to 'action' attribute's literal value.
Nov 05, 2015 10:15:23 PM org.apache.struts2.components.ServletUrlRenderer warn
WARNING: No configuration found for the specified action: 'parsedoc' in namespace: ''. Form action defaulting to 'action' attribute's literal value.
E:\work space\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\tryupload\doc\
2
0
pdf extraction and searching1.doc
Connection ok
document file cant be parsed
parsed
inside execute method
Nov 05, 2015 10:15:26 PM org.apache.struts2.components.ServletUrlRenderer warn
WARNING: No configuration found for the specified action: 'parsedoc' in namespace: '/'. Form action defaulting to 'action' attribute's literal value.
Nov 05, 2015 10:15:26 PM org.apache.struts2.components.ServletUrlRenderer warn
WARNING: No configuration found for the specified action: 'parsedoc' in namespace: '/'. Form action defaulting to 'action' attribute's literal value.
E:\work space\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\tryupload\doc\
2
1
pdf extraction and searching182.doc
Connection ok
package com.programmingfree.simplepdfsearch;
import org.apache.lucene.queryParser.ParseException;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper;
import java.io.File;
import java.io.IOException;
public class SimplePDFSearch {
// location where the index will be stored.
private static final String INDEX_DIR = "src/main/resources/index";
private static final int DEFAULT_RESULT_SIZE = 100;
public static void main(String[] args) throws IOException, ParseException {
File pdfFile = new File("src/resources/SamplePDF.pdf");
IndexItem pdfIndexItem = index(pdfFile);
// creating an instance of the indexer class and indexing the items
Indexer indexer = new Indexer(INDEX_DIR);
indexer.index(pdfIndexItem);
indexer.close();
// creating an instance of the Searcher class to the query the index
Searcher searcher = new Searcher(INDEX_DIR);
int result = searcher.findByContent("Hello", DEFAULT_RESULT_SIZE);
print(result);
searcher.close();
}
//Extract text from PDF document
public static IndexItem index(File file) throws IOException {
PDDocument doc = PDDocument.load(file);
String content = new PDFTextStripper().getText(doc);
doc.close();
return new IndexItem((long)file.getName().hashCode(), file.getName(), content);
}
//Print the results
private static void print(int result) {
if(result==1)
System.out.println("The document contains the search keyword");
else
System.out.println("The document does not contain the search keyword");
}
}
package com.programmingfree.simplepdfsearch;
public class IndexItem {
private Long id;
private String title;
private String content;
public static final String ID = "id";
public static final String TITLE = "title";
public static final String CONTENT = "content";
public IndexItem(Long id, String title, String content) {
this.id = id;
this.title = title;
this.content = content;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public String getContent() {
return content;
}
#Override
public String toString() {
return "IndexItem{" +
"id=" + id +
", title='" + title + '\'' +
", content='" + content + '\'' +
'}';
}
}
package com.programmingfree.simplepdfsearch;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import java.io.File;
import java.io.IOException;
public class Indexer {
private IndexWriter writer;
public Indexer(String indexDir) throws IOException {
// create the index
if(writer == null) {
writer = new IndexWriter(FSDirectory.open(
new File(indexDir)), new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer(Version.LUCENE_36)));
}
}
/**
* This method will add the items into index
*/
public void index(IndexItem indexItem) throws IOException {
// deleting the item, if already exists
writer.deleteDocuments(new Term(IndexItem.ID, indexItem.getId().toString()));
Document doc = new Document();
doc.add(new Field(IndexItem.ID, indexItem.getId().toString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field(IndexItem.TITLE, indexItem.getTitle(), Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field(IndexItem.CONTENT, indexItem.getContent(), Field.Store.YES, Field.Index.ANALYZED));
// add the document to the index
writer.addDocument(doc);
}
/**
* Closing the index
*/
public void close() throws IOException {
writer.close();
}
}
package com.programmingfree.simplepdfsearch;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Searcher {
private IndexSearcher searcher;
private QueryParser contentQueryParser;
public Searcher(String indexDir) throws IOException {
// open the index directory to search
searcher = new IndexSearcher(IndexReader.open(FSDirectory.open(new File(indexDir))));
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
// defining the query parser to search items by content field.
contentQueryParser = new QueryParser(Version.LUCENE_36, IndexItem.CONTENT, analyzer);
}
/**
* This method is used to find the indexed items by the content.
* #param queryString - the query string to search for
*/
public int findByContent(String queryString, int numOfResults) throws ParseException, IOException {
// create query from the incoming query string.
Query query = contentQueryParser.parse(queryString);
// execute the query and get the results
ScoreDoc[] queryResults = searcher.search(query, numOfResults).scoreDocs;
if(queryResults.length>0)
return 1;
else
return 0;
}
public void close() throws IOException {
searcher.close();
}
}
1
parsed
inside execute method
Nov 05, 2015 10:15:28 PM org.apache.struts2.components.ServletUrlRenderer warn
WARNING: No configuration found for the specified action: 'parsedoc' in namespace: '/'. Form action defaulting to 'action' attribute's literal value.
Nov 05, 2015 10:15:28 PM org.apache.struts2.components.ServletUrlRenderer warn
WARNING: No configuration found for the specified action: 'parsedoc' in namespace: '/'. Form action defaulting to 'action' attribute's literal value.
In struts.xml you are delegating the call of nextMove to tryupload.NextFileParser class and method parseNext. Struts will try to find a method named parseNext without any arguments. And in NextFileParser class you defined a parseNext method that needs an array of File.