"Resource not available" Error for displaying database into a JSP - java

I think i have got the successful connection to the database and when i run the Fetch.jsp, i do get the page with the Submit button. But when i click on submit button it shows an Tomcat Error type Status Report message /Sample description The Requested Resource is not available.
Tools:Eclipse Kepler
MySQL Workbench 6.1.7
Apache Tomcat 7.0.54
Fetch.jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Database_Test</title>
</head>
<body>
<form action="Sample" method="post">
Fetch Data: <input type="submit"></input>
</form>
</body>
</html>
Sample.java
package testusecase;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Sample extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 8462790020399479519L;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
#SuppressWarnings("unused")
Sample instance = new Sample();
final String URL = "jdbc:mysql://localhost:3306/samschema";
final String USER = "root";
final String PASSWORD = "password";
final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
try {
Class.forName(DRIVER_CLASS);
Connection connection = null;
connection = DriverManager.getConnection(URL, USER, PASSWORD);
String query = "SELECT * FROM samschema.sample1";
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
int serial_no = rs.getInt("serial_no");
String first_name = rs.getString("first_name");
String middle_name = rs.getString("middle_name");
String last_name = rs.getString("last_name");
String date_of_birth = rs.getString("date_of_birth");
String contact_no = rs.getString("contact_no");
String email_id = rs.getString("email_id");
String residential_address = rs.getString("residential_address");
String city = rs.getString("city");
BigDecimal percentage_x = rs.getBigDecimal("percentage_x");
Date yop_x = rs.getDate("yop_x");
String board_x = rs.getString("board_x");
String percentage_xii = rs.getString("percentage_xii");
String yop_xii = rs.getString("yop_xii");
String board_xii = rs.getString("board_xii");
String btech_stream = rs.getString("btech_stream");
String mtech_stream = rs.getString("mtech_stream");
String other_stream = rs.getString("other_stream");
String percentage_graduation = rs.getString("percentage_graduation");
String mca_percentage = rs.getString("mca_percentage");
String year_of_graduation = rs.getString("year_of_graduation");
String d_to_d = rs.getString("d_to_d");
String mtech_percentage = rs.getString("mtech_percentage");
String yop_diploma = rs.getString("yop_diploma");
String percentage_d_to_d = rs.getString("percentage_d_to_d");
// print the results
System.out.format("%d, %s, %s, %s, %s, %s, %s, %s, %s, %d, %d, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s\n", serial_no, first_name,
middle_name,last_name, date_of_birth,contact_no,email_id,residential_address,city, percentage_x, yop_x, board_x, percentage_xii, yop_xii, board_xii, btech_stream, mtech_stream, other_stream, percentage_graduation, mca_percentage, year_of_graduation, d_to_d, mtech_percentage, yop_diploma, percentage_d_to_d);
}
st.close();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>TestUseCase</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<security-constraint>
<web-resource-collection>
<web-resource-name>TestUseCase</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
</security-constraint>
<servlet>
<description></description>
<display-name>Login</display-name>
<servlet-name>Login</servlet-name>
<jsp-file>/Login.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>Sample</display-name>
<servlet-name>Sample</servlet-name>
<servlet-class>Sample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Sample</servlet-name>
<url-pattern>/Sample</url-pattern>
</servlet-mapping>
</web-app>
Java Stack Trace in console
Java Model Exception: Java Model Status [Unknown javadoc format for getAsciiStream(java.lang.String) [in ResultSet [in ResultSet.class [in java.sql [in U:\Miller\Eclipse\JDK\lib\rt.jar]]]]]
at org.eclipse.jdt.internal.core.JavadocContents.getMethodDoc(JavadocContents.java:158)
at org.eclipse.jdt.internal.core.BinaryMethod.getAttachedJavadoc(BinaryMethod.java:671)
at org.eclipse.jdt.internal.ui.text.javadoc.JavadocContentAccess2.getHTMLContent(JavadocContentAccess2.java:499)
at org.eclipse.jdt.internal.ui.text.java.ProposalInfo.extractJavadoc(ProposalInfo.java:93)
at org.eclipse.jdt.internal.ui.text.java.ProposalInfo.computeInfo(ProposalInfo.java:77)
at org.eclipse.jdt.internal.ui.text.java.ProposalInfo.getInfo(ProposalInfo.java:62)
at org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal.getAdditionalProposalInfo(AbstractJavaCompletionProposal.java:573)
at org.eclipse.jface.text.contentassist.AdditionalInfoController$3.run(AdditionalInfoController.java:106)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:53)
Browser Error
HTTP Status 500 - Error instantiating servlet class Sample
type Exception report
message Error instantiating servlet class Sample
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error instantiating servlet class Sample
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:610)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Unknown Source)
root cause
java.lang.ClassNotFoundException: Sample
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:610)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Unknown Source)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.54 logs.
Apache Tomcat/7.0.54

