How to run servlet in Eclipse? - java

Installation Details:
First I install the jdk then add a environment variable
variable name = "path"
variable value ="C:\Program Files\Java\jdk1.7.0_45\bin"(directory of java)
Then Extract the eclipse and tomcat
After extracting, I edit the catalina.bat from apache-tomcat-7.0.23\bin and add this:
"set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_45"
Then I made my first Servlet by creating new dynamic web project
<!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=UTF-8">
<title>Test Form</title>
</head>
<body>
<h1>JAVA TEST</h1>
<form action ="work.html" method ="get">
<input type="submit" value="login">
</form>
</body>
</html>
import java.io.IOException;
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;
/**
* Servlet implementation class work
*/
#WebServlet("/work.html")
public class work extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public work() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<html>");
out.print("<head>");
out.print("<title>Login Authentication Result</title>");
out.print("<h2>Welcome to servlet</h2>");
out.print("<p> powered by" + getServletContext().getServerInfo()+ "</p>");
out.print("</body>");
out.print("</hmtl>");
out.close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
<?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>Test3</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>
</web-app>
I'm new to servlet. I don't know why it is always have this error when clicking the button in the index.html
I think I have the same problem

Just configure Tomcat in eclipse!

Related

Http 404 resource not found [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 servlets and jsp. I did a small application on Eclipse JEE version. But when I am executing I am getting 'http 404: resource not found' error even though the Tomcat has been installed properly on Eclipse. Here is the code I am using:
This is my ServletDemo.java
package com.advancejava;
import java.io.IOException;
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;
/**
* Servlet implementation class ServletDemo
*/
#WebServlet(description = "ServletDemo", urlPatterns = { "/ServletDemo" })
public class ServletDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ServletDemo() {
super();
// TODO Auto-generated constructor stub
}
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/html");
try(PrintWriter pw = response.getWriter()) {
pw.println("<!DOCTYPE html>");
pw.println("<html>");
pw.println("<head>");
pw.println("<body>");
pw.println("<h1>Servlet Demo"+request.getContextPath()+"</h1>");
pw.println("</body>");
pw.println("</html>");
}
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
try{
pw.println("<html>");
pw.println("<head>");
pw.println("<title>Servlet</title>");
pw.println("</head>");
pw.println("<body>");
pw.println("<p>First DemoServlet</p>");
pw.println("</body>");
pw.println("</html>");
}
finally{
System.out.println("This is my Servlet Page");
}
}
}
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"
metadata-complete="true" version="3.0">
<display-name>ServletDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>ServletDemo</servlet-name>
<servlet-class>com.advancejava.ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDemo</servlet-name>
<url-pattern>/ServletDemo</url-pattern>
</servlet-mapping></web-app>
my index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Advance java
</body>
</html>
If there are any mistakes, please forgive me and suggest me how to correct them.
Since you've already declare your servlet at
#WebServlet(description = "ServletDemo", urlPatterns = { "/ServletDemo" })
don't declare twice in your web.xml.
the url to your servlet should be
http://localhost:8080/{contextPath}/ServletDemo
the contextPath will be your projectName by default if you use eclipse
there is one more thing, delete metadata-complete="true" in your web.xml. Otherwise it won't work.
<?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"
version="3.0">
<display-name>ServletDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Previous response: The index page should be "my index.html" or "index.html".
It needs to go right with what is in the servlet.
index.html
Posting it twice really is the problem. I'm glad this has been resolved. it's helpful to me as well. Thanks

Asynchronous Servlets or Filters don't work

I'm new to Java EE and was about to learn to use asynchronous Servlets. I created a web application with a simple index.jsp from which the servlet is called after pressing a button. I always get the following exception:
java.lang.IllegalStateException: Request is within the scope of a
filter or servlet that does not support asynchronous operations
But I set async-supported to true as annotation in the servlet or in web.xml or in both ways. I was searching for hours through similar questions here but I couldn't find a solution. I'm using NetBeans 8.0.2 and glassfish server 4.1 that comes along with NetBeans. Here is my index.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Async Test</h1>
<form method="get" action="Asynctest">
<input type="submit"
value="Start test">
</form>
</body>
</html>
the Asynctest servlet:
package Controller;
import java.io.IOException;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(asyncSupported = true, name = "Asynctest", urlPatterns = {"/Asynctest"})
public class Asynctest extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
AsyncContext ac = request.startAsync(request, response);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
and the web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>Asynctest</servlet-name>
<servlet-class>Controller.Asynctest</servlet-class>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>Asynctest</servlet-name>
<url-pattern>/Asynctest</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
It makes me crazy.. Thanks for your help!

Ajax call from JavaScript to servlet

