I'm having problems with my first servlet - java

This is the code to my servlet...
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
private String message;
public void init(){
message="Hello World";
}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>"+message+"</h1>");
}
public void destroy(){
}
}
I'm using xampp's tomcat 7
and this is my web.xml file
<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_3_0.xsd"
version="3.0"
metadata-complete="true">
<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>
My web.xml is in %TOMCAT_HOME%/webapps/ROOT/WEB_INF directory
and my HelloWorld.class is in %TOMCAT_HOME%/webapps/ROOT/WEB_INF/classes directory.
when I try to run my file from my browser I type
http://localhost:8080/HelloWorld
in the addressbar
and the following Servlet exception shows up
type Exception report
message
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.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:269)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:724)
root cause
java.lang.NoClassDefFoundError: HelloWorld (wrong name: com/HelloWorld/HelloWorld)
java.lang.ClassLoader.defineClass1(Native Method)
java.lang.ClassLoader.defineClass(ClassLoader.java:752)
java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2820)
org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1150)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:269)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:724)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.21 logs.
Please suggest a method to run my app properly...

Don't use the default (empty) package; give it a name instead...
package com.xyz;
...
public class HelloWorld extends HttpServlet
Update web.xml to reflect new package...
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>com.xyz.HelloWorld</servlet-class>
</servlet>
Make sure the servlet class file resides in...
WEB-INF/classes/com/xyz/HelloWorld.class

follow the following steps
Under the webapps folder, create a new folder for your webapp.
HelloWorld
Under HelloWorld create another folder called WEB-INF.
Under WEB-INF, create a folder called classes.
under WEB-INF, put your web.xml .
under the classes folder create your package structure com/HelloWorld
put your class file under classes/com/HelloWorld folder
restart the tomcat

Default packages are discouraged, always put your servlets and classes in some package. Lets say you have package com.practice and HelloWorld servlet in it then your web.xml becomes
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>com.practice.HelloWorld</servlet-class>
</servlet>
If you are defining servlet in com.practice package i.e. path should be WEB-INF/classes/com/practice/HelloWorld
Also, if you are using tomcat 7, then you do not have to use servlet mapping in web.xml at all.
You can simply use annotations for the same.
e.g.
#WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
private String message;
public void init() {
message = "Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy() {
}
}
Here WebServlet is the annotation that is equalivalent to defining servlet in web.xml and "/HelloWorld" is the url pattern

i don't know why you are just typing the servlet mapping url to invoke your web application as follows.
http://localhost:8080/HelloWorld
it should be in the following format
http://localhost:8080/your-web-application-name/url-pattern
for example, assume that you are invoking HelloWorld url mapping on Web Application called MyWebApp . it should be called as below.
host:port/MyWebApp/HelloWorld

I also faced the same issue. I resolved the issue as follows.
IDE Eclipse Photon
Go to this path:
Build Path> Configure Build Path > Source
Change the path of "Default output folder":
[project name]/WebContent/WEB-INF/classes
Try with this, Sometime it won't work.
If it is not working, create a new Java program with Public static void main(String[] args) and Run that project as Java Application, so your project will update and a new .class file will be created:

Related

Java Servlet on eclipse: Error instantiating servlet class | ClassNotFoundException

