Tomcat: Null Pointer Exception when trying to access web service - java

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.

Related

Error in web.xml file when I add context-parameters to it

I am getting an error in web.xml file while adding context parameters to it.
Here is web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<pram-name>ADMIN_PATH</param-name>
<param-value>AdminChatServlet</param-value>
</context-param>
<context-param>
<param-name>ROOMLIST_PATH</param-name>
<param-value>/RoomListServlet</param-value>
</context-param>
<context-param>
<param-name>CHROOM_PATH</param-name>
<param-value>/ChRoomServlet</param-value>
</context-param>
<servlet>
<servlet-name>MainChatServlet</servlet-name>
<servlet-class>MainChatServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>AdminChatServlet</servlet-name>
<servlet-class>AdminChatServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>RoomListServlet</servlet-name>
<servlet-class>RoomListServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ChRoomServlet</servlet-name>
<servlet-class>ChRoomServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MainChatServlet</servlet-name>
<url-pattern>/MainChatServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AdminChatServlet</servlet-name>
<url-pattern>/AdminChatServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>RoomListServlet</servlet-name>
<url-pattern>/RoomListServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ChRoomServlet</servlet-name>
<url-pattern>/ChRoomServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
and here is the servlet(MainChatServlet) using those context-parameters:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
import com.amir.*;
public class MainChatServlet extends HttpServlet {
String chRoomPath;//="ChRoomServlet.java";
String roomListPath;//="RoomListServlet.java";
String adminChatPath;//="AdminChatServlet.java";
public void init()
{
ServletContext context = getServletConfig().getServletContext();
context.setAttribute("chRoomPath",context.getInitParameter("CHROOM_PATH"));
context.setAttribute("roomListPath",context.getInitParameter("ROOMLIST_PATH"));
context.setAttribute("adminChatPath",context.getInitParameter("ADMINCHAT_PATH"));
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
chRoomPath = (String)getServletContext().getAttribute("chRoomPath");
roomListPath = (String)getServletContext().getAttribute("roomListpath");
adminChatPath = (String)getServletContext().getAttribute("adminChatPath");
session.setAttribute("chRoomPath",chRoomPath);
session.setAttribute("roomListPath", roomListPath);
session.setAttribute("adminChatPath",adminChatPath);
HashMap hashmap = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/chat","root","mysql");
synchronized(getServletContext())
{
hashmap = (HashMap)getServletContext().getAttribute("chatList");
if(hashmap == null)
{
hashmap =new HashMap();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from chatrooms");
while(rs.next())
{
hashmap.put(rs.getString(1),new ChatRoom(rs.getString(1),rs.getString(2),4));
}
rs.close();
getServletContext().setAttribute("roomList", hashmap);
}
}
conn.close();
}
catch(ClassNotFoundException e)
{
System.out.print("Error(Class)");
e.printStackTrace();
}
catch(SQLException e)
{
System.out.print("Error(SQL)");
e.printStackTrace();
}
RequestDispatcher view = request.getRequestDispatcher("chat.jsp");
view.forward(request, response);
}
}
and here is the default-package in which all the .java files(servlets are kept)
Screenshot#1
Why am I getting the error in the web.xml file?
Screenshot#2
EDIT: OR Suggest me any alternate idea if possible.

JAVA JSON Restfull WebService No 'Access-Control-Allow-Origin' header is present on the requested resource [duplicate]

This question already has answers here:
How to handle CORS using JAX-RS with Jersey
(5 answers)
Closed 6 years ago.
I have a JAVA RESTful webservice which will return JSON string and it was written in Java. My problem is when I send request to that webservice with below URL
http://localhost:8080/WebServiceXYZ/Users/insert
it's giving me the below error message
XMLHttpRequest cannot load http://localhost:8080/WebServiceXYZ/Users/insert/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 500.
Here is my Code
package com.lb.jersey;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.json.JSONException;
import org.json.JSONObject;
#Path("/Users")
public class RegistrationService
{
#POST
#Produces(MediaType.APPLICATION_JSON)
#Path("/insert")
public String InsertCredentials (String json) throws JSONException
{
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(dt);
String phone = null;
JSONObject returnJson = new JSONObject();
try
{
JSONObject obj = new JSONObject(json);
JSONObject result1 = obj.getJSONObject("Credentials");
phone = result1.getString("phone");
DBConnection conn = new DBConnection();
int checkUserID = conn.GetUserIDByPhone(phone);
if(checkUserID <= 0)
{
DBConnection.InsertorUpdateUsers(phone, currentTime);
}
int userID = conn.GetUserIDByPhone(phone);
int otp = (int) Math.round(Math.random()*1000);
DBConnection.InsertorUpdateCredentials(userID, otp, currentTime);
JSONObject createObj = new JSONObject();
createObj.put("phone", phone);
createObj.put("otp", otp);
createObj.put("reqDateTime", currentTime);
returnJson.put("Credentials", createObj);
System.out.println(returnJson);
}
catch (Exception e)
{
}
return returnJson.toString();
}
}
My web.xml code
<?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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>WebServiceXYZ</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.lb.jersey</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
I already read many articles but no progress, so please let me know, How can I handle this issue?
this is assuming you are using jetty as your server. hope it helps...
add the following code to your web.xml
<filter>
<filter-name>cross-origin</filter-name>
<filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
<init-param>
<param-name>allowedOrigins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>allowedMethods</param-name>
<param-value>GET,POST,DELETE,PUT,HEAD</param-value>
</init-param>
<init-param>
<param-name>allowedHeaders</param-name>
<param-value>origin, content-type, accept</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>cross-origin</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
and the following dependency in your pom.xml
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<version>8.0.0.M0</version>
</dependency>
the link to configure tomcat is link... here is another link2 modify accordingly :)
You can try setting the header for the HttpServletResponse
import javax.servlet.http.HttpServletResponse;
#Path("/Users")
public class RegistrationService
{
#Context
private HttpServletResponse servletResponse;
private void allowCrossDomainAccess() {
if (servletResponse != null){
servletResponse.setHeader("Access-Control-Allow-Origin", "*");
}
}
#POST
#Produces(MediaType.APPLICATION_JSON)
#Path("/insert")
public String InsertCredentials (String json) throws JSONException
{
allowCrossDomainAccess();
// your code here
}
}

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.

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

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>

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