error instantiating servlet class when trying to access a database - java

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.

Related

TomCat servlet unable to access GlobalNamingResources

Hey there im currently working on a application in tomcat and im trying to access a DataSource thats defined in the tomcat's server.xml. However im unable to access the resource and it will always return an empty DataSource. The servlet is able to access resources defined on the local level. My question is why is my application unable to access global resources?
The exception im getting when trying to access the database is: java.sql.SQLException: Cannot create JDBC driver of class '' for connect URL 'null'
server.xml
<GlobalNamingResources>
<Resource name="jdbc/AuthenticationDatabase" auth="Container" type="javax.sql.DataSource" username="tomcat" password="tomcat" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/tomcat" factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" />
</GlobalNamingResources>
AdminPanel.java
#WebServlet(name = "adminpanel", value = "/restricted/user-management")
public class AdminPanel extends HttpServlet {
private List<User> users;
private final String PreparedUsersSelectQuery = "SELECT active, user_name FROM users";
private final String PreparedRoleSelectQuery = "SELECT role_name FROM user_roles WHERE user_name = ?";
Context initCtx = new InitialContext();
Context EnvCtz = (Context) initCtx.lookup("java:comp/env");
DataSource userDB = (DataSource) EnvCtz.lookup("jdbc/AuthenticationDatabase");
public AdminPanel() throws NamingException {
}
protected void ProcessRequest(HttpServletRequest request, HttpServletResponse response) {
users = new ArrayList<>();
try {
Connection conn = userDB.getConnection();
PreparedStatement stmt = conn.prepareStatement(PreparedUsersSelectQuery);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
User user = new User(rs.getString("user_name"), rs.getBoolean("active"));
PreparedStatement roleStmt = conn.prepareStatement(PreparedRoleSelectQuery);
roleStmt.setString(1, user.username);
ResultSet roleResults = roleStmt.executeQuery();
while (roleResults.next()) {
user.roles.add(roleResults.getString("role_name"));
}
users.add(user);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
request.setAttribute("data", users);
RequestDispatcher dispatcher = request.getRequestDispatcher("ListUsers.jsp");
try {
dispatcher.forward(request, response);
} catch (ServletException | IOException e) {
throw new RuntimeException(e);
}
}
public void init() {
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
ProcessRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ProcessRequest(req, resp);
}
public void destroy() {
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_4_0.xsd"
version="4.0">
<resource-ref>
<description>Access to the userdatabase for the purpose of modifying the user data</description>
<res-ref-name>jdbc/AuthenticationDatabase</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<security-constraint>
<web-resource-collection>
<web-resource-name>Admin Panel</web-resource-name>
<url-pattern>/restricted/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin-user</role-name>
</auth-constraint>
</security-constraint>
<security-role>
<role-name>admin-user</role-name>
</security-role>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>User Management</realm-name>
</login-config>
</web-app>
Thanks for any and all assistance in this matter.

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{

Java jersey 2.6: ContainerRequestFilter: Not Inside a request scope

I have a service rest on my tomcat and it correctly works but when I deploy it on another tomcat server, it throws an exception.
I'm trying to implement a ContainerRequestFilter. And this exception seems caused by the #Context resourceInfo in my authenticationFilter (the class that implements ContainerRequestFilter). But I don't understand why and how to fix it. (I followed this tutorial)
A MultiException has 3 exceptions. They are:
1. java.lang.IllegalStateException: Not inside a request scope.
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of services.AuthentificationFilter errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on services.AuthentificationFilter
org.jvnet.hk2.internal.Collector.throwIfErrors(Collector.java:88)
org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:270)
org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:414)
org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:456)
org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:114)
org.jvnet.hk2.internal.SingletonContext$1.compute(SingletonContext.java:102)
org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture$1.call(Cache.java:97)
java.util.concurrent.FutureTask.run(FutureTask.java:266)
org.glassfish.hk2.utilities.cache.Cache$OriginThreadAwareFuture.run(Cache.java:154)
org.glassfish.hk2.utilities.cache.Cache.compute(Cache.java:199)
org.jvnet.hk2.internal.SingletonContext.findOrCreate(SingletonContext.java:153)
org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2445)
org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:98)
org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
org.glassfish.jersey.internal.inject.Providers.getAllRankedProviders(Providers.java:234)
org.glassfish.jersey.server.ApplicationHandler.getProcessingProviders(ApplicationHandler.java:616)
org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:409)
org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:161)
org.glassfish.jersey.server.ApplicationHandler$3.run(ApplicationHandler.java:286)
org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
org.glassfish.jersey.internal.Errors.process(Errors.java:315)
org.glassfish.jersey.internal.Errors.process(Errors.java:297)
org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:283)
org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:298)
org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:167)
org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:349)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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)
The code of my authenticationFilter
#Provider
public class AuthentificationFilter implements javax.ws.rs.container.ContainerRequestFilter {
#Context
private ResourceInfo resourceInfo;
private static final String AUTHORIZATION = "Authorization";
private static final String BASIC = "Basic";
private static final Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED).entity("Essayez de mettre sudo devant votre requete").build();
private static final Response ACCESS_FORBIDDEN = Response.status(Response.Status.FORBIDDEN).entity("You shall not pass !").build();
#Override
public void filter(final ContainerRequestContext context) throws IOException {
Method method = resourceInfo.getResourceMethod();
if(!method.isAnnotationPresent(PermitAll.class)) {
MultivaluedMap<String, String> headers = context.getHeaders();
List<String> authorization = headers.get(AUTHORIZATION);
if(method.isAnnotationPresent(DenyAll.class)) {
context.abortWith(ACCESS_FORBIDDEN);
return;
}else if(authorization == null || authorization.isEmpty()) {
context.abortWith(ACCESS_DENIED);
return;
}
String encodedUserPassword = authorization.get(0).replaceFirst(BASIC + " ", "");
String auth = new String(Base64.getDecoder().decode(encodedUserPassword.getBytes()));;
String[] authTab = auth.split(":");
String username = authTab[0];
String password = authTab[1];
if(method.isAnnotationPresent(RolesAllowed.class)) {
RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value()));
if(!isAllowed(username, password, rolesSet)) {
context.abortWith(ACCESS_DENIED);
return;
}
}
}
}
private boolean isAllowed(final String username, final String password, final Set<String> rolesSet)
{
boolean isAllowed = false;
User user;
if((user = new UserMapper().get(username, password)) != null) {
String role = user.getStatus().toString();
if(rolesSet.contains(role))
isAllowed = true;
}
return isAllowed;
}
}
The code of MyApplication.java that registers the filter:
public class MyApplication extends ResourceConfig {
public MyApplication() {
packages("services");
register(AuthentificationFilter.class);
}
}
And finally the web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="3.1">
<servlet>
<servlet-name>Example API</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>services.MyApplication</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>Example API</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
What am I doing wrong ?
I finally found the solution. I had to create a class that implements DynamicFeature and register my AuthenticationFilter thanks to a custom constructor.
#Provider
public class AuthenticationDynamicFeature implements DynamicFeature {
#Override
public void configure(ResourceInfo resourceInfo, FeatureContext featureContext) {
featureContext.register(new AuthenticationFilter(resourceInfo));
}
}
And here the custom constructor :
public AuthenticationFilter(ResourceInfo resourceInfo) {
super();
this.resourceInfo = resourceInfo;
}
I tried a lot of other ways, and this one, it's the only one that worked for me.

"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>

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.

Categories

Resources