In the servlet tag, the <servlet-class> element should be the fully qualified name of your servlet class. For example:
<servlet-class>testusecase.Sample</servlet-class>
Also note that the stack trace you show appears to be for when your app is starting up, and not when the specified problem occurs.

According to the stacktrace, the servlet /Placement tries to give control to Fetch.jsp and container fails to find it. It could be a lower/upper case problem, or is it really at root of web application ?
With the full error it is clear. In the web.xml file, you must give the fully qualified name of your servlet class :
<servlet-class>testusecase.Sample</servlet-class>

Related

HTTP Status 500 - Error instantiating servlet class com.sar.pkg.MyServlet

MyServlet.java
class MyServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
//private static final long serialVersionUID =102831973239L;
static String task;
public MyServlet(){
}
String tm;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
task = request.getParameter("task");
tm= request.getParameter("reminder_time");
try {
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date time=new Date();
formatter.format(time);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection(
"jdbc:mysql://localhost:3306/reminder","sarthak","sar31thak");
String INSERT_RECORD = "insert into ToDo values(?, ?)";
PreparedStatement pstmt = null;
pstmt = con.prepareStatement(INSERT_RECORD);
pstmt.setString(1, task);
pstmt.setDate(2, (java.sql.Date) time);
int rs= pstmt.executeUpdate();
if(rs!=0){
response.sendRedirect("success.html");
return;
}
else{
response.sendRedirect("error.html");
}
con.close();
}
catch(Exception e){
System.out.println("Got an EXCEPTION");}
}
catch (Exception e) {
System.out.println("Got an ERROR");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Alert</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>MyServlet</display-name>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.sar.pkg.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
Which causes the following error
HTTP Status 500 - Error instantiating servlet class com.sar.pkg.MyServlet
type Exception report
message Error instantiating servlet class com.sar.pkg.MyServlet
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error instantiating servlet class com.sar.pkg.MyServlet
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
root cause
java.lang.IllegalAccessException: Class org.apache.catalina.core.DefaultInstanceManager can not access a member of class com.sar.pkg.MyServlet with modifiers "public"
sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
java.lang.Class.newInstance(Unknown Source)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.47 logs.
I have tried to remove this error by using different serialVersionID and cleaned the project before running it. Still stuck on this. PLease help. Thanks in advance.
Your Servlet class com.sar.pkg.MyServlet is not public. Your definition
class MyServlet extends HttpServlet{
should be
public class MyServlet extends HttpServlet{

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)

error instantiating servlet class when trying to access a database

I've just gotten into servlets and I cannot display the information on tomcat.
This is my class with the doGet method
public class WhoisOlder extends HttpServlet {
private static final long serialVersionUID = 1L;
public WhoisOlder() {
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
final String OJDBC_Driver = "oracle.jdbc.driver.OracleDriver";
final String DB_URL = "";
final String USER = "";
final String PASS = "";
try {
Class.forName(OJDBC_Driver);
Connection con = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT GEBDAT FROM KLASSE");
while (rs.next()) {
System.out.println(rs.getString("GEBDAT"));
}
rs.close();
stmt.close();
con.close();
} catch (SQLException se) {
System.out.println("SQL Exception: " + se.getMessage());
se.printStackTrace(System.out);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I get the "Error instantiating servlet class" error, when I run the code on my browser. I have checked if the servlet name, servlet URL is correct, which it is. Is the code false in my class, which preventing to instantiate the class?
EDIT: Below is the exception and the root log.
java.lang.ClassNotFoundException: WhoisOlder
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2466)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2455)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
EDIT 2: My web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<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">
<description>OJDBCAnbindung</description>
<display-name>OJDBCAnbindung</display-name>
<servlet>
<servlet-name>WhoisOlder</servlet-name>
<servlet-class>WhoisOlder</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WhoisOlder</servlet-name>
<url-pattern>/WhoisOlder</url-pattern>
</servlet-mapping>
</web-app>
Put your servlet in a package, compile the .class file to the WEB-INF/classes folder. Change your web.xml to add the package name to your servlet's class file.

Tomcat: Null Pointer Exception when trying to access web service

I have a dynamic web project that contains a web service. I have exported it as a WAR file and placed it in the webapps directory of tomcat. Tomcat shows that the web app is running. When I attempt to invoke one of the operations of my service, I get the following exception:
java.lang.NullPointerException
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
java.lang.ClassLoader.loadClass(ClassLoader.java:247)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1629)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:461)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:931)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
java.lang.Thread.run(Thread.java:680)
Any idea what this means?
Here's my class the defines the web service:
package webservice;
import java.sql.*;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.core.MediaType;
#Path("/operations")
public class NotifyWebService {
#Path("/insertNewPatron")
#GET
public String insertNewPatron(#QueryParam("cardNumber")String cardNumber,
#QueryParam("pin") String pin,
#QueryParam("nickname") String nickname,
#QueryParam("deviceID")String deviceID) throws Exception {
String connectionUrl = "jdbc:sqlserver://mssql.acpl.lib.in.us:1433;" +
"databaseName=MobileNotify;user=Mobile_Notification_User;password=xxxxxxx;";
Connection c = DriverManager.getConnection(connectionUrl);
String insertPatronStatement = "INSERT INTO dbo.Patron VALUES ('"+cardNumber+"','"+pin+"','"+nickname+"')";
String insertDeviceOwner = "INSERT INTO dbo.DeviceOwner VALUES ('"+deviceID+"','"+cardNumber+"')";
Statement state = null;
state = c.createStatement();
state.executeUpdate(insertPatronStatement);
state.executeUpdate(insertDeviceOwner);
c.close();
return "true";
}
#Path("/initializeDevice")
#GET
public String initializeDevice( #QueryParam("deviceID")String deviceID) throws Exception{
String connectionUrl = "jdbc:sqlserver://mssql.acpl.lib.in.us:1433;" +
"databaseName=MobileNotify;user=Mobile_Notification_User;password=xxxxxx;";
Connection c = DriverManager.getConnection(connectionUrl);
String insertDeviceStatement = "INSERT INTO dbo.Devices VALUES ('"+deviceID+"',1,3,1,3)";
Statement state = c.createStatement();
state.executeUpdate(insertDeviceStatement);
return "true";
}
#Path("/updateDevicePreferences")
#GET
public String updateDevicePreferences(#QueryParam("deviceID") String deviceID,
#QueryParam("dueDateNotice")String dueDateNotice,
#QueryParam("dueDateNoticeAdvance") String dueDateNoticeAdvance,
#QueryParam("holdsNotice") String holdsNotice,
#QueryParam("eventNoticeAdvance")String eventNoticeAdvance) throws Exception{
String connectionUrl = "jdbc:sqlserver://mssql.acpl.lib.in.us:1433;" +
"databaseName=MobileNotify;user=Mobile_Notification_User;password=xxxxxx;";
Connection c = DriverManager.getConnection(connectionUrl);
String updateDeviceStatement = "UPDATE dbo.Devices SET dueDateNotice="+dueDateNotice+", dueDateNoticeAdvance="+dueDateNoticeAdvance
+", holdsNotice="+holdsNotice+", eventNoticeAdvance="+eventNoticeAdvance+" WHERE deviceID='"+deviceID+"'";
Statement state = c.createStatement();
state.executeUpdate(updateDeviceStatement);
return "true";
}
#Path("/removeUser")
#GET
public String removeUser(#QueryParam("cardNumber")String cardNumber) throws Exception{
String connectionUrl = "jdbc:sqlserver://mssql.acpl.lib.in.us:1433;" +
"databaseName=MobileNotify;user=Mobile_Notification_User;password=xxxxxx;";
Connection c = DriverManager.getConnection(connectionUrl);
String removeStatement = "DELETE FROM dbo.Patron WHERE cardNumber='"+cardNumber+"'";
Statement state = c.createStatement();
state.executeUpdate(removeStatement);
return "true";
}
#Path("/addEvent")
#GET
public String addEvent(#QueryParam("deviceID")String deviceID, #QueryParam("eventID")String eventID) throws Exception{
String connectionUrl = "jdbc:sqlserver://mssql.acpl.lib.in.us:1433;" +
"databaseName=MobileNotify;user=Mobile_Notification_User;password=xxxxx;";
Connection c = DriverManager.getConnection(connectionUrl);
String eventStatement = "INSERT INTO dbo.Events VALUES ('"+deviceID+"','"+eventID+"')";
Statement state = c.createStatement();
state.executeUpdate(eventStatement);
return "true";
}
#Path("/removeEvent")
#GET
public String removeEvent(#QueryParam("deviceID")String deviceID, #QueryParam("eventID")String eventID) throws Exception{
String connectionUrl = "jdbc:sqlserver://mssql.acpl.lib.in.us:1433;" +
"databaseName=MobileNotify;user=Mobile_Notification_User;password=xxxxx;";
Connection c = DriverManager.getConnection(connectionUrl);
String eventStatement = "DELETE FROM dbo.Events WHERE deviceID='"+deviceID+"' AND eventID='"+eventID+"'";
Statement state = c.createStatement();
state.executeUpdate(eventStatement);
return "true";
}
#Path("/removeAllEvents")
#GET
public String removeAllEvents(#QueryParam("deviceID")String deviceID) throws Exception{
String connectionUrl = "jdbc:sqlserver://mssql.acpl.lib.in.us:1433;" +
"databaseName=MobileNotify;user=Mobile_Notification_User;password=xxxx;";
Connection c = DriverManager.getConnection(connectionUrl);
String eventStatement = "DELETE FROM dbo.Events WHERE deviceID='"+deviceID+"'";
Statement state = c.createStatement();
state.executeUpdate(eventStatement);
return "true";
}
}
Here's my web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>APNS_WebService</display-name>
<servlet>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Let me know if more information is required!
I believe that the cause of your NPE is the lack of a <servlet-class> element in your <servlet> block. However, deciding what the servlet-class should be raises a bigger problem...
It looks like you have not chosen a JAX-RS framework. See JAX-RS Frameworks for insight on various alternatives.
I am currently using Jersey. A typical web.xml for Jersey might contain:
<servlet>
<servlet-name>WebService</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>webservice</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>WebService</servlet-name>
<url-pattern>/api/rest/*</url-pattern>
</servlet-mapping>
For many JAX-RS frameworks, the choice of framework will determine what you should enter as the <servlet-class>
Also note that since your root resource is in package webservice, I set the com.sun.jersey.config.property.packages parameter to webservice so Jersey will scan your package for any JAX-RS annotated classes.

code doesn't insert the data into the database

I am trying a servlet that puts the data into the database:derbi (that comes packed with netbeans). When a user clicks to submit data,the request follows to the FormHandler servlet (given below) If any of the text-field was empty the request follows to another servlet ErrorServlet and if every thing was fine the request follows to the Registered servlet. But before the request follows to the Registered Servlet there is a small code that is written to insert the data into the database (After this code the the user views the success page,that he has been registered).
Now the problem : The user fills all the text fields in the form and clicks submit. When he clicks submit,he sees the success page displaying Registered Successfully . But when i query the databse, i see that the data wasn't submitted to the databse. The rows and columns are empty ! I don't understand the reason for this .
Code for FormHandler.java :
package FormHandler;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.LinkedList;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class FormHandler extends HttpServlet {
#Override
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
}
#Override
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
String name = request.getParameter("Name");
String email = request.getParameter("Email");
String password = request.getParameter("Password");
LinkedList list = new LinkedList();
if(name.compareTo("") == 0 || email.compareTo("") == 0 || email.compareTo("") == 0) {
list.add("One or more field's' left blank");
request.setAttribute("ErrorList", list);
RequestDispatcher rd = request.getRequestDispatcher("ErrorServlet.view");
rd.forward(request, response);
} else {
try {
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/MyDatasource");
Connection connection = ds.getConnection();
String sqlStatement = "INSERT INTO INFORMATION VALUES('" + name + "'," + "'" + email + "'," + "'" + password + "')";
PreparedStatement statement = connection.prepareStatement(sqlStatement);
ResultSet result = statement.executeQuery();
}catch(Exception exc) {
System.out.println(exc);
}
request.setAttribute("Data", list);
RequestDispatcher rd = request.getRequestDispatcher("Registered.view");
rd.forward(request, response);
}
}
}
XML file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
<servlet>
<servlet-name>FormHandler</servlet-name>
<servlet-class>FormHandler.FormHandler</servlet-class>
</servlet>
<servlet>
<servlet-name>Registered</servlet-name>
<servlet-class>FormHandler.Registered</servlet-class>
</servlet>
<servlet>
<servlet-name>ErrorServlet</servlet-name>
<servlet-class>FormHandler.ErrorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FormHandler</servlet-name>
<url-pattern>/FormHandler.do</url-pattern>
</servlet-mapping>
<resource-ref>
<res-ref-name>jdbc/MyDatasource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
<servlet-mapping>
<servlet-name>Registered</servlet-name>
<url-pattern>/Registered.view</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ErrorServlet</servlet-name>
<url-pattern>/ErrorServlet.view</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
Html File :Code for html file
Note : I have already made a connection to database
I think you are getting somewhere a :
java.sql.SQLException: No ResultSet was produced
because executing your UPDATE query with executeQuery() actually returns no resultset
Use:
statement.executeUpdate();
try the following:
PreparedStatement ps2=null;
ps2 = connection.prepareStatement("INSERT INTO INFORMATION( colname1, colname2,colname3) VALUES(? ,? ,?)");
ps2.setString(1, name);
ps2.setString(2, email);
ps2.setString(3, password);
try {
rs=ps2.executeUpdate();
} catch (SQLException ex) {
// catch if any exception
}

Categories

Resources