0% found this document useful (0 votes)
24 views33 pages

1120245-Unit 06 - Servlets

Uploaded by

Sujal Sonawane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views33 pages

1120245-Unit 06 - Servlets

Uploaded by

Sujal Sonawane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Advanced Java Programming

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).

Hypertext Transfer Protocol (HTTP)


Definition: HTTP is the protocol used for data exchange between web servers and browsers.
Nature: Request and response protocol where the client requests a file, and the server responds.
Connection: Uses reliable TCP connections, typically on TCP port 80.
Versions:
HTTP/1.1 is the version defined in RFC 2616.
Initially defined in RFC 2068.

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

Example of an HTTP Request:


GET /servlet/default.jsp HTTP/1.1
Accept: text/plain; text/html
Accept-Language: en-gb
Connection: Keep-Alive
Host: localhost
Referer: http://localhost/ch8/SendDetails.htm
User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)
Content-Length: 33
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate

HTTP Request Overview


● Request Line:
○ Format: Method—URI—Protocol/Version
○ Example: GET /servlet/default.jsp HTTP/1.1
○ Method: Action type, like GET or POST.
○ URI (Uniform Resource Identifier): Identifies the resource, typically starting with
/ to indicate a path relative to the server’s root.
○ Protocol/Version: Specifies the HTTP protocol version, e.g., HTTP/1.1.
URI and URL
● URI: Specifies an Internet resource completely, usually as a relative path starting with /.
● URL: A type of URI that can be used as an address to access web resources directly.
Request Headers
● Contain details about the client’s environment and request metadata.
● Examples:
○ Accept-Language: Specifies browser language preference.
○ Content-Length: Specifies the length of the entity body data.
● Each header ends with a CRLF (Carriage Return/Line Feed) sequence.
Entity Body
● The data or parameters sent along with the request, often for POST requests.
● Example of Entity Body: LastName=Franks&FirstName=Michael
● CRLF Separator: A blank line (CRLF) between headers and the entity body signifies
where the entity body starts.
CRLF Importance
● The CRLF sequence is critical in HTTP requests as it:
○ Separates each header.
○ Marks the beginning of the entity body following a blank line.
Advanced Java Programming

HTTP Request Methods Overview


GET: Retrieves data from the server at the specified URL.
HEAD: Returns headers only, without the response body.
POST: Sends data to the server, often used for form submissions.
OPTIONS: Checks the server's capabilities or supported methods.
PUT: Uploads data to the server at the specified location.
DELETE: Removes a resource from the server.
TRACE: Tracks the route of a request for debugging purposes.

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

Servlet Application Architecture

Java Servlet Alternatives


ColdFusion:
Developed by Allaire, ColdFusion uses HTML-like custom tags for tasks like database queries.
It was once prominent in web application programming.

Server-side JavaScript (SSJS):


SSJS extends JavaScript to server-side use, allowing Java class access on the server via
Netscape’s LiveWire.

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.

JavaServer Pages (JSP):


JSP extends servlets, providing an alternative approach to web development using Java.

Active Server Pages (ASP):


Microsoft’s ASP uses scripting for Windows platforms, commonly with the Internet Information
Server. ASP is gradually being replaced by ASP.NET.
Advanced Java Programming

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.

How a Servlet Works


Loading: The servlet container loads the servlet the first time it is requested.
Request Processing: The servlet receives the request, processes it, and prepares a response.
Response Delivery: The servlet container sends the response back to the user.
Memory Persistence: The servlet remains in memory, ready for future requests, and is only
unloaded if memory runs low.
Auto-Reloading: Each request checks for updates; if the servlet's class file has a newer
timestamp, the servlet is reloaded without restarting the container.

The Tomcat Servlet Container


Popular Containers: Examples include Apache Tomcat, Allaire/Macromedia JRun, New
Atlanta ServletExec, Gefion Software LiteWebServer, and Caucho's Resin.
Apache Tomcat: The most widely used, considered the official servlet/JSP container, originally
by Sun Microsystems and now managed by the Apache Software Foundation.
Tomcat Version: Apache Tomcat version 6.0.18 is used as the servlet/JSP container reference.
Web Server Functionality: Tomcat can handle HTTP requests directly for servlets and static
files (e.g., HTML, images), though it’s often used with a more robust web server like Apache or
IIS for non-JSP/servlet requests.
Advanced Java Programming

Servlet Development Requirement: Requires a Java Development Kit (JDK) as Tomcat itself is
entirely Java-based.

The javax.servlet Package

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