I am trying to make AJAX call from html file to a servlet class to pass a variable but not getting any output. Please check the code below and suggest the changes that should be done.
This is my project structure
FrontPage.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function func() {
var build = document.getElementById('name').textContent;
$.ajax({
type : 'GET',
url : 'http://localhost:8081/Sample/TestServlet',
data : build,
success : function(data) {
alert("Success");
},
error : function() {
alert("Error");
}
});
}
</script>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a id="name" href="#" onClick="func();">Build1</a>
</body>
</html>
This is TestServlet.java. This is trying to print variable which is passed from javascript function using Ajax call:
package com.infy;
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;
/**
* Servlet implementation class TestServlet
*/
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TestServlet() {
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
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println(request.getParameter("build"));
}
}
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" 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>Sample</display-name>
<welcome-file-list>
<welcome-file>FrontPage.html</welcome-file>
</welcome-file-list>
<servlet>
<description>Sample Servlet</description>
<display-name>TestServlet</display-name>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.infy.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
</web-app>
I want to send the build variable to the servlet class and print the same from the servlet class but not getting any output.Please help me in fixing this.
you are sending the request as GET method and you are not passing the variable in url.Try to print the build value in servlet first and check weather it is coming to servlet or not.
You should send the GET request as :-
url : "/TestServlet?build="+build+",
type : "GET"
,
And watch out the URL also.
in servlet site create a json object.Like
JSONObject jsonObj = new JSONObject();
jsonObj.put("build", build);
Try it and let me know.

Servlet not displaying anything while called

I am just writing the code after a while for servlet/jsp.
When I am calling servlet it is giving me blank browser and even not an error.
My Jsp :
<%# 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>Insert title here</title>
</head>
<body>
<form action="HelloServlet" method="POST">
Please enter a color <br>
<input type="text" name="color"size="20px">
<input type="submit" value="submit">
</form>
</body>
</html>
My Servlet :
import java.io.IOException;
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;
/**
* Servlet implementation class HelloServlet
*/
#WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HelloServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#service(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Servlet called...");
String color = request.getParameter("color");
PrintWriter out = response.getWriter();
/*
* out.println(
*
* "<html> \n" + "<head> \n" +
* "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"> \n"
* + "<title> My first jsp </title> \n" + "</head> \n" + "<body> \n" +
* "<font size=\"12px\" color=\"" + color + "\">" + "Hello World" +
* "</font> \n" + "</body> \n" + "</html>");
*/
out.println("Aman.............");
}
/**
* #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);
}
}
And 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/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">
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
<display-name>TestApp</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>
</web-app>
Please help me out in this.
Thanks,
Aman
Add super to the following function and everything will work
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
**super(request, response) // add this**
}
The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers).
You have overrided the function which is responsible for calling doget and post.
Hope this solves your query
The mistake you made is you are using both annotation as well as registering the servlet through deployment descriptor (web.xml).
If you use annotation,registering the servlet through deployment descriptor is not required. But you should have tomcat7 as it will not run in the previous versions of tomcat. #WebServlet annotation is used to map the servlet with the specified name.
Moreover I assume that you are not using any package because in the url-mapping you dint specify one. But in case you are using some package named mypackage and your servlet class is inside it then change the url-mapping to something like this
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>mypackage.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
The protected service method checks the type of request, if request type is get, it calls doGet method, if request type is post, it calls doPost method, so on
try to remove this method,and your servlet should work
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
or rewrite your service method using this :
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String method = request.getMethod();
if(method.equals("GET"))
doGet(request, response);
else
doPost(request, response);
}
You don't write anything in service method so that it will never call either doPost or doGet

Java Servlet JSP does not print out attribute

I'm trying to write a servlet using generated HTML code, rather then printing out static HTMLs.
I'm using Eclipse-EE Europa and Tomcat 6.
I tried to use the flowing tips from HERE
But instead of printing the desired attribute It seems that the jsp ignoring the attribute or the attribute is empty.
Here is the servlet:
package com.serv.pac;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
* Servlet implementation class for Servlet: testServlet
*
*/
public class testServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#HttpServlet()
*/
public testServlet() {
super();
}
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "doGet response";
request.setAttribute("message", message);
request.getRequestDispatcher("/testServlet/WEB-INF/index1.jsp").forward(request, response);
PrintWriter out = response.getWriter();
out.println("the servlet");
}
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("first servlet");
}
}
Here is the JSP
<!doctype html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
And the following is the :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>servlet1_test</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>index1.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>testServlet</display-name>
<servlet-name>testServlet</servlet-name>
<servlet-class>com.serv.pac.testServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/testServlet</url-pattern>
</servlet-mapping>
</web-app>
And that is what I'm getting in the browser:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: </p>
</body>
</html>
As one may see there is nothing after the "Message" in the html body, as if the message attribute is empty.
Thank You
The only way I can see this happenning is you aren't actually accessing your Servlet.
You've declared a <welcome-file>
<welcome-file>index1.jsp</welcome-file>
So if you try to hit
localhost:8080/YourContextPath
the default Servlet will render and send you that jsp with a missing message attribute.
If you want to hit your actual Servlet, you need to use
localhost:8080/YourContextPath/testServlet
Note that you need to change
request.getRequestDispatcher("/testServlet/WEB-INF/index1.jsp").forward(request, response);
to
request.getRequestDispatcher("/WEB-INF/index1.jsp").forward(request, response);
and move your file under WEB-INF.

Categories