Unable to instantiate a servlet, getting class not found exception - java

I have created a sample maven project using the following command:
mvn archetype:generate -DgroupId=com.rohit -DartifactId=RohitLoginApp -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
Below is the image link of the project structure in eclipse:
Maven project structure in eclipse
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.rohit</groupId>
<artifactId>RohitLoginApp</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>RohitLoginApp Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>RohitLoginApp</finalName>
</build>
</project>
web.xml:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>RohitTestServlet</servlet-name>
<display-name>RohitTestServlet</display-name>
<description></description>
<servlet-class>com.company.rohit.RohitTestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RohitTestServlet</servlet-name>
<url-pattern>/RohitTestServlet</url-pattern>
</servlet-mapping>
</web-app>
RohitTestServlet.java
package com.company.rohit;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RohitTestServlet
*/
public class RohitTestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RohitTestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String userId = request.getParametker("userName");
String pwd = request.getParametker("psw");
response.getWriter().write("User ID and password are received");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Index.jsp
<html>
<body>
<h2>Login Page</h2>
<form action="RohitTestServlet">
User Name<br>
<input type="text" name="userName">
<br>
Password<br>
<input type="password" name="psw">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
When I deploy this app on tomcat, it first loads the welcome screen where I enter the userID and password and click on submit button. Then it redirects to servlet url i.e. http://localhost:8080/RohitLoginApp/RohitTestServlet?userName="xyz"&psw="www". However its unable to hit the servlet and get the response. Below is the error:
SEVERE: Allocate exception for servlet RohitTestServlet
java.lang.ClassNotFoundException: com.company.rohit.RohitTestServlet
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1856)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1705)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:506)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:488)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:115)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1148)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
It is unable to load the class. I had done clean build lot of times but still its unable to load the servlet.

It looks like your class is not being compiled into the war file. You need to make sure your servlet class is defined in src/main/java with the appropriate package subfolders. You can verify this by going to webapps directory and looking in the "classes" folder to see if your class is there.

Related

Error 505 on servlet request [duplicate]

This question already has an answer here:
Eclipse does not seem to compile servlet, causing java.lang.ClassNotFoundException
(1 answer)
Closed 5 years ago.
I'm trying to make a simple form but I get an error 500
index.php
<html>
<body>
<form action="login">
<input type="text" name="nombre"></input>
<input type="submit" value="Enviar"></input>
</form>
</body>
</html>
LoginServlet.java
package com.prueba1;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public LoginServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<display-name>LoginServlet</display-name>
<description></description>
<servlet-class>com.prueba1.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
The urlpatter is set as /login and the form action is login but when I try to submit , I get an 505 error, there is no error on code and I don't know whats the problem.I've followed many tutorials and always get the same error.
this is the error , the servlet class is not found
javax.servlet.ServletException: Error instanciando clase de servlet [com.prueba1.LoginServlet]
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1457)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:748)
causa raĆ­z
java.lang.ClassNotFoundException: com.prueba1.LoginServlet
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1285)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1457)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:748)
Project tree image:
Just tried to deploy and run your code on my own computer and it worked well. Make sure that your project structure is valid, you included your LoginServlet.java file into project right and that LoginServlet.class file is at the right directory after compilation. This is my project stucture:
Make sure your class is at WEB-INF/classes
link to screenshot
If you can't solve the problem, you should show your project structure after compilation. Maybe I can help you, if my screenshot will not help you. Don't forget that I'm using Maven to build the project. You structure may be a bit different.
If you are using Maven add the following lines into the dependencies block of pom.xml file:
`
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
`
If not, just try to add the following line before the class declaration block:
#WebServlet(name="any name you want", urlPatterns="/login")

Tomcat 404 classNotFoundException in HelloWorld servlet

I see most of similar problems and try most solutions, but nothing has worked for me!
I am completely new in Java EE and this is my first servlet.
This is my servlet that placed in: C:\tomcat\webapps\jspbook\WEB-INF\classes
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;
public class HelloWorld extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title> hello World Title </title>");
out.println("</head>");
out.println("<body>");
out.println("<h1> Hello To World in body!</h1>");
out.println("</body>");
out.println("</html>");
}
}
And this is web.xml file in C:\tomcat\webapps\jspbook\WEB-INF
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file> welcome.html </welcome-file>
</welcome-file-list>
</web-app>
Now, when i restart tomcat, and try http://127.0.0.1:8080/jspbook/HelloWorld
At first time Time this is my first error:
type Exception report
message Error instantiating servlet class HelloWorld
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error instantiating servlet class HelloWorld
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
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:1070)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2462)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2451)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:722)
root cause
java.lang.ClassNotFoundException: HelloWorld
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:503)
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:1070)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2462)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2451)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:722)
And when i reload the page, this is my second error:
HTTP Status 404 -
type Status report
message
description The requested resource is not available.
What is wrong with my code?
UPDATE:
I create a package and named it com.jspbook and placed it in here C:\tomcat\webapps\jspbook\WEB-INF\classes\com\jspbook\HelloWorld.java
package com.jspbook;
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;
public class HelloWorld extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title> hello World Title </title>");
out.println("</head>");
out.println("<body>");
out.println("<h1> Hello To World in body! </h1>");
out.println("</body>");
out.println("</html>");
}
}
web.xml is here: C:\tomcat\webapps\jspbook\WEB-INF\web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4">
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>com.jspbook.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file> welcome.html </welcome-file>
</welcome-file-list>
</web-app>
I try http://127.0.0.1:8080/jspbook/HelloWorld but the same Error appear!
(There is no compiled class file at all)
Please put the servlet in a package. The container is unable to load classes from default package.