1. RequestDispatcher: For dispatching requests to other resources (e.g., other servlets or


JSPs).
2. Servlet: The central interface to be implemented for creating a servlet.
3. ServletConfig: Provides configuration information for a servlet.
4. ServletContext: Allows servlets to access information about the servlet environment.
5. ServletRequest: Encapsulates client request information.
6. ServletResponse: Provides methods for sending a response back to the client.
7. SingleThreadModel: Ensures that servlets handle only one request at a time (now
deprecated).

Classes

1. GenericServlet: A protocol-independent servlet that implements Servlet and


simplifies creating custom servlets.
2. ServletInputStream: For reading binary data from a client request.
3. ServletOutputStream: For sending binary data in response to the client.

Exceptions

1. ServletException: General exception for servlet-related issues.


2. UnavailableException: Indicates that a servlet is temporarily or permanently
unavailable.

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 Life Cycle


The servlet life cycle has methods similar to the applet life cycle, but it's adapted to a
request-response model managed by a servlet engine. Here’s how the servlet engine handles a
servlet’s life cycle:

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().

Requests and Responses in Servlets


In a servlet application, the browser sends a request to the servlet container, which then forwards
it to the servlet.
Objects Used:
● ServletRequest: Represents the user request, passed as the first argument to the service
method.
● ServletResponse: Represents the server response, passed as the second argument to the
service method.

ServletRequest Interface
The ServletRequest interface provides essential methods to access information about the user's
request, such as:

Parameters: Allows retrieval of parameters sent by the user.


● getParameterNames(): Returns an Enumeration of parameter names.
● getParameter(String name): Retrieves the value of a specific parameter.

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;

public class RequestDemoServlet implements Servlet {

public void init(ServletConfig config) throws ServletException {


// Initialization code (optional)
}

public void destroy() {


// Cleanup code (optional)
}

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException {

System.out.println("Server Port: " + request.getServerPort());


System.out.println("Server Name: " + request.getServerName());
System.out.println("Protocol: " + request.getProtocol());
System.out.println("Character Encoding: " + request.getCharacterEncoding());
System.out.println("Content Type: " + request.getContentType());
System.out.println("Content Length: " + request.getContentLength());
System.out.println("Remote Address: " + request.getRemoteAddr());
Advanced Java Programming

System.out.println("Remote Host: " + request.getRemoteHost());


System.out.println("Scheme: " + request.getScheme());

Enumeration<String> parameters = request.getParameterNames();


while (parameters.hasMoreElements()) {
String parameterName = parameters.nextElement();
System.out.println("Parameter Name: " + parameterName);
System.out.println("Parameter Value: " + request.getParameter(parameterName));
}

Enumeration<String> attributes = request.getAttributeNames();


while (attributes.hasMoreElements()) {
String attribute = attributes.nextElement();
System.out.println("Attribute name: " + attribute);
System.out.println("Attribute value: " + request.getAttribute(attribute));
}
}

public String getServletInfo() {


return null;
}

public ServletConfig getServletConfig() {


return null;
}
}

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;

