NullPointerException caused by not accessing database from JSP - java

I am working on a project that is accessing PostgreSQL with a jdbc driver and process this data through a middleware and finally displays/updates via jsp pages. Using Eclipse I created a Dynamic Web Project. Then I have written code for all back-end and middleware operations. I can access database from static context (I mean main method of java sources). I can also use my java resources (e.g displaying) from jsp if I don't call any methods that are accessing database. But when I try to access database, it doesn't work and gives me a null pointer exception.
<jsp:useBean id="user" class="dbActionManagement.UserData" scope="session"/>
<jsp:setProperty name="user" property="*"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>next page</title>
</head>
<body>
You entered<BR>
Name: <%= user.getUsername() %><BR>
Email: <%= user.getEmail() %><BR>
Age: <%= user.getAge() %><BR>
</body>
</html>
This gives me:
SEVERE: Servlet.service() for servlet [jsp] in context with path
[/GNYSweb] threw exception [java.lang.NullPointerException] with root
cause java.lang.NullPointerException at
dbActionManagement.OfficerManager.getTotalPoint(OfficerManager.java:494)
at dbActionManagement.UserData.getUsername(UserData.java:28) at
org.apache.jsp.NextPage_jsp._jspService(NextPage_jsp.java:80) at
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
at
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown
Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown
Source) at java.lang.Thread.run(Unknown Source)
Also java class that I am using for this is UserData and method getUserName()
public String getUsername() {
int a = new OfficerManager().getTotalPoint("a");
return new Integer(a).toString();
}
OfficerManager has a default constructor and getTotalPoint is
public int getTotalPoint(String officerId){
int point = 0;
ResultSet results = null;
try {
if(DBConnection.db.isClosed()){ // problem is caused by this line
DBConnection.connect();
}
Statement sql = DBConnection.db.createStatement();
String sqlText = "select point from officers ";
sqlText += " where sicilno = '" + officerId + "'";
results = sql.executeQuery(sqlText);
} catch (SQLException e) {
e.printStackTrace();
}
if(results != null)
try {
while(results.next()){
point = (int) results.getDouble("point");
}
} catch (SQLException e) {
e.printStackTrace();
}
return point;
}
I have added postgreSQL jdbc driver to my build path. Also I included same jdbc driver in the lib folder of Tomcat. Also I am using an instance of Tomcat v7.0 at localhost and the location of this is [workspace metadata]

I understand the problem, it is basically I was trying to reach Connection object that is null. I use static objects for accessing database, I forgot to initialize them before using. There are several solutions for this, the most basic one is to write another method in UserData class called startConnection()
public void startConnection(){
new DBConnection("myDBName", "myUserName", "myPassword");
}
and call this method from jsp pages
...
<body>
<% user.startConnection(); %>
Name: <%= user.getUsername() %><BR>
</body>
...
That way I can initialize my DBConnection class instances properly before using them. Thanks for your help.

Avoid checking if the db is closed before connection is created, comment out:
//if(DBConnection.db.isClosed()){ // problem is caused by this line
DBConnection.connect();
// }
And then close the connection after using it and when an exception occurs. Your exception block should be changed to;
catch (SQLException e)
{
e.printStackTrace();
if((DBConnection !=null) && DBConnection.db !=null && !DBConnection.db.isClosed())
{
BConnection.db.close();
}
}
And also close it in the try block straight after usage.
As rule of thumb - alway check if the connection is not null before attempt closing it.
try doing something like this:
if((DBConnection !=null) && DBConnection.db !=null && DBConnection.db.isClosed())
{
DBConnection.connect();
}

Related

Failed to connect MySQL in IDEA 12.1.4