SEVERE: Allocate exception for servlet, error when trying to call a servlet from JSP page

When I run the jsp on the tomcat server and it runs ok, but when I click submit it throws the following error, I have checked over everything and I am not sure where to go from here because it seems like it should work, any help would be much appreciated, Thank you.
Error Stack Trace:
SEVERE: Allocate exception for servlet RegistrationServlet
java.lang.ClassNotFoundException: logon.RegistrationServlet.java
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:529)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:511)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:139)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1148)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
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"
xmlns:web="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>RegistrationTest</display-name>
<servlet>
<display-name>RegistrationServlet</display-name>
<servlet-name>RegistrationServlet</servlet-name>
<servlet-class>logon.RegistrationServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegistrationServlet</servlet-name>
<url-pattern>/RegistrationServlet</url-pattern>
</servlet-mapping>
</web-app>
The JSP page:
<h2>Signup Details</h2>
<form name="actionForm" action="RegistrationServlet" method ="post">
<br/>Username:<input type="text" name="name">
<br/>Password:<input type="password" name="password">
<br/>Email:<input type="text" name="email">
<br/><input type="submit" value="Submit">
</form>
The Servlet:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RegistrationServlet
*/
#WebServlet("/RegistrationServlet")
public class RegistrationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegistrationServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
System.out.println("In the registration Servlet");
User user = new User();
user.setName(request.getParameter("name"));
user.setPassword(request.getParameter("password"));
user.setEmail(request.getParameter("email"));
RegisterUser.addUser(user);
//response.sendRedirect("welcome.jsp");
} catch (Throwable exc)
{
System.out.println(exc);
}
}
}
For anybody that has a similar problem in the future, after cleaning the project, ensure that the build automatically box is checked under the project drop down menu as this is required to rebuild after clean, mine was unchecked by default for some reason.
Also I made a small error in the code, I used annotations (#webservlet) in my servlet and I also added the servlet to my web.xml which caused a conflict. This is now done automatically with annotations.
I also got the same exception and resolved just by putting full qualified calssname in the web.xml fle.
$fully qualified class name$

Servlet example in the java web application

I'm new to java web application development, can you tell me, what am I doing wrong:
I have generated the web application using maven:
mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=webapp -DarchetypeArtifactId=maven-archetype-webapp
I have put HelloWorld.java in the src.main.resources folder, here is the code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head><title>Hello World</title></title>");
pw.println("<body>");
pw.println("<h1>Hello World</h1>");
pw.println("</body></html>");
}
}
my web.xml from src.main.webapp.WEB-INF looks like:
!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>
here is my pom.xml:
project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-webapp</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>my-webapp Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>my-webapp</finalName>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<configuration>
<url>http://localhost:8080/manager/html</url>
<server>mytomcat</server>
<path>/my-app</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
Then i type
mvn package tomcat:deploy
and on the link localhost:8080/web/HelloWorld -
HTTP Status 500 - Error instantiating servlet class HelloWorld
type Exception report
message Error instantiating servlet class HelloWorld
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error instantiating servlet class HelloWorld org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) 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) root cause
java.lang.ClassNotFoundException: HelloWorld org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714) org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) 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)
I have put HelloWorld.java in the src.main.resources folder
The java code should not be in src/main/resources, it should be in src/main/java.
Your HelloWorld.java has never been built and thus it cannot be found by tomcat. Your war file does not contain the HelloWorld.class.

Regarding logs configuration for servlet

I am developing an application , I want to configure the log4j as I want separate logging to be done for my project also so that a separate log file is created .. below is the pic of my project please click on the url to see it..snapshot of the project structure
Now here is the servlet
package com.saral;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class First
*/
//#WebServlet("/First")
public class MyServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
static final Logger logger = Logger.getLogger(MyServlet.class);
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PropertyConfigurator.configure("log4j.properties");
logger.info("before---->");
// TODO Auto-generated method stub
String name=request.getParameter("txtName");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("Hello,"+name);
out.println("<br> this output is generated by a simple servlet.");
out.println("Total Number of users logged in--->"+request.getSession().getServletContext().getAttribute("sessionCount"));
out.close();
}}
and the structure of the web.xml is
<?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>FirstDemo</display-name>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.saral.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/helloServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
<listener>
<listener-class>com.saral.SessionCounter</listener-class>
</listener>
</web-app>
but upon running the application on tomcat it shows the following error..
INFO: Server startup in 888 ms
log4j:ERROR Could not read configuration file [log4j.properties].
java.io.FileNotFoundException: log4j.properties (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at org.apache.log4j.PropertyConfigurator.doConfigure(PropertyConfigurator.java:306)
at org.apache.log4j.PropertyConfigurator.configure(PropertyConfigurator.java:324)
at com.saral.MyServlet.doGet(MyServlet.java:29)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
log4j:ERROR Ignoring configuration file [log4j.properties].
Please advise how to generate the separate logs, please advise
This means the log4j.properties file is not in your classpath. You need to put it under the "src" folder and redeploy the application to tomcat.

Categories