NullPointerException in con.createStatement() in servlet - eclipse

I am using eclipse kepler IDE.
I am getting java.lang.nullpointerexception and i know the reason because i am getting null in con object and con is used to call a method createStatement() which is throwing this exception.
I jst want to know why this con object accessing null from MyListener.java through getAttribute() method.
I have created msaccess DB and datasource named servletTest. But i don't know
why con is accessing null that's why it is giving exception.
Exception is given below:
Feb 05, 2014 11:48:12 AM org.apache.catalina.core.AprLifecycleListener init
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.8.0\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre8/bin/client;C:/Program Files/Java/jre8/bin;C:/Program Files/Java/jre8/lib/i386;C:\Windows\System32;C:\Program Files\Java\jdk1.8.0\bin;C:\Users\praveen\Desktop\eclipse;;.
Feb 05, 2014 11:48:12 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:advanced java' did not find a matching property.
Feb 05, 2014 11:48:12 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Feb 05, 2014 11:48:12 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Feb 05, 2014 11:48:12 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1175 ms
Feb 05, 2014 11:48:12 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Feb 05, 2014 11:48:12 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.50
Feb 05, 2014 11:48:14 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Feb 05, 2014 11:48:14 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Feb 05, 2014 11:48:14 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1189 ms
java.lang.NullPointerException
at com.student.servletcontextevent.FetchData.doGet(FetchData.java:47)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:409)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1044)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:744)
**inde.html**
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
fetch records
</body>
</html>
**FetchData**
package com.student.servletcontextevent;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletContext;
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 FetchData
*/
#WebServlet("/FetchData")
public class FetchData extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public FetchData() {
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.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
// Retrieving connection object from ServletContext object
ServletContext ctx = getServletContext();
Connection con = (Connection) ctx.getAttribute("mycon");
// retieving data from emp table
Statement ps = con.createStatement();
ResultSet rs = ps.executeQuery("Select * from emp");
while (rs.next()) {
out.print("<br>" + rs.getString(1) + " " + rs.getString(2));
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
out.close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
**MyListener**
package com.student.servletcontextevent;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
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 MyListener
*/
#WebServlet("/MyListener")
public class MyListener extends HttpServlet implements ServletContextListener {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public MyListener() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see ServletContextListener#contextDestroyed(ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
/**
* #see ServletContextListener#contextInitialized(ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent event) {
// TODO Auto-generated method stub
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String dataSourceName = "servletTest";
String dbUrl = "jdbc:odbc:" + dataSourceName;
Connection con=DriverManager.getConnection(dbUrl);
//storing connection object as an attribute in ServletContext
ServletContext ctx=event.getServletContext();
ctx.setAttribute("mycon", con);
}catch(Exception e){e.printStackTrace();}
}
/**
* #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 {
// TODO Auto-generated method stub
}
}

Your listener class shouldn't extend HttpServlet, since it's not a servlet, but only a ServletContextListener. And as such, it should be annotated with #WebListener, and not with #WebServlet.
That said, you shouldn't use a single database connection in your webapp since, obviously, if two requests are handled concurrently, both will the use the same connection and will thus be unable to do their transactional work correctly.
Read the documentation of your servlet container to understand how to properly create a DataSource and access it from the servlets (see http://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html for Tomcat). Each request handling method should get a connection from the DataSource, use it, then close the connection. Also, don't use the JDBC/ODBC bridge, which is buggy, slow and completely obsolete. Use the JDBC driver for your database. Every database on earth has a JDBC driver these days.
A side note to finish: whether you're using Eclipse, NetBeans or Notepad to write your code has nothing to do with the exception you're getting, at runtime, once your code is executed inside your web container. The IDE is completely irrelevant to your question.

Are you sure you can connect to your database?
My guess is 'con' is null in FetchData servlet because an exception is thrown in MyListener when connecting to database or MyListener is never used at all.
Indeed database connection should not be managed programmatically in your application, if you google for 'tomc1t database jndi' you should find a great tutorial.

Just to add more to #JB Nizet's correct answer..
Reasons for null pointer exception on database connection:
1) Not able to access database.
2) database access might require username and password which is not supplied or incorrect.
3) Wrong database name/url.
And just some suggestions :
1) Why are you creating connection object in listener? You can create them in seperate java file and access those in your servlets and not listeners.
2)Why are you saving connection object(con) in servlet context? Makes no sense to me.. Since you are sure that your application uses single database, you can make connection object static, and you can access it just by classname.

Related

Hibernate and Eclipse error

I'm creating a simple web application with a register form, and I have used Hibernate. But i have this kind of error:
this is the code:
AddUser.java
import java.io.IOException;
import javax.imageio.spi.ServiceRegistry;
import javax.security.auth.login.Configuration;
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;
#WebServlet("/CreateUser.do")
public class AddUser extends HttpServlet {
private static final long serialVersionUID = 1L;
public AddUser() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Configuration config = new Configuration().configure("hibernate.cfg.xml");
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("login"), request.getParameter("password"));
session.save(u);
session.getTransaction().commit();
session.close();
RequestDispatcher view = request.getRequestDispatcher("useradd.jsp");
view.forward(request, response);
}
}
This is the error: ERROR
How can I do to solve this problem? Thanks you!
#LuisMuñoz
I add also the error if someone want to see it directly.
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Servlet execution threw an exception
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
javax.servlet.ServletException: Servlet execution threw an exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.lang.Error: Unresolved compilation problems:
Cannot instantiate the type Configuration
The method configure() is undefined for the type Configuration
The method getProperties() is undefined for the type Configuration
The method buildSessionFactory(ServiceRegistry) is undefined for the type Configuration
AddUser.doPost(AddUser.java:32)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.
My Eclipse Page:
ECLIPSE
From the error it looks like there is no method configure for Configuration object. Check the javadocs https://docs.oracle.com/javase/9/docs/api/index.html?javax/security/auth/login/Configuration.html

Connect KafkaProducer using Servlet

I am trying to connect KafkaProducer using servlet and setup my project in eclipse. But when i run KafkaProducer i get an exception:
org.apache.catalina.core.StandardWrapperValve invoke SEVERE:
Servlet.service() for servlet [simple_kafka.SimpleProducer] in context
with path [/kafka_web] threw exception [Servlet execution threw an
exception] with root cause java.lang.ClassNotFoundException:
org.apache.kafka.clients.producer.KafkaProducer at
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1291)
at
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119)
at simple_kafka.SimpleProducer.doPost(SimpleProducer.java:56) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:661) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:742) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
my KafkaProducerServlet is as follow:
package simple_kafka;
import java.io.IOException;
import java.util.Properties;
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.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
//import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
/**
* Servlet implementation class SimpleProducer
*/
#WebServlet("/producer")
public class SimpleProducer extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public SimpleProducer() {
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
doGet(request, response);
response.getWriter().append("Served at: ").append(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG);
String topicName = "ReplicaTopic";
String key = "Key1";
String value = "Value-1";
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.1.59:9092,192.168.1.59:9093");
props.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
KafkaProducer<String, String> producer = new KafkaProducer <String, String>(props);
try {
ProducerRecord<String, String> record = new ProducerRecord<>(topicName,key,value);
producer.send(record);
producer.close();
}
catch(Exception e) {
response.getWriter().append("Exception at: ").append((CharSequence) e);
}
// response.sendRedirect("/consumer");
}
}
I had Included Following JAR's in BuildPath of project Property:
Kafka 2.12-0.11.0.1.jar
kafka-clients-0.11.0.1.jar
slf4j-api-1.7.25.jar
After day long searching i found that you need to include the JAR files WEB-INF-> lib folder and you need to delete your server from eclipse & reconfigured it. After doing that i am able to run the KafkaProducer.

Tomcat Class Not Found - Servlet

I am having a strange problem in deploying a basic web app through Eclipse and Tomcat
The error -
SEVERE: Allocate exception for servlet DeCommServlet
java.lang.ClassNotFoundException: com.authentication.DeCommServlet
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
However, the application still gets to the DeCommServlet doPost() method and tomcat stays deployed but with that error.
Servlet:
<servlet>
<servlet-name>DeCommServlet</servlet-name>
<servlet-class>com.authentication.DeCommServlet</servlet-class>
</servlet>
<!-- Servlet Mappings -->
<servlet-mapping>
<servlet-name>DeCommServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
The servlet class is the correct link but still getting this error. I have nothing in any of the lib folders, but in the application properties I have the Apache Tomcat Lib added in Build Path >> Libraries
Has anyone seen this before?
Code for DeCommServlet:
#WebServlet("/DeCommServlet")
public class DeCommServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public DeCommServlet() {
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
System.out.println("sdf");
System.out.println("ddd");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.getUserPrincipal().getName();
response.sendRedirect("http://www.google.com");
}
New Class Path1
This is how your webapp should look like :
> DeCommGlobal
> |-->src
> |-->com
> |-->authentication
> |-->DeCommServlet.java
> |-->META-INF
> |-->WEB-INF
> |-->classes
> |-->lib
It was the deployment assembly that was causing the issue. Added the lib folder and we are good to go! Thanks

Run servlet on glassfish server prompts for master password and run fails

I have written a simple HelloServlet as follows.
import java.io.IOException;
import java.io.PrintWriter;
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 HelloServlet
*/
#WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HelloServlet() {
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.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>Hello</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1>Hello</H1>\n" +
"</BODY></HTML>");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
I have GlassFish 3.1 installed in the Java EE perspective in Eclipse.
Whenever I try and run the servlet clicking on "run on server" on the server it comes up with the following message:
This domain requires an administrative password to be set before the
domain can be started. Please specify an administrative password. The
Master Password is required to start the domain. No console, no
prompting possible. You should either create the domain with
--savemasterpassword=true or provide a password file with the --passwordfile option.
Command start-domain failed.
There is always a default master password "changeit" for glassfish. Why is it prompting me with this message ?

eclipse delete servlet with web.xml entries

am using Eclipse's New->Servlet wizard thereby having auto-generated servlet and servlet-mapping entries ready for me. But when I select a servlet's java file and delete it, the corresponding entries in web.xml don't get deleted.
How do I do this?
I would imagine just edit the web.xml file and delete the entries. It's likely by design that they are not automatically deleted when you delete the servlet.
How about using Annotations? You don't have to take care of any configuration in web.xml for this.
package com.inventwheel.servlet;
import java.io.IOException;
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 DeleteMe
*/
#WebServlet(description = "DeleteMe Servlet", urlPatterns = { "/DeleteMe" })
public class DeleteMe extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public DeleteMe() {
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 {
// TODO Auto-generated method stub
}
}