Servlet : Not able to run the Hello World Program - java

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.

Related

Cannot access servlet using Eclipse and Tomcat 9

I created a new dynamic web project called TestWeb in Eclipse. I added a single index.html to the WebContent folder and created a single web servlet, making the servlet available at /Test.
I can access the index.html file at http://localhost:8080/TestWeb, however, I cannot access the servlet at http://localhost:8080/TestWeb/Test. Please assist.
Here is the code for the Servlet:
#WebServlet("/Test")
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
}
Here is 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" id="WebApp_ID" version="4.0">
<display-name>TestWeb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Firstly check your web.xml (deployment descriptor) file, make sure it has correct xml schema defined in it and if everything is good there then change you annotation like this
#WebServlet("/Test/*")
I soled the issue by renaming the project. My project name consisted of two words and one space. "Password Services". Once I renamed the project to "Server" I could reach the servlet.

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.

Output of ServletProgram created using Servlet Interface is not getting as Expected? [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 created a Servlet Program using Servlet Interface and I am just Sending my response to the Browser using response interface method getWriter() which returns PrintWriter reference and I am trying to print the following Information such as Hello and a Date on the Browser.
But,I am getting a following 404 Error.
Can anyone guide me Why?
Code for my Servlet Program.
class FirstAppUsingServlet implements Servlet
{
public void init(ServletConfig config) throws ServletException
{
}
public void destroy()
{
}
public ServletConfig getServletConfig()
{
return null;
}
public String getServletInfo()
{
return null;
}
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
Date d1=new Date();
System.out.println(d1);
PrintWriter out=response.getWriter();
out.println("Hello Java");
out.println(d1);
}
}
Code for the 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>FirstServletApp</display-name>
<servlet>
<description></description>
<display-name>FirstAppUsingServlet</display-name>
<servlet-name>FirstAppUsingServlet</servlet-name>
<servlet-class>FirstAppUsingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstAppUsingServlet</servlet-name>
<url-pattern>/FirstAppUsingServlet</url-pattern>
</servlet-mapping>
</web-app>
And the Following error:
http://localhost:8089/FirstServletApp/WEB-INF/classes/FirstAppUsingServlet.java
Do couple of things:
First check whether TOMCAT server started properly or not. For this, check
http://localhost:8080/ from the browser. I am assumming you have started server on 8080 port.
If Server is started properly, then you will see TOMCAT home page. If it is not, then you have to check JAVA_HOME environmental variable setting.
Check if you have any error on console page of your editor.
Check if your URL is correct because you haven't pasted URL here.

My .jsp AJAX call is returning the code from my Servlet controller instead of executing it

I have an index.jsp calling a Java controller which performs an operation and returns a result. All the code is sitting in a server. So I have Tomcat running on the server and call the index page from my local machine. The problem is that the AJAX that calls the controller is bringing back the whole Java code instead of executing it in the server and bringing back the result. So I'm literally getting
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginController extends HttpServlet {
public LoginController()
{
super();
}
etc. This is the Ajax code:
function loadRows()
{
var review_ID = location.search.split('review=')[1];
$.ajax({
url : "../src/mvcdemo/controllers/LoginController.java",
type : "post",
data : {
"reviewID" : review_ID
},
success : function(data) {
alert(data);
...
}
});
PS: Java IS installed in the server, and the whole project works fine if I run it from my localhost. The problem is in the communication between the local machine and the server. Also, when running it on my localhost, the URL is just "LoginController" but when running it on the server it was not finding the file, so I had to use the relative path and add the ".java" at the end for it to work, I'm not sure if that has anything to do with it.
Thanks in advance for any info!
EDIT:
I am using web.xml to define my Servlets, this is the 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" 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>MVCDemo</display-name>
<servlet>
<description></description>
<display-name>LoginController</display-name>
<servlet-name>LoginController</servlet-name>
<servlet-class>mvcdemo.controllers.LoginController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginController</servlet-name>
<url-pattern>/LoginController</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>UpdateController</display-name>
<servlet-name>UpdateController</servlet-name>
<servlet-class>mvcdemo.controllers.UpdateController</servlet-class>
</servlet>
<servlet>
<description></description>
<display-name>SubmitController</display-name>
<servlet-name>SubmitController</servlet-name>
<servlet-class>mvcdemo.controllers.SubmitController</servlet-class>
</servlet>
Correct me if I am wrong but your jsp is not calling the controller.
Solution 1
Anyway try this using servlet 3.0 annotations (not tested):
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/login")
public class LoginController extends HttpServlet {
public LoginController() {
super();
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
// do whatever it is you want
}
}
Then
$.ajax({
url : "/login",
type : "post",
data : {
"reviewID" : review_ID
},
success : function(data) {
alert(data);
...
}
});
Solution 2
If you cannot use servlet 3.0 annotations (which are really useful and more intuitive than web.xml)
Then you will have to use web.xml
You need to make sure that your web.xml is being loaded by the server correctly.

I'm having problems with my first servlet

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:

Categories

Resources