I had learn javascript on the base of code of my web. Then, I tried to develop a new web but failed. After google, I still don't have clues. So I ask for help here. Thanks for advance.
My IDEA is 12.1.4. The install process is:
1) I make new project by selecting "JavaEE Web Module";
2) I then copy previously java script to deal with mysql, and a part of code would be listed below;
package inhouse;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;
public class DBTool {
private DataSource ds = null;
private Connection conn = null;
private Statement stm = null;
private ResultSet rs = null;
private Context ctx = null;
public DBTool() throws NamingException{
this("editingphosphorylation");
}
public DBTool(String dbName) throws NamingException{
try{
ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/" + dbName);
}
catch (NamingException e) {
throw new NamingException("Can't get DataSource from pool: " + e.getMessage());
}
}
public Connection getConnection() throws SQLException{
conn = ds.getConnection();
return conn;
}
......
}
3) Add "resource-ref" to WEB-INF/web.xml;
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/editingphosphorylation</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
4) Download "mysql-connector-java-5.1.40-bin.jar", and put it to WEB-INF/lib;
5) With "View-Tool Windows-Database", I confirm mysql database could be accessed;
6) But when start tomcat, it output following error:
HTTP Status 500 - An exception occurred processing JSP page /geneList.jsp at line 26
type Exception report
message An exception occurred processing JSP page /geneList.jsp at line 26
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /geneList.jsp at line 26
23:
24: try{
25: db = new DBTool();
26: conn = db.getConnection();
27: //Class.forName("com.mysql.jdbc.Driver").newInstance();
28: //Connection conn = java.sql.DriverManager.getConnection("jdbc:mysql://localhost:3306/editingphosphorylation","2pm","editingphosphorylation");
29: pst = conn.prepareStatement("select * from gene_sequence where geneName = ?");
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
javax.servlet.ServletException: org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:916)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:845)
org.apache.jsp.geneList_jsp._jspService(geneList_jsp.java:147)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1452)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
inhouse.DBTool.getConnection(DBTool.java:39)
org.apache.jsp.geneList_jsp._jspService(geneList_jsp.java:85)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(JdbcOdbcDriver.java:524)
sun.jdbc.odbc.JdbcOdbcDriver.knownURL(JdbcOdbcDriver.java:493)
sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(JdbcOdbcDriver.java:307)
java.sql.DriverManager.getDriver(DriverManager.java:262)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1437)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
inhouse.DBTool.getConnection(DBTool.java:39)
org.apache.jsp.geneList_jsp._jspService(geneList_jsp.java:85)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Any geneList.jsp is like this
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# page import="inhouse.*, java.sql.*" %>
<%# page import="java.io.*" %>
<html>
<head>
<title>get gene list</title>
</head>
<body>
<% String geneName = request.getParameter("geneName");
DBTool db;
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try{
db = new DBTool();
conn = db.getConnection();
//Class.forName("com.mysql.jdbc.Driver").newInstance();
//Connection conn = java.sql.DriverManager.getConnection("jdbc:mysql://localhost:3306/editingphosphorylation","2pm","editingphosphorylation");
pst = conn.prepareStatement("select * from gene_sequence where geneName = ?");
pst.setString(1, geneName);
rs = pst.executeQuery();
if(rs.next()){
rs.beforeFirst();%>
<table>
<th>
<td>Gene Name</td><td>Transcript Name</td><td>DNA Sequence</td><td>Protein Sequence</td>
</th>
<%while(rs.next()){
String geneNameRetrieve = rs.getString("geneName");
String transcriptNameRetrieve = rs.getString("transcriptName");
String dnaSequenceRetrieve = rs.getString("dnaSequence");
String proteinSequenceRetrieve = rs.getString("proteinSequence"); %>
<tr>
<td><%=geneNameRetrieve%></td><td><%=transcriptNameRetrieve%></td><td><%=dnaSequenceRetrieve%></td><td><%=proteinSequenceRetrieve%></td>
</tr><%
}%>
</table>
<%}else{%>
<div>No data.</div>
<%}
DBTool.close(rs, pst);
}finally {
DBTool.close(conn);
}%>
</body>
</html>
Compare with previously project, and according to google, I found the new project lack META-INF directory, so I make a new directory in web, and put a new context.xml into it.
<?xml version='1.0' encoding='utf-8'?>
<Context path="/">
<Loader delegate="true" />
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/editingprosphorylation" auth="Container" type="javax.sql.DataSource"
maxActive="555" maxIdle="50" maxWait="10000"
timeBetweenEvictionRunsMillis="60000"
username="2pm" password="editingprosphorylation" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/editingprosphorylation"/>
</Context>
However, it doesn't work. After google, I hardly don't know how to do, Any suggestion would be grateful!
Typo:
editingphosphorylation (editingpHosphorylation)
editingprosphorylation (editingpRosphorylation)

