So the problem is, that whenever I run my local tomcat server it runs the welcome servlet 3 times. It doesn't matter what is inside the doGet method, it might be only System.out.println("something"); and it will print 3 times: "something".
When the server is running and I'm calling the same servlet via web browser it works OK. I believe something is wrong with initialization, but I have no idea what and I couldn't find any solution so far. I have tried to build a completely new project, copy all classes and .xml files, but the result is exactly the same.
Edit: I'm using Itnellij UE.
Edit2: When I stop local server I'm getting this warning:
> 18-Dec-2018 21:41:23.388 WARNING [main]
> org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads
> The web application [ROOT] appears to have started a thread named
> [Abandoned connection cleanup thread] but has failed to stop it. This
> is very likely to create a memory leak. Stack trace of thread:
> java.lang.Object.wait(Native Method)
> java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:144)
> com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:70)
> java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
> java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
> java.lang.Thread.run(Thread.java:748)
These are my classes and xmls:
Servlet:
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 java.io.IOException;
import java.sql.SQLException;
import java.util.List;
#WebServlet(name = "Servlet1", urlPatterns = {"/servlet1"})
public class Servlet1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String numberOfSolutions = getServletContext().getInitParameter("number-solutions");
int numberOfRows = Integer.parseInt(numberOfSolutions);
List<Solution> allSolutions;
Solution solution = new Solution();
Solution solution1 = new Solution("newServlet", 2, 3);
System.out.println();
try {
solution1.saveSolutionToDb();
allSolutions = solution.getAllSolutions(numberOfRows);
request.setAttribute("solutionsList", allSolutions);
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Solution:
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
public class Solution {
private int id;
private Timestamp created;
private Timestamp updated;
private String description;
private int exerciseId;
private long usersId;
public Solution() {
}
public Solution(String description, int exerciseId, long usersId) {
this.description = description;
this.exerciseId = exerciseId;
this.usersId = usersId;
}
public void saveSolutionToDb() throws SQLException {
String query = "INSERT INTO solution(created,description,exercise_id,users_id) VALUES(NOW(),?,?,?);";
PreparedStatement preparedStatement = DbUtil.getConnection().prepareStatement(sql);
preparedStatement.setString(1, this.description);
preparedStatement.setInt(2, this.exerciseId);
preparedStatement.setLong(3, this.usersId);
preparedStatement.executeUpdate();
DbUtil.getConnection().close();
}
public ArrayList<Solution> getAllSolutions(int rows) throws SQLException {
ArrayList<Solution> listOfLoadedSolutions;
String query = "SELECT * FROM solution ORDER BY id DESC LIMIT " + rows + ";";
PreparedStatement preparedStatement = DbUtil.getConnection().prepareStatement(query);
listOfLoadedSolutions = getSolutions(preparedStatement);
DbUtil.getConnection().close();
return listOfLoadedSolutions;
}
private ArrayList<Solution> getSolutions(PreparedStatement preparedStatement) throws SQLException {
ArrayList<Solution> allLoadedSolutions = new ArrayList<>();
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Solution loadedSolution = new Solution();
loadedSolution.id = resultSet.getInt("id");
loadedSolution.created = resultSet.getTimestamp("created");
loadedSolution.updated = resultSet.getTimestamp("updated");
loadedSolution.description = resultSet.getString("description");
loadedSolution.exerciseId = resultSet.getInt("exercise_id");
loadedSolution.usersId = resultSet.getLong("users_id");
allLoadedSolutions.add(loadedSolution);
}
return allLoadedSolutions;
}
}
Connection:
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class DbUtil {
private static DataSource ds;
public static Connection getConnection() throws SQLException {
return getInstance().getConnection();
}
private static DataSource getInstance() {
if (ds == null) {
try {
Context ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/szkola_programowania");
} catch (NamingException e) {
e.printStackTrace();
}
}
return ds;
}
}
context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/szkola_programowania"
auth="Container"
type="javax.sql.DataSource"
username="user"
password="pass"
driverClassName="com.mysql.cj.jdbc.Driver"
connectionProperties="useUnicode=yes;characterEncoding=utf8;"
url="jdbc:mysql://localhost:3306/szkola_programowania"
maxTotal="100"
maxIdle="30"
maxWaitMillis="10000" />
</Context>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>servlet1</welcome-file>
<welcome-file>default.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>number-solutions</param-name>
<param-value>5</param-value>
</context-param>
</web-app>
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pl.coderslab</groupId>
<artifactId>webExample</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
</dependency>
</dependencies>
</project>
Related
I'm making a webapp using JSP and MYSQL.
I have set up a connection pool and used it in a Servlet, but I cannot access it.
I had to create manually the "lib" folder inside WEB-INF to put the database connector and the META-INF folder to put the context.xml file, because those folders were not there at the begining.
I'm following a tutorial from 2016 so I don't know how different it is now.
Thanks in advance for your help.
Src folder:
Main files:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
</web-app>
context.xml
<Context>
<Resource name="jdbc/wishes" auth="Container" type="javax.sql.DataSource" maxActive="15" maxIdle="3" maxWait="5000" username="root" password="" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/jee">
</Resource>
</Context>
Servlet
package com.gabit.dev.makeawish.controllers;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
#WebServlet(name = "ServletDatabase", value = "/ServletDatabase")
public class ServletDatabase extends HttpServlet {
private static final long serialVersionUID = 1L;
#Resource(name = "jdbc/wishes")
private DataSource myPool;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter output = response.getWriter();
response.setContentType("text/plain");
Connection myConnection = null;
Statement myStatement = null;
ResultSet myResult = null;
try {
myConnection = myPool.getConnection();
String query = "SELECT * FROM wishes";
myStatement = myConnection.createStatement();
myResult = myStatement.executeQuery(query);
while (myResult.next()) {
String title = myResult.getString(2);
output.println(title);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Error
java.lang.NullPointerException: Cannot invoke "javax.sql.DataSource.getConnection()" because "this.myPool" is null
at com.gabit.dev.makeawish.controllers.ServletDatabase.doGet(ServletDatabase.java:31)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:683)
...
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)
I am trying to run a webapp called TestServer2 in the Tomcat 7 running Ubuntu 14.04 but it gave failed as FAIL - Application at context path /TestServer2-0.0.1-SNAPSHOT could not be started. I followed an example online here and I tested it on my local Tomcat server instance running with Eclipse and it works just fine but when I deployed it into the server Ubuntu 14.04 with Tomcat 7 it gave me that error. Below are the codes I used:
web.xml
<?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>TestServer2</display-name>
<context-param>
<param-name>resteasy.resources</param-name>
<param-value>com.heyho.rest.JSONService</param-value>
</context-param>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>TestServer2</groupId>
<artifactId>TestServer2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>JBoss repository</id>
<url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>2.2.1.GA</version>
</dependency>
<!-- <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxb-provider</artifactId>
<version>2.2.0.GA</version> </dependency> -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>2.2.1.GA</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
JSONService.java
package com.heyho.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
#Path("/service")
public class JSONService {
#POST
#Path("/post")
#Consumes("application/json")
public Response createProductInJSON(UserInput input) {
String result = "User input submitted : " + input;
return Response.status(201).entity(result).build();
}
}
UserInput.java
package com.heyho.rest;
public class UserInput {
int counter;
String attribute;
String publicKey;
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
#Override
public String toString() {
return "User Input = counter " + counter + " attribute = " + attribute + " public key = " + publicKey ;
}
}
ClientPost.java
package com.heyho.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import com.google.gson.Gson;
public class ClientPost {
public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
try {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (certificate, authType) -> true).build();
CloseableHttpClient client = HttpClients.custom()
.setSslcontext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
HttpPost postRequest = new HttpPost(
"http://somewebsite.de:50064/TestServer2/service/post");
Gson gson = new Gson();
Map<String,Object> test = new HashMap<String,Object>();
test.put("counter", 1000);
test.put("attribute", "user attribute");
test.put("publicKey", "user public key");
String json = gson.toJson(test);
StringEntity input = new StringEntity(json);
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = client.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Is there something wrong with my code? Also how do I debug the Tomcat 7 running on the server so that it could give me some logs or error?
UPDATE
I have found the error in log something like this:
SEVERE: Exception sending context initialized event to listener instance of class org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
java.lang.UnsupportedClassVersionError: com/heyho/rest/JSONService : Unsupported major.minor version 52.0 (unable to load class com.heyho.rest.JSONService)
I'm not sure what is the problem here. I have declared JSONService on my web.xml but it still gives me error
"Unsupported major.minor version 52.0" means that the class com.heyho.rest.JSONService has been compiled for a newer version of Java as you try to run it with. Upgrade the JVM to 1.8 and it should work. Alternatively, you can make sure to compile the class for the version of the JVM.
I am trying to make a maven login application using hibernate to persist the data onto a mysql database. I am deploying the application on a glassfish server. I am able to start the server and fill in data on the html form but once I submit the form, I get the following error logs:
2016-11-21T22:40:05.371-0500|Info: HHH000412: Hibernate Core {5.2.4.Final}
2016-11-21T22:40:05.379-0500|Info: HHH000206: hibernate.properties not found
2016-11-21T22:40:05.385-0500|Info: HHH000021: Bytecode provider name : javassist
2016-11-21T22:40:05.471-0500|Warning: StandardWrapperValve[RegisterServlet]:Servlet.service() for servlet RegisterServlet threw exception
java.lang.ExceptionInInitializerError
at model.RegisterService.isExistingUser(RegisterService.java:8)
at model.RegisterServlet.doPost(RegisterServlet.java:59)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [C:\Users\marvi\workspace1\LoginApp\hibernate.cfg.xml]
at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:53)
at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
at org.hibernate.cfg.Configuration.configure(Configuration.java:258)
at model.HibernateUtil.<clinit>(HibernateUtil.java:15)
... 32 more
I have moved the location of the hibernate.cfg.xml file from root folder, to the resource folder and also into the resource folder but problem prevails I have also added path of the cfg.xml file to the .configure() method, but did not work. I have looked at all the previously asked questions:
ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml] in project root folder 2
Hibernate ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml] IntelliJ 1
org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [/HibernateTest/src/hibernate.cfg.xml] 1
HTTP Status 500 - org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]
but non of the solutions given fix my problem.
image of Project structure
Below is my code for my entity class.
package model;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.annotations.NamedQueries;
import org.hibernate.annotations.NamedQuery;
#Entity
#NamedQueries({
#NamedQuery(name="getUserByUserNameAndPassword",
query="SELECT u FROM User u WHERE u.userName = :uname AND u.password = :pword")
})
public class User{
#Id
private Long userId;
private String firstName;
private String lastName;
private String userName;
private String password;
public User() {
}
//Getters and setters
}
Below is by hibernate util class.
package model;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
private static final ServiceRegistry serviceRegistry;
static {
Configuration conf = new Configuration();
conf.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
try {
sessionFactory = conf.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("Initial SessionFactory creation failed." + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Below is my hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="show_sql">true</property>
<mapping resource="User.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
My servlet class
package model;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RegisterServlet
*/
#WebServlet("/register")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RegisterServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String fName = request.getParameter("firstName");
String uName = request.getParameter("userName");
String lName = request.getParameter("lastName");
String password = request.getParameter("password");
User user = new User();
user.setFirstName(fName);
user.setLastName(lName);
user.setUserName(uName);
user.setPassword(password);
RegisterService rs = new RegisterService();
if (!rs.isExistingUser(user.getUserName())) {//if user does NOT exist, then we register them
rs.registerUser(user);//register the user first
out.println("<h1>Registration Successful</h1>");
out.println("To login with new UserId and Password<a href=login.jsp>Click here</a>");
out.println("</center>");
out.println("</body>");
out.println("</html>");
out.close();
}else{//if user already exist
out.println("<h1>Username Exists!!</h1>");
out.println("To try again<a href=register.jsp>Click here</a>");
//RequestDispatcher d = request.getRequestDispatcher("index.jsp");
//d.forward(request, response);
}
//doGet(request, response);
}
}
My service class:
package model;
import org.hibernate.Session;
public class RegisterService {
public boolean isExistingUser(String uname) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
User user = (User) session.getNamedQuery("getUser").setParameter("uname", uname).uniqueResult();
session.getTransaction().commit();
session.close();
if (user.getUserName() != uname) {
return false;
}
return true;
}
public void registerUser(User user) {
if (!isExistingUser(user.getUserName())) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.saveOrUpdate(user);
session.getTransaction().commit();
session.close();
}
}
}
and finally my pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.marv.servelet</groupId>
<artifactId>LoginApp</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>LoginApp Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.4.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
</dependency>
</dependencies>
<build>
<finalName>LoginApp</finalName>
</build>
</project>
Put your Hibernate.cfg.xml in src folder of your project and update the code as below and check if it works.
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
This will automatically fetch the .cfg file without mentioning it.
I tried to import the Gson library from Google using Maven but when I run my web application, I receive error that the Gson class isn't found. I tried to put provided for the scope of the Gson library but it didn't do anything.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>Skeleton</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
TestServlet.java
package servlets;
import com.google.gson.Gson;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Philippe on 2016-05-10.
*/
#WebServlet(name = "/TestServlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> list = new ArrayList<String>() ;
list.add("item1");
list.add("item2");
Gson gson = new Gson() ;
String json = gson.toJson(list) ;
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
log
java.lang.ClassNotFoundException: com.google.gson.Gson at
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1305)
at
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1139)
at servlets.TestServlet.doGet(TestServlet.java:34) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:622) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
Is there anything I'm missing ?
Just try by removing <scope>compile</scope> as documented in the site.
<!-- http://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
I'm trying to run a simple servlet/mysql webapp using tomcat server in my eclipse.
when I try to connect to the database from a servlet, I get the following error:
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create
PoolableConnectionFactory (Access denied for user ''#'localhost' (using password: YES))
below is the script that I executed:
The servlet:
import java.io.IOException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class EmployeeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Resource(name = "jdbc/testDB")
DataSource ds;
public EmployeeServlet() {
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
Connection con = ds.getConnection();
Statement stmt = con.createStatement();
String query = "select * from Employee";
ResultSet rs = stmt.executeQuery(query);
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.print("<center><h1>Employee Details</h1></center>");
out.print("<html><body>");
out.print("<table border=\"1\" cellspacing=10 cellpadding=5>");
out.print("<tr><th>Employee ID</th>");
out.print("<th>Employee Name</th>");
out.print("<th>Salary</th>");
out.print("<th>Department</th></tr>");
while (rs.next()) {
out.print("<tr>");
out.print("<td>" + rs.getInt("emp_id") + "</td>");
out.print("<td>" + rs.getString("emp_name") + "</td>");
out.print("<td>" + rs.getDouble("salary") + "</td>");
out.print("<td>" + rs.getString("dept_name") + "</td>");
out.print("</tr>");
}
out.print("</table></body></html>");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
content of context.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<Context crossContext="true">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/testDB" auth="Container"
type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/mysql">
</Context>
try connecting to mysql from any other tool / from command prompt with all the information you used in your code to connect to the same. Try including the port also in the connection url. Default port is 3306
Use mysql's GRANT query to give you permissions to access the database if you are accessing db from remote client.
seems port number missing in the url:
jdbc:mysql://localhost:<port>/mysql