#
Java Servlet (GET Method)
This tutorial explains to you what a Java Servlet is and will provide you with a short Java Servlet example (with doGet() | GET Method).
A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Web servlets are the Java counterpart to other dynamic Web content technologies such as PHP and ASP.NET. Using Servlets in Java, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.
The servlets could respond to a GET or to a POST Call Method.
In this response I will show you an example of responding to a GET Method Call. Similar you can create a Java servlet to respond to a POST Call.
First, you have to create an HTML page. Let's define it as an index page into the Web Dynamic Project:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>From this page you call a Java servlet using GET Method</title>
</head>
<body>
<form action="MyJavaServlet" method="GET">
Name: <input type="text" name="name"> <br />
Telephone#: <input type="text" name="telephone" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Here is the web.xml file:
And here is the code (the example) of my Java servlet which respond to a GET Method call :
package servlets;
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 MyJavaServlet
*/
@WebServlet("/MyJavaServlet")
public class MyJavaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MyJavaServlet() {
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
PrintWriter myResponse = response.getWriter();
String message = "This is your response from a GET call. <br> The response is a Java Servlet !";
myResponse.println( "\n" +"<title> Example of using Java Servlet with GET Call Method !</title>\n" +
"\n" +
"<h2 align="\"center\"">" + message + "</h2>\n" +
"<ul>\n" +
" <li><b>You entered the name </b>: " + request.getParameter("name") + "\n" +
" </li><li><b>You entered the telephone# </b>: " + request.getParameter("telephone") + "\n" +
"</li></ul>\n" +
"");
}
}