I know this question has been asked a lot but I tried everything and it's still not working for me, hoping someone can help.
I'm trying to run a servlet page on server with eclipse, keeps showing this error:
Here's my source code:
I've wrote a simple servlet page just to see it running on server:
package main.java.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class StationsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public StationsServlet() {
}
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.println("<html>");
writer.println("<body>");
writer.println("Hello");
writer.println("</body></html>");
writer.flush();
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
My web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>weather-files-war</display-name>
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>stationsServlet</servlet-name>
<servlet-class>main.java.servlet.StationsServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>stationsServlet</servlet-name>
<url-pattern>/stations</url-pattern>
</servlet-mapping>
</web-app>
and finally, my folders/modules structure:
PS: I created a homepage.jsp and it's working properly on server, the problem is when hitting the servlet class.
First of all check what the problem with exclamation mark near your StationsServlet.java
Also try to add annotation #WebServlet(name = "StationsServlet ", value = "/stations")
before public class StationsServlet extends HttpServlet { in your servlet class.
it need to help.
I created a new project and a new workspace and just copied modules and classes to the new one and it worked.
I guess it was something to do with eclipse project structure and configurations.
Hope this information is useful for the programmers looking for an answer for this common issue. This answer is based on this question.
Please make sure your servlet class under the following folder
(Your Project Name)/src/main/java
Add Annotation to your servlet
#WebServlet(name="stationsServlet", value = "/stations")
Your .jsp (homepage.jsp) form should be,
Please follow these steps.

Http status 404 -/the requested resource is not available [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I am new to java, I just tried to read initialization parameters from Deployment Descriptor file (web.xml), But got above error?
My web.xml and java file coding coding in snap attached.
My directrory structure is
c:\....tomcat\webapps\dd\web-inf\classes
No error in java class file.
Java file code which is compiled successfully
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet {
String fileName;
public void init(ServletConfig config) throws ServletException {
super.init(config);
fileName = config.getInitParameter("logfilename");
}
protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
processRequest(request, response);
}
protected void processRequest(HttpServletRequest request,HttpServletResponse
response)throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println(fileName);
out.close();
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>MyServlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
<init-param>
<param-name>logfilename</param-name>
<param-value>value1</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet2</servlet-name>
<url-pattern>/mc11</url-pattern>
</servlet-mapping>
</web-app>
Other detail of my directory and error page i think that my web.xml not working
There are two problems I can see at the moment...
Servlet init parameters
You currently have:
//defining param1
param1
value1
That's not how you define the parameter. You should specify a param-name element containing the name of the parameter, rather than using the name of the parameter as an XML element name.
<init-param>
<param-name>logfilename</param-name>
<param-value>...</param-value>
</init-param>
Also note that // isn't how you write comments in XML - if you wanted a comment, you should have:
<!-- Define the first parameter -->
<init-param>
<param-name>logfilename</param-name>
<param-value>...</param-value>
</init-param>
(The param-value element should have been a hint - if you could really just specify your own element, I'd have expected <logfilename>value in here</logfilename> - having the name specified as an element name, but the value specified with a fixed element name of param-value would have been an odd scheme.)
Servlet mapping
Currently your mapping is:
<servlet-name> FormServlet</servlet-name>
<url-pattern>/ss/</url-pattern>
</servlet-mapping>
I suspect that mapping won't match http://localhost:8080/dd/ss/s.html because you don't have any wildcards in there - it you may well find that it matches exactly http://localhost:8080/dd/ss/. It's not clear where the dd part comes in, but I assume that's a separate part of your configuration. You should try:
<!-- I would recommend removing the space from the servlet
- name *everywhere*. -->
<servlet-name>FormServlet</servlet-name>
<url-pattern>/ss/*</url-pattern>
</servlet-mapping>
If that doesn't work for http://localhost:8080/dd/ss/s.html, see whether it maps http://localhost:8080/ss/s.html - it may be that your engine isn't configured the way you expect elsewhere.
There is no problem with code,I try net beans tool and done assignment perfectly with the help of above code.Before that may be problem in tomcat.

Servlet : Not able to run the Hello World Program

Not duplicate of this question
Here is my code
HelloWorld.java
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException
{
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy()
{
// do nothing.
}
}
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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Servlet</display-name>
<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>
</web-app>
there is no compilation error, however facing this issue.
Please help!!
I changed url to
http://localhost:8080/Servlet/HelloWorld
and now facing exception
Folder Structure
You should provide the class name with the package name.
However, I would recommend to try using #WebServlet(name = "HelloWorld", urlPatterns = "/helloWorld") above the servlet class.
so if owuld be :
#WebServlet(name = "Welcome", urlPatterns = "/testPage")
public class HelloWorld extends HttpServlet {
//blah blah
}
There are a couple of things to check :
- first that the application is deployed corectly on the server. You should have a .war project that is deployed. You should see a successful deployment on you server logs
- Build your url. This is composed of server IP, in your case local host, than port 8080 is usually the default, than context root (if not defined than it should be the name of the application) and last the servlet name: http://localhost:8080/appname/helloworld
There is also an possible error on your Web.xml. The servlet class tag you defined your class but has no package. Probably you have the class also in a package.
package. HelloWorld
Verify if there is another application working on the same port as Apache Tomcat.
Try to clean your Apache Tomcat server.

Error 404: The requested resource is not available using HelloWorld servlet [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 1 year ago.
I am writing a Java Servlet, and I am struggling to get a simple HelloWorld example to work properly.
The HelloWorld.java class is:
package crunch;
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 {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
I am running Tomcat v7.0, and have already read similar questions, with responses referring to changing the invoker servlet-mapping section in web.xml. This section actually doesn't exist in mine, and when I added it the same problem still occurred.
Try this (if the Java EE V6)
package crunch;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
#WebServlet(name="hello",urlPatterns={"/hello"}) // added this line
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
now reach the servlet by http://127.0.0.1:8080/yourapp/hello
where 8080 is default Tomcat port, and yourapp is the context name of your applciation
You definitely need to map your servlet onto some URL. If you use Java EE 6 (that means at least Servlet API 3.0) then you can annotate your servlet like
#WebServlet(name="helloServlet", urlPatterns={"/hello"})
public class HelloWorld extends HttpServlet {
//rest of the class
Then you can just go to the localhost:8080/yourApp/hello and the value should be displayed. In case you can't use Servlet 3.0 API than you need to register this servlet into web.xml file like
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>crunch.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
Writing Java servlets is easy if you use Java EE 7
#WebServlet("/hello-world")
public class HelloWorld extends HttpServlet {
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Hello World");
out.flush();
}
}
Since servlet 3.0
The good news is the deployment descriptor is no longer required!
Read the tutorial for Java Servlets.
this is may be due to the thing that you have created your .jsp or the .html file in the WEB-INF instead of the WebContent folder.
Solution: Just replace the files that are there in the WEB-INF folder to the Webcontent folder and try executing the same - You will get the appropriate output
For those stuck with "The requested resource is not available" in Java EE 7 and dynamic web module 3.x, maybe this could help: the "Create Servlet" wizard in Eclipse (tested in Mars) doesn't create the #Path annotation for the servlet class, but I had to include it to access successfuly to the public methods exposed.
You have to user ../../projectName/Filename.jsp in your action attr. or href
../ = contains current folder simple(demo.project.filename.jsp)
Servlet can only be called with 1 slash forward to your project name..
My problem was in web.xml file. In one <servlet-mapping> there was an error inside <url-pattern>: I forgot to add / before url.

Servlet excecution in Tomcat 7

I have installed JDK 1.7 and Tomcat 7.0. I am unable to execute basic servlet program. Kindly tell me the process of execution. And just give me details what are new things in Tomcat 7.0.
If I have to place any annotation like #WebServlet, tell me in which file I have to place and which packages I have to import.
web.xml
<web-app>
<servlet>
<servlet-name>kiru</servlet-name>
<servlet-class>DatesrvApp</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>kiru</servlet-name>
<servlet-pattern>/classes/date</servlet-pattern>
</servlet-mapping>
</web-app>
DatesrvApp.java
import javax.servlet.*;
import java.io.*;
import java.util.*;
public class DatesrvApp extends GenericServlet {
public void service(ServletRequest req,ServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Date d = new Date();
pw.println("<b><center>Date and Time is" + d.toString() + "</center></b>");
pw.close();
}
}
GenericServlet servlet can't read your URL pattern, Please use HttpServlet.
you should put
<url-pattern>/classes/date</url-pattern>
instead of
<servlet-pattern>/classes/date</servlet-pattern>
And put servlet-api.jar file from lib folder of the directory where Tomcat 7.0 is installed in your classpath.
Please use HttpServlet as suggested by Masud.

Categories

Resources