public class ResponseDemoServlet implements Servlet {

public void init(ServletConfig config) throws ServletException {


// Initialization code (optional)
}

public void destroy() {


// Cleanup code (optional)
}

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException {

// Get the PrintWriter to write response


PrintWriter out = response.getWriter();

// Write HTML content to the response


out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>ServletResponse</TITLE>");
out.println("</HEAD>");
Advanced Java Programming

out.println("<BODY>");
out.println("<B>Demonstrating the ServletResponse object</B>");
out.println("<BR><BR>");

// Display server and request details


out.println("Server Port: " + request.getServerPort() + "<BR>");
out.println("Server Name: " + request.getServerName() + "<BR>");
out.println("Protocol: " + request.getProtocol() + "<BR>");
out.println("Character Encoding: " + request.getCharacterEncoding() + "<BR>");
out.println("Content Type: " + request.getContentType() + "<BR>");
out.println("Content Length: " + request.getContentLength() + "<BR>");
out.println("Remote Address: " + request.getRemoteAddr() + "<BR>");
out.println("Remote Host: " + request.getRemoteHost() + "<BR>");
out.println("Scheme: " + request.getScheme() + "<BR>");

// Display request parameters


Enumeration<String> parameters = request.getParameterNames();
while (parameters.hasMoreElements()) {
String parameterName = parameters.nextElement();
out.println("Parameter Name: " + parameterName + "<BR>");
out.println("Parameter Value: " + request.getParameter(parameterName) + "<BR>");
}

// Display request attributes


Enumeration<String> attributes = request.getAttributeNames();
while (attributes.hasMoreElements()) {
String attribute = attributes.nextElement();
out.println("Attribute name: " + attribute + "<BR>");
out.println("Attribute value: " + request.getAttribute(attribute) + "<BR>");
}

out.println("</BODY>");
out.println("</HTML>");
}

public String getServletInfo() {


return null;
}

public ServletConfig getServletConfig() {


Advanced Java Programming

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;

public class SimpleServlet extends GenericServlet {

@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {

// Get PrintWriter to write response


PrintWriter out = response.getWriter();

// Write HTML content to the response


out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Extending GenericServlet</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("Extending GenericServlet makes your code simpler.");
out.println("</BODY>");
out.println("</HTML>");
Advanced Java Programming

}
}

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.*;

public class RegisterServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Set content type


response.setContentType("text/html");

// Get PrintWriter to write response


PrintWriter out = response.getWriter();

// 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

out.println("<INPUT TYPE=SUBMIT VALUE=Submit>");


out.println("</FORM>");
out.println("</BODY>");
out.println("</HTML>");
}

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Set content type


response.setContentType("text/html");

// Get PrintWriter to write response


PrintWriter out = response.getWriter();

// 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.

Usage Example in HTML Form


The following form sends a POST request to the RegisterServlet:

<FORM ACTION="Register" METHOD="POST">


<INPUT TYPE="TEXT" NAME="firstName">
Advanced Java Programming

<INPUT TYPE="TEXT" NAME="lastName">


<INPUT TYPE="SUBMIT">
</FORM>
Request Handling:
● When the form is submitted, the servlet receives the form data in the body (using POST).
● doPost processes the data, while doGet handles direct URL access, guiding the user to
submit data.

Obtaining HTTP Request Headers


The example below demonstrates how to use the HttpServletRequest interface to access all
HTTP request headers sent by a client. It iterates through the headers and displays each
name-value pair in the response.

import javax.servlet.*;
import javax.servlet.
.*;
import java.io.*;
import java.util.*;

public class RegisterServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Set the content type


response.setContentType("text/html");

// Get PrintWriter to write response


PrintWriter out = response.getWriter();

// Get all header names as an Enumeration


Enumeration<String> headerNames = request.getHeaderNames();

// Display each header name and its corresponding value


while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String headerValue = request.getHeader(headerName);
out.println(headerName + ": " + headerValue + "<BR>");
}
Advanced Java Programming

}
}

Obtaining the Query String


The getQueryString method of the HttpServletRequest interface allows servlets to retrieve the
query string from an HTTP request. The query string contains parameter name/value pairs that
are appended to the URL, typically when using the GET method in an HTML form.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class HttpRequestDemoServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Set the content type


response.setContentType("text/html");

// Get PrintWriter to write response


PrintWriter out = response.getWriter();

// Generate HTML response


out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Obtaining the Query String</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");

// Display the query string


out.println("Query String: " + request.getQueryString() + "<BR>");

// HTML form for user input


out.println("<FORM METHOD=GET>");
out.println("<BR>First Name: <INPUT TYPE=TEXT NAME=FirstName>");
out.println("<BR>Last Name: <INPUT TYPE=TEXT NAME=LastName>");
out.println("<BR><INPUT TYPE=SUBMIT VALUE=Submit>");
out.println("</FORM>");
Advanced Java Programming

out.println("</BODY>");
out.println("</HTML>");
}
}

Obtaining Parameters from HttpServletRequest


The getParameterNames and getParameter methods in the HttpServletRequest interface allow
servlets to retrieve form parameter name/value pairs without manually parsing the query string.
This is useful for handling HTML form data, especially when using the GET or POST methods.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class HttpRequestDemoServlet1 extends HttpServlet {

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Set the content type


response.setContentType("text/html");

// Get PrintWriter to write response


PrintWriter out = response.getWriter();

// Generate HTML response


out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Obtaining the Parameter</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");

// Display request parameters


out.println("The request's parameters are:<BR>");
Enumeration<String> parameterNames = request.getParameterNames();

// Iterate through parameter names and display each name/value pair


Advanced Java Programming

while (parameterNames.hasMoreElements()) {
String parameterName = parameterNames.nextElement();
out.println(parameterName + ": " + request.getParameter(parameterName) + "<BR>");
}

// HTML form for user input


out.println("<FORM METHOD=GET>");
out.println("<BR>First Name: <INPUT TYPE=TEXT NAME=FirstName>");
out.println("<BR>Last Name: <INPUT TYPE=TEXT NAME=LastName>");
out.println("<BR><INPUT TYPE=SUBMIT VALUE=Submit>");
out.println("</FORM>");

out.println("</BODY>");
out.println("</HTML>");
}
}