Trying to call a servlet when loading a jsp

I am building a simple Train booking system, now i am trying to call a servlet once i open a jsp to select data from the database then return back to the same servlet, but i keep getting errors.
this is my trip.jsp
<body>
<% if ((request.getAttribute("trips") == null)) {
%>
<jsp:include page="/trips" flush="true" />
<% } %>
<table>
<tr>
<th>Trip Number</th>
<th>Train Number</th>
<th>Source</th>
<th>Destination</th>
<th>Departure Time</th>
<th>Arrival Time</th>
<th>Date</th>
<th>Reserved Seats</th>
<th>Price</th>
</tr>
<%
//ArrayList list = new ArrayList();
List trip = new ArrayList();
Iterator viewTrip;
if(request.getAttribute("trips")!=null && request.getAttribute("trips")!=""){
List allTrips = (ArrayList)request.getAttribute("trips");
Iterator itr = allTrips.iterator();
while(itr.hasNext()){
trip = (ArrayList)itr.next();
viewTrip = trip.iterator();
%>
<tr>
<%
while(viewTrip.hasNext()){
%>
<td>
<%=viewTrip.next()%>
</td>
<%
}
%>
</tr>
<%
}
}
%>
</table>
</body>
and this is my servlet. trips.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Connection con = DB.getActiveConnection();
Statement stmt = con.createStatement();
ResultSet rs = null;
ArrayList trip = new ArrayList();
ArrayList data = null;
try {
String query = "select * from trips";
rs = stmt.executeQuery(query);
while(rs.next()){
data = new ArrayList();
data.add(rs.getString(9)); // trip number
data.add(rs.getInt(1)); // train number
data.add(rs.getString(2)); // source
data.add(rs.getString(3)); // destination
data.add(rs.getTime(4)); //departure time
data.add(rs.getTime(5));// arrival time
data.add(rs.getDate(6));// date
data.add(rs.getInt(7));// reserved seats
data.add(rs.getDouble(8));//price
trip.add(data);
}
request.setAttribute("trips", trip);
con.close();
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/updateTrip.jsp");
requestDispatcher.include(request, response);
//out.close();
//return;
}
catch (Exception e) {
e.printStackTrace();
}
}
and this is the error i get
25-Dec-2016 15:47:01.822 SEVERE [http-nio-8084-exec-4]
org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [jsp] in context with path [/Train] threw exception [java.lang.IllegalStateException: Exception occurred when flushing data] with root cause
java.io.IOException: Stream closed
at org.apache.jasper.runtime.JspWriterImpl.ensureOpen(JspWriterImpl.java:200)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:105)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:184)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:120)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:75)
at org.apache.jsp.updateTrip_jsp._jspService(updateTrip_jsp.java:199)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
You are using try with resources, which automatically closes the stream while exiting the try block.
try (PrintWriter out = response.getWriter()) {
....
}
trip.jsp passes request and response objects to the servlet trips.java, where you get the PrintWriter of the response (and for some reason, not using it anywhere) in a try with resource, which will close the underlying stream at the end of the try block. Now, when your include is finished and control comes back to the trip.jsp and try to write the jsp content, it'll fail as the stream is already closed.
Just change your code as:
PrintWriter out = response.getWriter();
try {
....
} catch (IOException e) {
....
}
or if you don't want to handle the exception here, just remove the try altogether.

