Java Serverletes
Java Serverletes
Background
1
o In this phase:
▪ The servlet processes the HTTP request.
▪ It can read data provided in the request (e.g., query parameters, form data).
▪ It formulates an HTTP response to send back to the client.
▪ The servlet remains in the server’s address space and handles subsequent
requests.
▪ The service( ) method is called for each HTTP request.
3. Cleanup and Unloading (destroy( )):
o If the server decides to unload the servlet (based on server-specific algorithms), it
calls the destroy( ) method.
o The destroy( ) method releases any allocated resources (e.g., file handles).
o Important data may be saved to a persistent storage before the servlet is removed.
In summary, the servlet life cycle involves initialization, request processing, and eventual cleanup.
Servlets provide dynamic functionality within the server’s address space, handling client requests
efficiently.
2
The process of setting up and using Tomcat for servlet development
1. Downloading and Installing Tomcat:
o To create and test servlets, you’ll need a servlet container or server like Apache
Tomcat.
o Extract the downloaded zip file to a suitable location on your system.
2. Compiling Servlets:
o Tomcat provides a .jar file called servlet-api.jar containing necessary class files for
servlet development.
o Locate servlet-api.jar in the TOMCAT_HOME\lib directory (where TOMCAT_HOME is
the Tomcat installation directory).
o Compile your servlets using the javac command. For example:
o javac HelloWorldServlet.java -classpath "C:\apache-tomcat-7.0.47-windows-
x64\apache-tomcat-7.0.47\lib\servlet-api.jar"
o This generates the .class file containing the bytecode for your servlet.
3. Setting Up the Directory Structure:
o Create the following directory structure under the webapps subdirectory of Tomcat:
o TOMCAT_HOME\webapps\net\WEB-INF\classes
o Place the compiled HelloWorldServlet.class file in the
TOMCAT_HOME\webapps\net\WEB-INF\classes directory.
4. Configuring web.xml:
o Edit the web.xml file located in:
o TOMCAT_HOME\webapps\net\WEB-INF
o Add the servlet’s name and mapping:
o <servlet>
o <servlet-name>HelloServlet</servlet-name>
o <servlet-class>HelloServlet</servlet-class>
o </servlet>
o <servlet-mapping>
o <servlet-name>HelloServlet</servlet-name>
o <url-pattern>/servlet/HelloServlet</url-pattern>
o </servlet-mapping>
5. Running the Servlet:
o Start Tomcat by running the startup.bat or startup.sh script in the bin directory.
o Access the servlet using the URL:
o http://localhost:8080/net/servlet/HelloServlet
By following these steps, you’ll be able to create, compile, and deploy servlets using Tomcat. Feel
free to experiment with the sample servlets provided by Tomcat to get started!
simple servlet
1. Creating and Compiling the Servlet Source Code:
o A servlet is a Java program executed within a web container (such as Apache
Tomcat).
o It handles client requests and server responses.
o The example servlet, HelloServlet, is a subclass of GenericServlet.
o The service() method (inherited from GenericServlet) processes requests.
o It takes a ServletRequest (for reading client data) and a ServletResponse (for
formulating the response).
3
o The setContentType("text/html") sets the MIME type for the HTTP response (HTML
in this case).
o The getWriter() method obtains a PrintWriter to write content to the client.
o The servlet responds with a simple HTML message: <B>Hello!</B>.
2. Deployment and Configuration:
o Compile the HelloServlet.java source code.
o Place the HelloServlet.class file in the proper Tomcat directory (as described earlier).
o Add HelloServlet to the web.xml file (deployment descriptor) to configure its
behavior.
3. Starting Tomcat:
o Ensure that Tomcat is running before executing the servlet.
4. Requesting the Servlet:
o Open a web browser and enter the URL:
▪ http://localhost:8080/examples/servlets/servlet/HelloServlet
o Alternatively, use the IP address 127.0.0.1:
▪ http://127.0.0.1:8080/examples/servlets/servlet/HelloServlet
o The browser will display the output of the servlet, showing the bolded string
“Hello!”.
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!</B>");
pw.close();
}
}
In summary, servlets provide a powerful way to handle client-server communication, and the
example demonstrates a basic servlet setup and execution.
Example Overview
o PostParameters.html: Defines an HTML form with two labels (Employee and Phone)
and corresponding text fields. The form submits data to a servlet via an HTTP POST
request.
4
2. HTML Form (PostParameters.html):
o <html>
o <body>
o <center>
o <form name="Form1" method="post"
action="http://localhost:8080/examples/servlets/servlet/PostPar
ametersServlet">
o <table>
o <tr>
o <td><b>Employee</td>
o <td><input type="textbox" name="e"
size="25" value=""></td>
o </tr>
o <tr>
o <td><b>Phone</td>
o <td><input type="textbox" name="p"
size="25" value=""></td>
o </tr>
o </table>
o <input type="submit" value="Submit">
o </form>
o </center>
o </body>
o </html>
o
3. Servlet (PostParametersServlet.java):
o For each parameter, we output its name and value to the client.
5
o pw.println(paramValue);
o }
o
o pw.close();
o }
o }
o
5. Result:
o The browser will display a dynamically generated response by the servlet, showing
the parameter names and their corresponding values.
Remember, this example demonstrates how to read parameters from an HTTP POST request. You can
adapt this approach to handle other types of data in your servlets.
6
▪ Writes the selected color to the response using PrintWriter.
▪ Closes the writer.
o Compile the servlet, copy it to the appropriate directory, and update the web.xml
file.
4. Testing the Example:
o Start Tomcat (if not already running).
o Open the web page in a browser.
o Select a color (e.g., Red).
o Submit the form.
o The browser displays the dynamically generated response from the servlet.
o The URL sent to the server includes the query string:
http://localhost:8080/examples/servlets/servlet/ColorGetServlet?color=Red.
Remember that parameters for an HTTP GET request are part of the URL’s query string. In this case,
the user’s selection (e.g., “Red”) is included in the URL when submitting the form.
<!DOCTYPE html>
<html>
<head>
<title>Color Selection</title>
</head>
<body>
<center>
<form name="Form1"
action="http://localhost:8080/examples/servlets/servlet/ColorGetServlet">
<b>Color:</b>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>
Serverlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
7
pw.println("<b>The selected color is: " + color + "</b>");
pw.close();
}
}
<!DOCTYPE html>
<html>
<head>
<title>Color Selection</title>
</head>
<body>
<center>
8
<form name="Form1" method="post"
action="http://localhost:8080/examples/servlets/servlet/ColorPostServlet">
<b>Color:</b>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
handling cookies
1. AddCookie.html (Web Page):
o This HTML page allows users to specify a value for the cookie named “MyCookie.”
o It contains:
▪ A text field where users can enter a value.
▪ A submit button.
o When the submit button is pressed, the value from the text field is sent to
AddCookieServlet via an HTTP POST request.
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlets/servlet/AddCookieServlet">
<b>Enter a value for MyCookie:</b>
<input type="textbox" name="data" size="25" value="">
9
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>
2. AddCookieServlet.java (Servlet for Setting Cookies):
o This servlet processes the submission from AddCookie.html.
o It retrieves the value of the parameter named “data” (the user’s input).
o Creates a Cookie object named “MyCookie” with the retrieved value.
o Adds this cookie to the header of the HTTP response using the addCookie() method.
o Writes a feedback message to the browser indicating that the cookie has been set.
o import java.io.*;
o import javax.servlet.*;
o import javax.servlet.http.*;
o
o public class AddCookieServlet extends HttpServlet {
o public void doPost(HttpServletRequest request, HttpServletResponse response)
o throws ServletException, IOException {
o String data = request.getParameter("data");
o // Create cookie.
o Cookie cookie = new Cookie("MyCookie", data);
o // Add cookie to HTTP response.
o response.addCookie(cookie);
o // Write output to browser.
o response.setContentType("text/html");
o PrintWriter pw = response.getWriter();
o pw.println("<B>MyCookie has been set to");
o pw.println(data);
o pw.close();
o }
o }
3. GetCookiesServlet.java (Servlet for Retrieving Cookies):
o This servlet displays cookie values.
o It invokes the getCookies() method to read any cookies included in the HTTP GET
request.
o For each cookie, it retrieves the name and value using the getName() and getValue()
methods.
o The servlet then writes these cookie names and values to the HTTP response.
o import java.io.*;
o import javax.servlet.*;
o import javax.servlet.http.*;
o
o public class GetCookiesServlet extends HttpServlet {
o public void doGet(HttpServletRequest request, HttpServletResponse response)
o throws ServletException, IOException {
o // Get cookies from header of HTTP request.
o Cookie[] cookies = request.getCookies();
o // Display these cookies.
10
o response.setContentType("text/html");
o PrintWriter pw = response.getWriter();
o pw.println("<B>");
o for (int i = 0; i < cookies.length; i++) {
o String name = cookies[i].getName();
o String value = cookies[i].getValue();
o pw.println("name = " + name + "; value = " + value);
o }
o pw.close();
o }
o }
11
▪ Creates a Date object representing the current date and time.
▪ Binds this new Date object to the “date” attribute using setAttribute("date",
date).
▪ Displays the current date and time.
4. Behavior:
o When you first request this servlet, the browser displays the current date and time.
o On subsequent invocations, two lines are displayed:
▪ The first line shows the date and time when the servlet was last accessed
(retrieved from the session attribute).
▪ The second line shows the current date and time (updated and stored in the
session).
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
12