Sending an Error Code in a Servlet


Wcan use the sendError(int sc, String msg) method of HttpServletResponse to send an HTTP
error response. The sc parameter is the error code, and the msg parameter is the custom error
message you want to display.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class LoginServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Example login credentials (in a real application, validate against a database)


String validUsername = "admin";
String validPassword = "password";

// Retrieve parameters from the login form


String username = request.getParameter("username");
String password = request.getParameter("password");
Advanced Java Programming

// 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
}

// If login is successful, proceed with normal processing


PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Login Successful</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("Welcome, " + username + "!");
out.println("</BODY>");
out.println("</HTML>");
}

@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

Manipulating Multi-Value Parameters


The getParameterValues method is essential for handling multi-value parameters in servlets,
particularly when dealing with checkboxes or multiple-selection controls in HTML forms. This
method retrieves all values associated with a given parameter name, allowing the servlet to
process user selections effectively.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class HttpRequestDemoServlet2 extends HttpServlet {

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Generate HTML form


out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Obtaining Multi-Value Parameters</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<BR>");
out.println("<BR>Select your favorite singer:");
out.println("<BR><FORM METHOD=POST>");
out.println("<BR><INPUT TYPE=CHECKBOX NAME=favoriteMusic
VALUE=Alka>Alka");
out.println("<BR><INPUT TYPE=CHECKBOX NAME=favoriteMusic
VALUE=Shreya>Shreya");
out.println("<BR><INPUT TYPE=CHECKBOX NAME=favoriteMusic
VALUE=Sunidhi>Sunidhi");
out.println("<BR><INPUT TYPE=CHECKBOX NAME=favoriteMusic
VALUE=Kavita>Kavita");
out.println("<BR><INPUT TYPE=SUBMIT VALUE=Submit>");
out.println("</FORM>");
out.println("</BODY>");
Advanced Java Programming

out.println("</HTML>");
}

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Retrieve all selected values for the parameter "favoriteMusic"


String[] values = request.getParameterValues("favoriteMusic");

response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Check if any values were selected


if (values != null) {
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Selected Favorites</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("You have selected: ");

// Loop through the selected values and display them


for (String value : values) {
out.println("<BR>" + value);
}
out.println("</BODY>");
out.println("</HTML>");
} else {
out.println("No favorite music selected.");
}
}
}

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.

public void include(ServletRequest request, ServletResponse response) throws


ServletException, IOException;

● forward Method: This method forwards the request to another resource. Unlike include,
the original servlet's processing stops after forwarding.

public void forward(ServletRequest request, ServletResponse response) throws


ServletException, IOException;

Differences Between sendRedirect and forward


sendRedirect:
● Sends a status code to the client’s browser, prompting it to make a new request to a
different URL.
● Causes a round trip to the client, losing the original HttpServletRequest object.
● Data must be passed using query strings or session attributes since the request context is
lost.

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.

Understanding HTTP and Its Stateless Nature


● HTTP Protocol: The Hypertext Transfer Protocol (HTTP) is used for communication
between web browsers (clients) and web servers. Each HTTP request from a client results
in a separate connection to the server, which is closed after the response is sent. This
Advanced Java Programming

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.

Session Management Techniques


To manage user sessions effectively, several techniques can be employed:
● User Authentication:
This involves verifying a user's identity and associating a session with that user once they
log in. Once authenticated, the server can maintain user-related information (like user
preferences, shopping cart contents, etc.) during their session.

● Hidden Form Fields:


Web applications can use hidden fields in forms to store session-related data. When a user
submits a form, the server can read these hidden fields and retrieve the necessary session
information. However, this method can expose sensitive data to users if not handled
securely.

● 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.*;

public class SessionDemoServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Obtain the session object


Advanced Java Programming

HttpSession session = request.getSession();

// Check if this is a new session


if (session.isNew()) {
// Set an attribute in the session
session.setAttribute("username", "Guest");
response.getWriter().println("New session created. Username set to Guest.");
} else {
// Retrieve an attribute from the session
String username = (String) session.getAttribute("username");
response.getWriter().println("Welcome back, " + username + "!");
}

// Other processing...
}
}

Session Management Solutions


To overcome the limitations of statelessness, various session tracking methods can be
implemented:

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

Hidden Form Fields