Connect Servlet to MySQL database in eclipse [duplicate]

This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 6 years ago.
I successfully connected database with simple java program using JDBC but when I am trying to connect database with Servlet, it gives me following errors and exceptions:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:8888/ebookshop
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at QueryServlet.doGet(QueryServlet.java:35)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:534)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
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)
All severs running well and also I already added servlet and connecter API's in my library.
For more Information these are my html and servlet files are:
html file
<html>
<head><title>Yet Another Bookshop</title></head>
<body>
<h2>Yet Another Bookshop</h2>
<form method="get" action="http://localhost:9999/Sixth/query">
<b>Choose an author:</b>
<input type="checkbox" name="author" value="Tan Ah Teck">Ah Teck
<input type="checkbox" name="author" value="Mohammad Ali">Ali
<input type="checkbox" name="author" value="Kumar">Kumar
<input type="submit" value="Search">
</form>
</body>
</html>
My servlet:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class QueryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// JDK 6 and above only
// The doGet() runs once per HTTP GET request to this servlet.
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set the MIME type for the response message
response.setContentType("text/html");
// Get a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();
Connection conn = null;
Statement stmt = null;
try {
// Step 1: Allocate a database Connection object
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check!
// database-URL(hostname, port, default database), username, password
// Step 2: Allocate a Statement object within the Connection
stmt = conn.createStatement();
// Step 3: Execute a SQL SELECT query
String sqlStr = "select * from books where author = "
+ "'" + request.getParameter("author") + "'"
+ " and qty > 0 order by price desc";
// Print an HTML page as the output of the query
out.println("<html><head><title>Query Response</title></head><body>");
out.println("<h3>Thank you for your query.</h3>");
out.println("<p>You query is: " + sqlStr + "</p>"); // Echo for debugging
ResultSet rset = stmt.executeQuery(sqlStr); // Send the query to the server
// Step 4: Process the query result set
int count = 0;
while (rset.next()) {
// Print a paragraph <p>...</p> for each record
out.println("<p>" + rset.getString("author")
+ ", " + rset.getString("title")
+ ", $" + rset.getDouble("price") + "</p>");
count++;
}
out.println("<p>==== " + count + " records found =====</p>");
out.println("</body></html>");
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You need to load your driver before you get a connection, something like that:
//Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
Here is a nice example: http://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm
you should add this line,
Class.forName("com.mysql.jdbc.Driver");
As it is the first step to establish connection with JDBC driver,
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// Step 1: Allocate a database Connection object
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check!
// database-URL(hostname, port, default database), username, password
// Step 2: Allocate a Statement object within the Connection
stmt = conn.createStatement();
Provide that you added the mysql connector jar in your buidpath
As I see this jdbc:mysql://localhost:8888/ebookshop you have changed the default port of mysql from 3306 to 8888
If you did not change the port just use 3306 as the port for mysql
As the exception is saying No suitable driver found that obviously means you don't have the
mysql-connector-[version].jar in your classpath If you are using eclipse just place the jar under WEB-INF/lib and if you are using standalone tomcat just place the driver jar in the lib folder of Tomcat
try this
public static void connect() throws Exception {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost:3306/database_name?autoReconnect=true";
c = DriverManager.getConnection(url,"root","123");
}
thanx..

JSF interaction with database

Following bean's database related code is working in simple Java application but when i use it within JSF page it is giving Java null pointer exception error.
Thanks in advance.
Bean class:-
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
#ManagedBean
#SessionScoped
public class Db implements Serializable{
int eId;
public int geteId() {
return eId;
}
public void seteId(int eId) {
this.eId = eId;
}
public static Connection getConnection() throws Exception {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:#localhost:1521:globldb3";
String username = "scott";
String password = "tiger";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public String addEmployee() throws Exception{
Connection conn = null;
PreparedStatement pstmt = null;
try {
int a = this.eId;
conn = getConnection();
String query = "INSERT INTO c(n) VALUES(?)";
pstmt = conn.prepareStatement(query);
pstmt.setInt(1,a);
pstmt.executeUpdate(); // execute insert statement
return "success";
} catch (Exception e) {
e.printStackTrace();
return "failure";
} finally {
pstmt.close();
conn.close();
}
}
}
Following is my JSF page
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<body>
<h:form>
<p>Enter value <h:inputText value="#{db.eId}"/> </p>
<p> <h:commandButton value="Add record" action="#{db.addEmployee}"/> </p>
</h:form>
</body>
</html>
Following is stack trace
javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:787)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1252)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:306)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:558)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:379)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:259)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:281)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.NullPointerException
at erpJavaFiles.Employee.addEmployee(Employee.java:118)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.el.parser.AstValue.invoke(AstValue.java:262)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 23 more
Here,
} finally {
pstmt.close();
conn.close();
}
you aren't checking if they are null before you close them. If an exception is been thrown upon connecting, they will stay null. Fix it as follows:
} finally {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
}
There are no other potential causes for a NPE in the addEmployee() method. I see that you've an e.printStackTrace() call in the catch block. Read this one for the real cause of the problem. I guess that it's a ClassNotFoundException on the JDBC driver class, because you forgot to put the JDBC driver in /WEB-INF/lib folder of the webapp.

