Module 4 Ajava (1)
Module 4 Ajava (1)
MODULE 4
SERVLETS
A Servlet is a small program that executes on the server side of a web connection.
Just as applets extend the functionality of web browsers, servlets extend the
functionality of web servers.
Servlets are designed to handle requests, process data, and generate dynamic content
for web pages.
When a user requests a static page, they enter a URL into the browser. The browser generates
an HTTP request for a specific file, which the server maps to the appropriate resource. The
server responds with an HTTP response containing the requested file. The response header
includes metadata, such as the content type (e.g., text/html), which indicates the MIME type
of the source web page.
Advantages of Servlets Over Traditional CGI
Java servlets offer several advantages over traditional Common Gateway Interface (CGI)
scripts and other CGI-like technologies. These advantages include efficiency, convenience,
power, portability, and cost-effectiveness.
1. Efficiency
Process Management: Traditional CGI scripts start a new process for each HTTP
request, which can be inefficient. The overhead of starting a new process can be
significant, especially for fast operations. In contrast, servlets run within the Java
Virtual Machine (JVM), and each request is handled by a lightweight Java thread
rather than a heavyweight operating system process.
Memory Usage: With traditional CGI, if multiple requests are made to the same CGI
program simultaneously, the code for the CGI program is loaded into memory
multiple times. Servlets, however, use multiple threads within a single JVM instance,
meaning only one copy of the servlet class is loaded into memory regardless of the
number of requests.
2. Convenience
Language Familiarity: Developers familiar with Java do not need to learn another
language, such as Perl, to write server-side programs. This reduces the learning curve
and increases productivity.
Built-in Utilities: Servlets provide extensive infrastructure for common tasks such as
parsing and decoding HTML form data, reading and setting HTTP headers, handling
cookies, and tracking sessions. These built-in utilities simplify development and
reduce the need for custom code.
3. Power
Direct Server Communication: Servlets can directly interact with the web server,
which is not possible with regular CGI programs. This direct communication
1
21CS642 Advanced Java Programming
simplifies tasks that involve looking up images or other data stored in standard
locations.
Data Sharing: Servlets can share data among each other, facilitating features like
database connection pools. This capability makes it easier to implement complex
functionalities and improve performance.
State Management: Servlets can maintain information across multiple requests,
simplifying session tracking and caching of previous computations. This state
management capability is essential for creating dynamic, user-specific content.
4. Portability
Standardized API: Servlets are written in Java and follow a well-defined,
standardized API. This ensures that servlets developed for one server (e.g., I-Planet
Enterprise Server) can run on other servers (e.g., Apache, Microsoft IIS) with minimal
changes.
Cross-Platform Support: Servlets are supported by almost every major web server,
either directly or through a plugin. This wide support enhances their portability across
different server environments.
5. Cost-Effectiveness
Inexpensive Deployment: Many web servers that support servlets are available for
free or at a low cost. This makes it economical to add servlet functionality to a web
server. While many commercial-quality web servers are expensive, adding servlet
support is usually free or inexpensive.
Low-Cost Infrastructure: The use of free or inexpensive servers is suitable for
personal use or low-volume websites. However, even for high-volume commercial
sites, the cost of adding servlet support is minimal compared to the overall cost of the
web server infrastructure.
Phases of the Servlet Life Cycle
The life cycle of a servlet is managed by the web container (e.g., Apache Tomcat) and
includes the following phases:
Loading the Servlet Class
The servlet class is loaded when the web container receives the first request for the servlet.
This loading happens only once during the servlet's life cycle.
Creating an Instance
The web container creates an instance of the servlet class. This instance creation also happens
only once, ensuring a single instance of the servlet is used to handle multiple requests.
Initialization (init)
2
21CS642 Advanced Java Programming
The web container invokes the init method to initialize the servlet. This method is called only
once when the servlet instance is first loaded.
Syntax:
public void init(ServletConfig config) throws ServletException
Request Handling (service)
Each time a request is received, the web container calls the service method of the servlet. If
the servlet has not been initialized, the container calls the init method before invoking the
service method.
Syntax:
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
Destruction (destroy)
Before the servlet instance is removed from service, the web container calls the destroy
method. This method allows the servlet to perform any cleanup, such as releasing resources
or closing connections.
Syntax:
public void destroy()
Example of a Servlet
Below is an example of a simple servlet that handles HTTP GET requests and responds with
a "Hello, World!" message.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// Initialization method
@Override
public void init() throws ServletException {
// Initialization code here
System.out.println("Servlet is being initialized");
3
21CS642 Advanced Java Programming
// Destruction method
@Override
public void destroy() {
// Cleanup code here
System.out.println("Servlet is being destroyed");
}
}
Explanation
Loading the Servlet Class: When the servlet is first requested, the web container
loads the HelloWorldServlet class.
Creating an Instance: The web container creates an instance of HelloWorldServlet.
Initialization: The init method is called, which can be used to perform initialization
tasks.
Request Handling: The doGet method handles HTTP GET requests. It sets the
response content type to text/html and writes a simple "Hello, World!" message to the
response.
Destruction: When the servlet is about to be unloaded, the destroy method is called,
allowing for any necessary cleanup.
4
21CS642 Advanced Java Programming
Deployment Descriptor
A Deployment Descriptor (DD) is an XML file named web.xml located in the WEB-INF
directory of a Java web application. This file configures the web application and controls the
behavior of Java Servlets and JavaServer Pages (JSP). It defines mappings between URLs
and the corresponding servlets that should handle requests to those URLs. It also specifies
initialization parameters, servlet filters, listener classes, and other configurations.
Structure of web.xml
The web.xml file includes several important components:
1. Header: This includes the XML version and encoding.
2. DOCTYPE: Specifies the Document Type Definition (DTD) for the XML file.
3. <web-app> element: This is the root element of the deployment descriptor and
contains other configuration elements.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/dtd/web-app_2_2.dtd">
<web-app>
<servlet>
<servlet-name>MyJavaServlet</servlet-name>
<servlet-class>myPackage.MyJavaServletClass</servlet-class>
<init-param>
<param-name>parameter1</param-name>
<param-value>735</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyJavaServlet</servlet-name>
<url-pattern>/myServlet</url-pattern>
</servlet-mapping>
</web-app>
5
21CS642 Advanced Java Programming
Components of web.xml
1. Header:
<?xml version="1.0" encoding="ISO-8859-1"?>
This line declares the XML version and the character encoding used in the file.
2. DOCTYPE:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/dtd/web-app_2_2.dtd">
This line defines the DTD, ensuring the XML file follows the structure specified by the DTD
for web applications.
3. <web-app> Element:
<web-app>
...
</web-app>
The root element that contains all the configuration details of the web application.
4. <servlet> Element:
<servlet>
<servlet-name>MyJavaServlet</servlet-name>
<servlet-class>myPackage.MyJavaServletClass</servlet-class>
<init-param>
<param-name>parameter1</param-name>
<param-value>735</param-value>
</init-param>
</servlet>
o <servlet-name>: Specifies a name for the servlet. This name is used in the
<servlet-mapping> element to map the servlet to a URL pattern.
o <servlet-class>: Specifies the fully qualified class name of the servlet.
o <init-param>: Specifies initialization parameters for the servlet. Each <init-
param> contains a <param-name> and a <param-value>.
5. <servlet-mapping> Element:
<servlet-mapping>
<servlet-name>MyJavaServlet</servlet-name>
<url-pattern>/myServlet</url-pattern>
6
21CS642 Advanced Java Programming
</servlet-mapping>
o <servlet-name>: Matches the name specified in the <servlet> element.
o <url-pattern>: Defines the URL pattern that will be mapped to the servlet.
When a request matches this URL pattern, the specified servlet will handle the
request.
Additional Configuration Options
The web.xml file can also include other configurations such as:
Servlet Filters: To intercept requests and responses and perform filtering tasks.
Listener Classes: To handle events in the web application lifecycle.
Error Pages: To define custom error pages for different HTTP error codes.
Security Constraints: To define security constraints for the web application.
Reading Data from Client in a Servlet
To read data sent from a client to a servlet, you need to handle HTTP requests, either using
the GET or POST method. The data sent by the client can be accessed using the
getParameter() or getParameterValues() methods of the HttpServletRequest object. Here's a
detailed explanation and example:
Methods to Handle Client Data
1. doGet() Method:
o Used when the client sends data via the HTTP GET method.
o Typically handles query parameters appended to the URL.
2. doPost() Method:
o Used when the client sends data via the HTTP POST method.
o Handles form data sent in the body of the HTTP request.
Retrieving Parameters
getParameter(String name):
o Retrieves the value of a single parameter as a String.
o Returns null if the parameter does not exist.
o Returns an empty string if the parameter exists but has no value.
getParameterValues(String name):
o Retrieves the values of a parameter that has multiple values as a String array.
o Useful for handling multi-select form elements or checkboxes.
7
21CS642 Advanced Java Programming
8
21CS642 Advanced Java Programming
9
21CS642 Advanced Java Programming
10
21CS642 Advanced Java Programming
<body>
<form action="/myHeaderServlet" method="get">
<label for="email">Enter Email Address:</label>
<input type="text" id="email" name="email">
<input type="submit" value="Submit">
</form>
</body>
</html>
Servlet Code to Handle HTTP Headers:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
11
21CS642 Advanced Java Programming
12
21CS642 Advanced Java Programming
13
21CS642 Advanced Java Programming
out.println("</body>");
out.println("</html>");
14
21CS642 Advanced Java Programming
15
21CS642 Advanced Java Programming
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Create a cookie
Cookie myCookie = new Cookie("userId", "123");
16
21CS642 Advanced Java Programming
17
21CS642 Advanced Java Programming
if (cookies != null) {
for (Cookie cookie : cookies) {
out.println("Name: " + cookie.getName() + ", ");
out.println("Value: " + cookie.getValue() + "<br/>");
}
} else {
out.println("<h2>No cookies found</h2>");
}
out.println("</body></html>");
}
}
JavaServer Pages (JSP)
JavaServer Pages (JSP) is a technology for developing web pages that support dynamic
content. It provides a simplified way to create and manage content using HTML and Java
combined. JSP is designed to provide a high-level abstraction over Java servlets.
Key Characteristics of JSP
Server-Side Processing: JSP runs on the server, generating dynamic content before
sending it to the client.
Ease of Use: JSP is easier to write and manage than Java servlets because it embeds
Java code directly within HTML.
Lifecycle Methods in JSP
There are three key lifecycle methods in JSP:
1. jspInit():
o Called once when the JSP is first loaded.
o Similar to the init() method in servlets.
o Used for initialization tasks.
public void jspInit() {
18
21CS642 Advanced Java Programming
19
21CS642 Advanced Java Programming
20
21CS642 Advanced Java Programming
o Common Directives:
Page Directive: Used to import Java classes, set page encoding, etc.
<%@ page import="java.util.Date" %>
Include Directive: Includes content from another file.
<%@ include file="header.html" %>
Taglib Directive: Declares a tag library that can be used in the JSP
page.
<%@ taglib uri="myTags.tld" prefix="mytag" %>
4. Expression Tags
o Syntax: <%= expression %>
o Purpose: Evaluates the expression and converts the result to a string, which is
then included in the output.
o Example:
<%= new java.util.Date() %>
5. Scriptlet Tags
o Syntax: <% code %>
o Purpose: Contains Java code that is executed during the request processing.
o Example:
<%
int number = 10;
if (number > 5) {
out.println("Number is greater than 5");
}
%>
Example JSP Page
Below is an example JSP page that demonstrates the use of various JSP tags:
<%@ page import="java.util.Date" %>
<html>
<head>
<title>JSP Example</title>
</head>
21
21CS642 Advanced Java Programming
<body>
<%-- This is a comment --%>
<%! int age = 25; %>
<p>Your age is: <%= age %></p>
<p>Current date and time: <%= new Date() %></p>
<%
for (int i = 0; i < 5; i++) {
out.println("Count: " + i + "<br>");
}
%>
</body>
</html>
Variables and Objects in JSP
In a JSP page, you can declare variables and objects using declaration tags. These variables
and objects are available throughout the JSP page. Here's how you can declare and use them:
Declaration Example
<%@ page import="java.util.Date" %>
<html>
<head>
<title>JSP Programming</title>
</head>
<body>
<%! int age = 29; %>
<%! Date currentDate = new Date(); %>
<p>Your age is: <%= age %></p>
<p>Current date and time: <%= currentDate %></p>
</body>
</html>
Explanation
Declaration Tag (<%! ... %>): Used to declare the variable age and the object
currentDate.
22
21CS642 Advanced Java Programming
Expression Tag (<%= ... %>): Used to output the values of age and currentDate
directly into the HTML content.
Declaring and Using Methods in JSP
In JSP, methods can be declared in the same way they are in regular Java programs, but they
need to be placed within JSP declaration tags (<%! ... %>). These methods can then be called
within the JSP using expression tags (<%= ... %>).
Here is an example to illustrate how methods are declared and used in JSP:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Programming</title>
</head>
<body>
<%!
// Method to add two numbers
int add(int n1, int n2) {
int c;
c = n1 + n2;
return c;
}
%>
<p>Addition of two numbers: <%= add(45, 46) %></p>
</body>
</html>
Explanation:
1. Page Directive (<%@ ... %>): Specifies the language as Java and sets the content
type and page encoding.
23
21CS642 Advanced Java Programming
24
21CS642 Advanced Java Programming
<!DOCTYPE html>
<html>
<head>
<title>JSP Programming</title>
</head>
<body>
<%! int grade = 26; %> <!-- Declaring a variable in JSP -->
25
21CS642 Advanced Java Programming
The switch statement allows the execution of one block of code among many based on the
value of a variable or expression.
Example Using switch Statement
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Programming</title>
</head>
<body>
<%! int grade = 85; %> <!-- Declaring a variable in JSP -->
<%
String result;
switch (grade / 10) {
case 10:
case 9:
result = "A";
break;
case 8:
result = "B";
break;
case 7:
result = "C";
break;
case 6:
result = "D";
break;
default:
result = "F";
26
21CS642 Advanced Java Programming
break;
}
%>
27
21CS642 Advanced Java Programming
break;
default:
result = "F";
break;
}
%>
4. Expression Tag: Outputs the letter grade to the HTML content.
<p>Your grade is: <%= result %></p>
Looping Statements in JSP
Loops in JSP are almost identical to loops in Java programming, with the added capability of
repeating HTML tags within the loop. The three common types of loops used in JSP are:
1. For Loop
2. While Loop
3. Do-While Loop
These loops are essential, especially in JSP database programs where repetitive tasks such as
displaying rows from a database are required.
Example Using for Loop
The following example demonstrates a simple for loop in JSP that outputs "Hello World" ten
times:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
<title>For Loop Example</title>
</head>
<body>
<%
for (int i = 0; i < 10; i++) {
%>
<p>Hello World</p>
<%
28
21CS642 Advanced Java Programming
}
%>
</body>
</html>
Explain Requset String generated by browser. how to read a request string in jsp?
1. A browser generate requst string whenever the submit button is selected. The user requests
the string consists of URL and the query the string. Example of request string:
http://www.jimkeogh.com/jsp/?fname=” Bob” & lname =”Smith”
2. Your jsp programneeds to parse the query string to extract the values of fields that are to be
processed by your program. You can parse the query string by using the methods of the
request object.
3. getParameter(Name) method used to parse a value of a specific field that are to be
processed by your program
4. code to process the requset string
5. Copying from multivalued field such as selection list field can be tricky multivalued fields
are handled by using getParameterValues()
6. Other than requset string url has protocols, port no, the host name
1. Request Parameters (Query String)
When a form is submitted, the browser sends a request to the server with parameters encoded
in the URL (query string) or sometimes in the request body. Here's an example of a request
string:
http://www.example.com/servlet?fname=Bob&lname=Smith
To retrieve these parameters in a JSP, you use the request.getParameter("parameterName")
method.
2. Parsing Request Parameters in JSP
To parse and use the parameters sent in the request, you typically do something like this in
your JSP:
<%@ page language="java" %>
<%
String firstName = request.getParameter("fname");
String lastName = request.getParameter("lname");
%>
Here, fname and lname are the names of the parameters as specified in the query string.
3. Handling Multivalued Parameters
29
21CS642 Advanced Java Programming
If a parameter can have multiple values (like checkboxes or multi-select dropdowns), you use
request.getParameterValues("parameterName"):
String[] selectedValues = request.getParameterValues("fieldName");
4. Cookies in JSP
Cookies are small pieces of data stored on the client-side by the browser. In JSP, you can
create and read cookies using the Cookie class and methods provided by the
HttpServletRequest object.
Creating a Cookie:
<%@ page language="java" %>
<%
String cookieName = "EMPID";
String cookieValue = "AN2536";
30
21CS642 Advanced Java Programming
%>
In this example, request.getCookies() returns an array of Cookie objects sent by the client.
You iterate through these cookies to find the one with the name "EMPID".
Step-by-Step Guide to Configure Tomcat
1. Download Tomcat
Visit the Apache Tomcat website (jakarta.apache.org or tomcat.apache.org).
Navigate to the download section and select the latest stable release.
Choose the "Binaries" distribution, which includes the executable files you need.
2. Install Tomcat
Create a folder for Tomcat. For example, C:\tomcat (on Windows) or /opt/tomcat (on
Unix-like systems).
Download the zip file for Tomcat and unzip it into your chosen folder (C:\tomcat or
/opt/tomcat).
3. Configure Environment Variables (Windows)
Set JAVA_HOME environment variable:
o Right-click on "My Computer" or "This PC" and select "Properties".
o Go to "Advanced system settings" -> "Environment Variables".
o Under "System Variables", click "New" and add JAVA_HOME with the path
to your JDK installation (e.g., C:\Program Files\Java\jdk1.8.0_291).
4. Configure Environment Variables (Unix-like systems)
Edit your shell profile file (e.g., .bash_profile, .bashrc, .profile):
export JAVA_HOME=/path/to/your/jdk
export PATH=$PATH:$JAVA_HOME/bin
Source the profile file to apply changes: source ~/.bash_profile or source ~/.bashrc.
5. Modify Tomcat Startup Script
Navigate to C:\tomcat\bin or /opt/tomcat/bin.
Edit the startup script (startup.bat for Windows, startup.sh for Unix-like systems).
Set the JAVA_HOME variable to your JDK installation path:
set JAVA_HOME=C:\path\to\your\jdk (for Windows)
JAVA_HOME=/path/to/your/jdk (for Unix-like systems)
6. Start Tomcat
Open a command prompt (Windows) or terminal (Unix-like systems).
31
21CS642 Advanced Java Programming
32
21CS642 Advanced Java Programming
Explanation:
o request.getSession(): Retrieves the current session associated with the request,
creating a new one if necessary.
o session.setAttribute(attributeName, attributeValue): Sets an attribute (Product
with value 1234) in the session object.
2. Reading Session Attributes
To read session attributes in subsequent requests or pages within the same session, you can
use methods like session.getAttributeNames() and session.getAttribute(attributeName):
<html>
<head>
<title>JSP Session</title>
</head>
<body>
<%
// Get all attribute names in the session
Enumeration<String> attributeNames = session.getAttributeNames();
while (attributeNames.hasMoreElements()) {
String attributeName = attributeNames.nextElement();
String attributeValue = (String) session.getAttribute(attributeName);
%>
<p>Attribute Name: <%= attributeName %></p>
<p>Attribute Value: <%= attributeValue %></p>
<%
}
%>
</body>
</html>
Explanation:
o session.getAttributeNames(): Returns an Enumeration of all attribute names
stored in the session.
33
21CS642 Advanced Java Programming
34