● These fields are included in forms but are not visible to users. They retain session data
across form submissions.
● Advantages: Easy to implement and supports anonymous sessions.
● Disadvantages: Session data can only persist through dynamically generated forms and
not through static documents or after browser shutdown.

out.println("<FORM ACTION=\"/servlet/ShoppingCart\" METHOD=\"POST\">");
if (items != null) {
for (String item : items) {
out.println("<INPUT TYPE=HIDDEN NAME=\"item\" VALUE=\"" + item +
"\">");
}
}
out.println("<INPUT TYPE=SUBMIT VALUE=\"Add More Items\">");
out.println("<INPUT TYPE=SUBMIT VALUE=\"Check Out\">");
out.println("</FORM>");

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);

Cookie Operations in Java Servlets


1. Setting Cookie Attributes
You can set attributes for cookies such as the comment, maximum age, and more. Here’s how
you can create a cookie and set its comment:

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
String[] values = request.getParameterValues("bookId");
if (values != null) {
String bookId = values[0];
Cookie bookCookie = new Cookie("Buy", bookId);
bookCookie.setComment("User wants to buy this book from the bookstore.");
response.addCookie(bookCookie); // Send the cookie to the client
}
}

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:

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
String bookId = request.getParameter("Remove");
if (bookId != null) {
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if (cookie.getName().equals("Buy") && cookie.getValue().equals(bookId)) {
cookie.setMaxAge(0); // Delete the cookie
response.addCookie(cookie); // Send the updated cookie to the client
}
}
}
}
Advanced Java Programming

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:

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
String name = cookie.getName();
String value = cookie.getValue();
out.println(name + " = " + value + "<br>");
}
}
}

Example Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CookieExample extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// 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>");
}
}

// Set a new cookie


String name = request.getParameter("cookieName");
if (name != null && name.length() > 0) {
String value = request.getParameter("cookieValue");
Cookie newCookie = new Cookie(name, value);
response.addCookie(newCookie);
out.println("<h2>New cookie set:</h2>" + 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>");
}
}

Session Management with HttpSession in Java Servlets


Overview of HttpSession
The HttpSession interface provides a way to maintain user-specific data across multiple requests
in a web application.
Each user has a unique HttpSession object that can store key-value pairs, making it a convenient
way to store user data temporarily.
Sessions can be tracked using cookies or URL rewriting, but typically cookies are used to store
the session identifier.

Key Steps in Session Management


Creating a Session: When a user accesses a servlet for the first time, a new HttpSession object is
created.
Sending the Session Identifier: The session identifier is sent to the client, typically stored in a
cookie.
Advanced Java Programming

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.

Important HttpSession Methods

● Creating and Retrieving a Session


○ HttpSession getSession(): Returns the current session, creating a new one if none
exists.
○ HttpSession getSession(boolean create): Returns the current session or null if
none exists and create is false.

● Managing Session Attributes


○ Object getAttribute(String name): Retrieves an attribute.
○ void setAttribute(String name, Object attribute): Stores an attribute.
○ void removeAttribute(String name): Removes an attribute.
○ Enumeration<String> getAttributeNames(): Returns the names of all attributes.

● 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.*;

public class SessionExample extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
Advanced Java Programming

PrintWriter out = response.getWriter();

// Get the HttpSession object


HttpSession session = request.getSession(true); // create if not exists

// Print session info


Date created = new Date(session.getCreationTime());
Date accessed = new Date(session.getLastAccessedTime());
out.println("<h2>Session Information</h2>");
out.println("Session ID: " + session.getId() + "<br>");
out.println("Created: " + created + "<br>");
out.println("Last Accessed: " + accessed + "<br>");

// Set session info if needed


String dataName = request.getParameter("dataName");
if (dataName != null && dataName.length() > 0) {
String dataValue = request.getParameter("dataValue");
session.setAttribute(dataName, dataValue); // store in session
}

// Print session contents


out.println("<h3>Session Attributes</h3>");
Enumeration<String> attributeNames = session.getAttributeNames();
while (attributeNames.hasMoreElements()) {
String name = attributeNames.nextElement();
String value = session.getAttribute(name).toString();
out.println(name + " = " + value + "<br>");
}

out.println("<h3>Set New Attribute</h3>");


out.println("<form method='get'>");
out.println("Attribute Name: <input type='text' name='dataName'><br>");
out.println("Attribute Value: <input type='text' name='dataValue'><br>");
out.println("<input type='submit' value='Set Attribute'>");
out.println("</form>");
}
}

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.

All the Best!


With Regards.
Darshan Sir and Team V2V

You might also like