1120245-Unit 06 - Servlets
1120245-Unit 06 - Servlets
Unit 06 - Servlets
Introduction to Servlets
Definition: Servlets are small programs that execute on the server side of a web connection.
Functionality: They dynamically extend the functionality of a web server, similar to how applets
extend web browsers.
Characteristics:
● Secure
● Portable
● Easy to use
Execution: Servlets run within the Java Virtual Machine (JVM) and are independent of browser
compatibility.
Servlet's Job
● Read explicit data sent by the client (e.g., form data).
● Read implicit data sent by the client (e.g., request headers).
● Generate results based on the request.
● Send explicit data back to the client (e.g., HTML content).
● Send implicit data to the client (e.g., status codes, response headers).
Key Points:
The client always initiates a transaction.
The server cannot contact the client directly or make a callback connection.
Either party can terminate the connection prematurely.
HTTP Requests
Structure of an HTTP Request:
Method—URI—Protocol/Version
Request Headers
Entity Body
Advanced Java Programming
HTTP Responses
Structure of an HTTP Response: An HTTP response has three main components:
● Protocol—Status code—Description: Provides the HTTP version, status code, and a
description of the response status.
● Response Headers: Contains metadata about the response, such as server information,
content type, date, and content length.
● Entity Body: Holds the content being returned, such as HTML or other data.
Example:
HTTP/1.1 200 OK
Server: Microsoft-IIS/4.0
Date: Mon, 3 Jan 1998 13:13:33 GMT
Content-Type: text/html
Last-Modified: Mon, 11 Jan 1998 13:23:42 GMT
Content-Length: 112
Entity Body:
<HTML>
<HEAD><TITLE>HTTP Response Example</TITLE></HEAD>
<BODY>Welcome to Brainy Software</BODY>
</HTML>
Advanced Java Programming
PHP:
An open-source technology popular for web development, offering session management and
built-in features like file upload.
Servlets:
Introduced by Sun Microsystems in 1996, servlets enable Java-based web applications.
ASP.NET:
Part of Microsoft’s .NET framework, ASP.NET provides robust features such as state
management independent of cookies or URL rewriting. It runs on the Common Language
Runtime, similar to Java Virtual Machine.
Benefits of Servlets
Efficiency: Uses lightweight Java threads rather than separate processes, improving performance.
Persistency: Remains in memory, allowing state maintenance between requests.
Portability: Written in Java, so servlets are platform-independent.
Robustness: Java provides error handling and garbage collection, helping manage memory
effectively.
Extensibility: Supports inheritance and polymorphism, allowing easy subclass customization.
Security: Enhanced by Java Security Manager, avoiding risks of executing CGI scripts via OS
shells.
Powerful: Can interact directly with web servers, supporting database connection pooling and
session tracking.
Convenience: Simplifies tasks like form data parsing, HTTP header management, and cookie
handling.
Rapid Development Cycle: Java’s extensive library accelerates the development process.
Widespread Acceptance: Java’s popularity means easy access to third-party components, saving
development time.
Servlet Development Requirement: Requires a Java Development Kit (JDK) as Tomcat itself is
entirely Java-based.
The javax.servlet package is indeed a fundamental part of Java EE used for creating servlets,
which are Java programs that run on a web server and handle client requests. Here’s a brief
overview of the components:
Interfaces
Classes
Exceptions
These components provide the foundation for servlet development in Java, allowing for web
applications that process requests and dynamically generate responses.
Advanced Java Programming
Servlet Loading
● Loads the servlet when it’s first requested by a client.
Method Execution Flow
● Calls the init() method upon loading.
● Handles requests by invoking the service() method repeatedly.
● Calls the destroy() method when shutting down.
Advanced Java Programming
init() Method
Called once when the servlet is loaded, before any request is processed.
Steps involved:
Checks if the servlet is already loaded.
If not loaded, uses a class loader to get the servlet class and creates an instance.
Initializes resources, e.g., establishing a database connection.
Takes a ServletConfig object as a parameter:
● public void init(ServletConfig config) throws ServletException
Common Practice:
Calls super.init(config) to pass the ServletConfig object to the superclass.
service() Method
Handles client requests and executes only after init() has completed.
Functionality:
A single servlet instance services all requests.
Each request is processed in a separate thread.
Used in GenericServlet for general request handling.
In HttpServlet:
service(HttpServletRequest, HttpServletResponse) examines the request type and calls
appropriate methods like doGet() or doPost().
Common Practice:
Override doGet() or doPost() in HTTP servlets instead of service() for specialized request
handling.
Advanced Java Programming
destroy() Method
Marks the end of the servlet’s lifecycle.
Tasks performed:
Releases resources allocated in init().
Saves persistent data for the next servlet load.
The servlet engine, not the application, manages the unloading of the servlet by calling destroy().
ServletRequest Interface
The ServletRequest interface provides essential methods to access information about the user's
request, such as:
User Information:
● getRemoteAddr(): Retrieves the IP address of the client.
● getRemoteHost(): Retrieves the host name of the client.
Additional Information:
● getServerPort(), getServerName(), getProtocol(), etc., to obtain server details.
● getCharacterEncoding(), getContentType(), getContentLength() to get details on request
content.
Example
index.html
This HTML form sends a request to the servlet when submitted.
<HTML>
<HEAD>
<TITLE>Sending a request</TITLE>
Advanced Java Programming
</HEAD>
<BODY>
<FORM ACTION="http://localhost:8080/examples/servlets/servlet/RequestDemoServlet"
METHOD="POST">
<BR><BR>
Author: <INPUT TYPE="TEXT" NAME="Author">
<INPUT TYPE="SUBMIT" NAME="Submit">
<INPUT TYPE="RESET" VALUE="Reset">
</FORM>
</BODY>
</HTML>
RequestDemoServlet.java
This servlet receives the request and prints details from the ServletRequest object.
import javax.servlet.*;
import java.util.Enumeration;
import java.io.IOException;
ServletResponse Interface
Purpose: Represents the server's response to the user.
Key Method:
getWriter(): Returns a java.io.PrintWriter object to write HTML and other text to the client. This
is commonly used for generating dynamic HTML responses.
Example Code
index2.html
This HTML form collects the author's name and submits it to ResponseDemoServlet.
<HTML>
<HEAD>
<TITLE>Sending a request</TITLE>
Advanced Java Programming
</HEAD>
<BODY>
<FORM ACTION="http://localhost:8080/examples/servlets/servlet/ResponseDemoServlet"
METHOD="POST">
<BR><BR>
Author: <INPUT TYPE="TEXT" NAME="Author">
<INPUT TYPE="SUBMIT" NAME="Submit">
<INPUT TYPE="RESET" VALUE="Reset">
</FORM>
</BODY>
</HTML>
ResponseDemoServlet.java
This servlet processes the request and sends the response as HTML content to the client.
import javax.servlet.*;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.Enumeration;
out.println("<BODY>");
out.println("<B>Demonstrating the ServletResponse object</B>");
out.println("<BR><BR>");
out.println("</BODY>");
out.println("</HTML>");
}
return null;
}
}
GenericServlet
The GenericServlet class simplifies the process of creating servlets by implementing the Servlet
and ServletConfig interfaces. It also implements java.io.Serializable.
Benefits:
● Simplified Code: By providing blank implementations of all five methods in the Servlet
interface, it allows us to override only the methods we need.
● Ease of Use: We don’t need to manually handle the ServletConfig object because
GenericServlet manages it internally, providing easy access with getServletConfig().
Example Code: SimpleServlet
The example below shows a servlet called SimpleServlet that extends GenericServlet and
overrides only the service method. This servlet responds with an HTML page that contains a
simple message.
import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
}
}
HttpServlet
The HttpServlet class, extending GenericServlet, provides built-in methods to handle
HTTP-specific requests.
Key Methods:
● doGet: Called when an HTTP GET request is received. Typically used for requests where
data is passed in the URL query string.
● doPost: Called when an HTTP POST request is received. Commonly used for submitting
form data securely in the request body.
● Other Methods: Additional HTTP methods such as doPut, doDelete, doOptions, and
doTrace correspond to PUT, DELETE, OPTIONS, and TRACE requests.
Example Code: RegisterServlet
This servlet demonstrates the doGet() and doPost() methods. When the user submits a form using
POST, doPost() is called; if they access the URL directly or use GET, doGet() is invoked.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// HTML response
out.println("<HTML>");
out.println("<HEAD><TITLE>The GET method</TITLE></HEAD>");
out.println("<BODY>");
out.println("The servlet has received a GET request. Now, click the button below.");
out.println("<FORM METHOD=POST>");
Advanced Java Programming
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// HTML response
out.println("<HTML>");
out.println("<HEAD><TITLE>The POST method</TITLE></HEAD>");
out.println("<BODY>");
out.println("The servlet has received a POST request. Thank you.");
out.println("</BODY>");
out.println("</HTML>");
}
}
doGet Method:
● This method is invoked when the user accesses the servlet directly via a URL or when a
GET request is sent.
● It responds with an HTML form containing a POST request button.
doPost Method:
● Triggered by submitting the form (POST request).
● Responds with a thank-you message, acknowledging the POST request.
import javax.servlet.*;
import javax.servlet.
.*;
import java.io.*;
import java.util.*;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
out.println("</BODY>");
out.println("</HTML>");
}
}
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
while (parameterNames.hasMoreElements()) {
String parameterName = parameterNames.nextElement();
out.println(parameterName + ": " + request.getParameter(parameterName) + "<BR>");
}
out.println("</BODY>");
out.println("</HTML>");
}
}
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Check credentials
if (!validUsername.equals(username) || !validPassword.equals(password)) {
// Send error response if login fails
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Login failed. Please check
your username and password.");
return; // Stop further processing
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Display login form for GET requests
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Login Page</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<FORM METHOD='POST'>");
out.println("Username: <INPUT TYPE='text' NAME='username'><BR>");
out.println("Password: <INPUT TYPE='password' NAME='password'><BR>");
out.println("<INPUT TYPE='submit' VALUE='Login'>");
out.println("</FORM>");
out.println("</BODY>");
out.println("</HTML>");
}
}
Advanced Java Programming
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("</HTML>");
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Request Dispatching
Request dispatching in servlets allows you to manage how requests and responses are processed
by forwarding or including content from other resources, such as other servlets, JSP pages, or
HTML files. The RequestDispatcher interface provides two primary methods for this purpose:
include and forward.
Advanced Java Programming
RequestDispatcher Interface: This interface is found in the javax.servlet package and facilitates
request handling in servlets.
Methods:
● include Method: This method includes the content of another resource in the response. It
allows the current servlet to include content dynamically from another servlet, JSP, or
HTML page.
● forward Method: This method forwards the request to another resource. Unlike include,
the original servlet's processing stops after forwarding.
forward:
● Forwards the request directly to another resource without involving the client’s browser.
● Retains the original HttpServletRequest and HttpServletResponse objects.
● Allows seamless passing of request attributes to the forwarded resource.
Session tracking and management are essential in web applications to maintain state across
multiple requests from the same client, especially in a stateless protocol like HTTP. Here's an
overview of the concepts and methods involved in session management.
stateless nature means that the server does not remember past requests from the same
client.
● Implications of Statelessness: The lack of persistent state can lead to issues in scenarios
like online shopping, where users might want to add multiple items to a shopping cart
without losing previous selections.
● URL Rewriting:
In this technique, session identifiers are appended to URLs. When a user navigates the
site, their session ID is included in the URL, allowing the server to associate requests
with the corresponding session. This method is useful when cookies are disabled in the
user's browser, but it can make URLs lengthy and less readable.
● Persistent Cookies:
Cookies are small pieces of data stored on the client’s browser that can persist between
sessions. A server can set a cookie containing a session identifier, which the browser will
send back with each subsequent request. This allows the server to recognize the user and
retrieve their session data.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
// Other processing...
}
}
User Authentication
● Users log in using a username and password.
● The server tracks sessions based on the logged-in user's username.
● Advantages: Simple to implement; maintains sessions even across different machines.
● Disadvantages: Requires user registration; no logout mechanism with basic
authentication; users cannot maintain multiple sessions simultaneously.
String name = req.getRemoteUser();
if (name == null) {
// Handle unauthorized access
} else {
String[] items = req.getParameterValues("item");
if (items != null) {
for (String item : items) {
addItemToCart(name, item);
}
}
}
Advanced Java Programming
URL Rewriting
● Appends session information (like a session ID) to URLs, enabling the server to track
sessions.
● Advantages: Works well with all servers.
● Disadvantages: Limited space for information and potential naming collisions with added
parameters.
Cookies
● Small pieces of data stored on the client side that are sent back to the server with each
request.
● Example: Creating cookies in a servlet and retrieving them upon subsequent requests.
● Advantages: Persistent storage on the client side and widely supported.
● Disadvantages: Users can disable cookies; security concerns regarding sensitive
information.
Advanced Java Programming
●
Cookie c1 = new Cookie("userName", "Helen");
Cookie c2 = new Cookie("password", "Keppler");
response.addCookie(c1);
response.addCookie(c2);
2. Deleting a Cookie
To delete a cookie, you can set its maximum age to zero. Here’s an example of how to handle the
removal of a book from a shopping cart:
3. Sending Cookies
Cookies must be sent to the client before you write any content to the response. Use addCookie()
method to send cookies:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Your Shopping Cart</title></head><body>");
4. Retrieving Cookies
You can retrieve cookies sent by the client using getCookies() method. Here’s how to do it:
Example Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Retrieve cookies
Cookie[] cookies = request.getCookies();
if (cookies != null) {
Advanced Java Programming
out.println("<h2>Cookies:</h2>");
for (Cookie cookie : cookies) {
String name = cookie.getName();
String value = cookie.getValue();
out.println(name + " = " + value + "<br>");
}
}
out.println("<form method='get'>");
out.println("Cookie Name: <input type='text' name='cookieName'><br>");
out.println("Cookie Value: <input type='text' name='cookieValue'><br>");
out.println("<input type='submit' value='Set Cookie'>");
out.println("</form>");
}
}
Retrieving the Session: For subsequent requests, the client sends back the session identifier,
allowing the server to retrieve the associated HttpSession object.
Accessing Session Attributes: You can store and retrieve data associated with the session using
methods provided by the HttpSession interface.
● Session Information
○ String getId(): Returns the session identifier.
○ long getCreationTime(): Returns the time the session was created.
○ long getLastAccessedTime(): Returns the time the session was last accessed.
○ int getMaxInactiveInterval(): Returns the time before the session expires.
● Session Lifecycle
○ void invalidate(): Invalidates the session.
○ boolean isNew(): Checks if the session is newly created.
○ void setMaxInactiveInterval(int interval): Sets the maximum inactive interval for
the session.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
HttpSessionEvent
The HttpSessionEvent class is used to indicate that a session has been created or destroyed.
Advanced Java Programming
Associated Listener: The HttpSessionListener interface listens for session lifecycle events,
allowing you to respond to these events.
Methods:
getSession(): Returns the HttpSession object associated with the event.
HttpSessionBindingEvent
The HttpSessionBindingEvent class is used to notify listeners when an object is bound or
unbound to a session. This is particularly useful for tracking the addition or removal of attributes
in a session.
Associated Listener: The HttpSessionAttributeListener interface listens for changes to attributes
in a session.
Methods:
getName(): Returns the name of the attribute that is being added or removed.
getValue(): Returns the value of the attribute that is being added or removed.
getSession(): Returns the HttpSession object associated with the event.