java.lang.IllegalStateException: Parent was not null, but this component not related

I have the following exception at the time of running JSF program.
org.apache.jasper.JasperException: An exception occurred processing JSP page /pages/general/internalServerErrorPage.jsp at line 44
41: <link rel="shortcut icon" href="<%=request.getContextPath()%>/resources/images/infomindzicon.ico" type="image/x-icon" />
42: </head>
43: <body id="sscmsMainBody">
44: <h:form id="internalServerErrorPageForm" binding="#{ServerErrorBean.initForm}">
45: <rich:page id="richPage" theme="#{LayoutSkinBean.layoutTheme}"
46: width="#{LayoutSkinBean.layoutScreenWidth}"
47: sidebarWidth="0">
Caused by: javax.servlet.ServletException: javax.servlet.jsp.JspException: java.lang.IllegalStateException: Parent was not null, but this component not related
at org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:858)
at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:791)
at org.apache.jsp.pages.general.internalServerErrorPage_jsp._jspService(internalServerErrorPage_jsp.java:207)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:377)
What is the meaning of this exception and how can I resolve this?
Update: My code is below,
public HtmlForm getInitForm() {
validateSession();
return initForm;
}
The validate session method is
private void validateSession() {
HttpSession session = null;
try {
FacesContext facesContext = FacesContext.getCurrentInstance();
actionPanelRendered = false;
if (facesContext != null) {
session = (HttpSession) facesContext.getExternalContext().getSession(false);
if (session != null) {
if (session.getAttribute(SessionAttributes.USER_LOGIN_NAME.getName()) != null) {
actionPanelRendered = true;
}
}
}
} catch(Exception e) {
logger.info("Exception arise in server error bean");
e.printStackTrace();
}
}
It's thus coming from the following line:
<h:form id="internalServerErrorPageForm" binding="#{ServerErrorBean.initForm}">
You've bound the form to the bean for some unknown reason. The exception indicates that this component has a parent, but that this is actually not a parent at all as per the component tree in the JSP page. This in turn indicates that you're doing something like the following in the bean before or during the call of getInitForm() method:
form.setParent(someComponent);
If this is true, then you should remove this line.
Update: another possible cause is that you're forgotten to put a <f:view> around the HTML with the JSF components.
Update 2: one more cause is that you're binding multiple and physically different <h:form> components to one and same bean property. They should each be bound to their own unique property (or in this particular case, not be bound at all, this can be done better, see below).
Unrelated to the problem, as to your validateSession method, the entire method can be simplified to the following single EL expression in the view:
rendered="#{not empty user.name}"
assuming that SessionAttributes.USER_LOGIN_NAME equals to user.

Categories

Resources