Unit 1
Unit 1
UNIT-I
1. SERVLET OVERVIEW
A Servlet in Java is a server-side program that runs within a web server or application server to handle requests and
responses in web applications. It is a part of the Java EE (Java Enterprise Edition) platform and is used for building
dynamic web content.
Servlet is a technology which is used to create a web application, it resides at server side and generates a
dynamic web page.
Servlet is an API that provides many interfaces and classes including documentation.
Servlet is an interface that must be implemented for creating any Servlet.
Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can respond
to any requests.
Servlet is a web component that is deployed on the server to create a dynamic web page
2. WEB SERVERS
Web Server: Web server is a program which processes the network requests of the users and serves them with files
that create web pages. This exchange takes place using Hypertext Transfer Protocol (HTTP).
Basically, web servers are computers used to store HTTP files which makes a website and when a client requests a
certain website, it delivers the requested website to the client.
For example, you want to open Facebook on your laptop and enter the URL in the search bar of google. Now, the
laptop will send an HTTP request to view the facebook webpage to another computer known as the webserver. This
computer (webserver) contains all the files (usually in HTTP format) which make up the website like text, images,
gif files, etc.
After processing the request, the webserver will send the requested website-related files to your computer and then
you can reach the website. One web server can handle multiple users at any given time which is a necessity
otherwise there had to be a web server for each user and considering the current world population, is nearly close to
impossible.
A web server is never disconnected from the internet because if it was, then it won’t be able to receive any requests,
and therefore cannot process them.
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 3 of 13
2.2 Types of Web server
There are many web servers available in the market both free and paid. Some are described below,
Apache HTTP server: It is the most popular web server and about 60 percent of the world’s web server
machines run this web server. The Apache HTTP web server was developed by the Apache Software
Foundation. It is an open-source software which means that we can access and make changes to its code and
mold it according to our preference. The Apache Web Server can be installed and operated easily on almost all
operating systems like Linux, MacOS, Windows, etc.
Microsoft Internet Information Services (IIS): IIS is a high performing web server developed by Microsoft.
It is strongly united with the operating system and is therefore relatively easier to administer. It is developed by
Microsoft, it has a good customer support system which is easier to access if we encounter any issue with the
server.
Lighttpd: Lighttpd is pronounced as ‘Lightly’. It currently runs about 0.1 percent of the world’s websites.
Lighttpd has a small CPU load and is therefore comparatively easier to run. It has a low memory footprint and
hence in comparison to the other web servers, requires less memory space to run which is always an advantage.
Jigsaw Server: Jigsaw has been written in the Java language and it can run
CGI (common gateway interference) scripts as well as PHP programs.
It is not a full-fledged server and was developed as an experimental server to
demonstrate the new web protocols. It is an open-source software which means that we can access its code and
add changes to it according to our needs and then upload our own module (the changed code).
Sun Java System: The Sun Java System supports various languages, scripts, and technologies required for
Web 2.0 such as Python, PHP, etc. It is not an open-source software and therefore its code is inaccessible which
means that we cannot make changes in the code to suit our needs.
2.3 Uses of Web Server: Web servers are mostly used for
o sending and receiving mails on Internet by using SMTP (Simple Mail transfer Protocol);
o fetching requests for File Transfer Protocol (FTP) files; and
o Designing, developing, and publishing websites.
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 4 of 13
2 A static web server includes a computer and A dynamic web server also includes a computer with
the HTTP software. plenty of other software, unlike an application server
and database model.
3 It is called static; the web pages content won't It is called dynamic because the application server is used
change unless the user manually changes it, to update the web pages files at the server-side, and due
and the server will deliver web files as is to the to which, it can change on every call requested by the
web browser. web browser.
4 Static web servers take less time to load the The Dynamic web server can only produce the data when
data. it is requested from the database. Therefore, it is time
consuming and more complicated when compared to
static web servers.
3.1 Procedure:
1. Create and compile the servlet source code. Then, copy the servlet’s class file to the proper directory, and add the
servlet’s name and mappings to the proper web .xml file.
2. Start Tomcat.
3. Start a web browser and request the servlet.
3.3 Explanation:
First, note that it imports the javax.servlet package. This package contains the classes and interfaces required to build
servlets.
Next, the program defines Hello Servlet as a sub class of GenericServlet.
The GenericServlet class provides functionality that simplifies the creation of a servlet.
For example, it provides versions of init( ) and destroy( ), which may be used as is. You need supply only the service(
) method.
Inside HelloServlet, the service( ) method (which is inherited from GenericServlet) is overridden. This method
handles requests from a client.
Notice that the first argument is a Servlet Request object. This enables the servlet to read data that is provided via
the client request.
The second argument is a ServletResponse object. This enables the servlet to formulate a response for the client.
The call to setContentType( ) establishes the MIME type of the HTTP response.
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 5 of 13
In this program, the MIME type is text/html. This indicates that the browser should interpret the content as HTML
source code. Next, the getWriter( ) method obtains a Print Writer. Anything written to this stream is sent to the client
as part of the HTTP response. Then println( ) is used to write some simple HTML source code as the HTTP response.
Servlet technology is used to create a web application (resides at server side and generates a dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway
Interface) scripting language was common as a server-side programming language.
There are many interfaces and classes in the Servlet API (Application Programming Interface) such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.
4. SERVLET CHAINING
Servlet Chaining refers to the process where multiple servlets are linked together to handle a single request in a
sequential manner. Each servlet in the chain processes the request and may modify it before passing it to the next
servlet in the chain. Similarly, responses may be modified as they pass back through the chain.
A) Forward Methods: In this model when we forward a request to a group of servlets, finally we get the result of
destination servlet as a response but not the result of intermediate servlets.
Syntax: - forward(HttpServletRequest request, HttpServletResponse response):
Forwards the request to another resource.
B) Include Methods: If a single client request is passed to a servlet and that servlet makes use of other group of
servlets to process a request by including the group of servlets into a single servlet.
Syntax: - include(HttpServletRequest request, HttpServletResponse response):
Includes the output of another resource in the response.
In the above diagram client request goes to servlet s1 and s1 internally includes s2, s3 and s4 servlets and finally result
of all these servlets given to the client by a source servlet s1.
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 6 of 13
5. SERVER-SIDE INCLUDES
Server Side Includes (SSI) is a simple interpreted server-side scripting language used almost exclusively for
the World Wide Web. It is most useful for including the contents of one or more files into a web page on a web
server using its #include directive.
Server Side Includes (SSI) in the context of Java often refer to a feature that allows dynamic inclusion of content on a
web page at the server side. SSI is commonly used in Java-based web applications built using Servlets and JSP
(JavaServer Pages). This mechanism enables a JSP or servlet to include another file (JSP, HTML, or other resources)
dynamically during the server-side request processing.
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 7 of 13
<jsp:include page="header.jsp" />
</body>
</html>
Explanation
Dynamic Behavior: The <jsp:include> tag ensures that header.jsp, main.jsp, and footer.jsp are included
dynamically during the request.
Modularity: Each section of the page (header, main content, footer) is in its own file, making the design more
modular and maintainable.
Explanation
Static Behavior: The @include directive merges the content of header.jsp and footer.jsp into index.jsp at
translation time (when the JSP is compiled into a servlet).
While JSP-based SSIs are useful, modern Java web applications often use frameworks like Spring MVC (Model
View Controller), which provide more advanced mechanisms for templating and inclusion.
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a separate
connection to the Web server and the server automatically does not keep any record of previous client request.
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 8 of 13
6.2 Session Tracking Techniques in Java
Still there are four ways to maintain session between web client and web server.
1. Cookies:
o Small data stored on the client-side by the browser.
o The server sends cookies to the client, which are included in subsequent requests.
How it works:
o Server creates a cookie and sends it in the HTTP response header.
o Browser stores the cookie and sends it back with each request.
Advantages:
o Persistent across browser restarts if configured.
o Simple to implement.
Disadvantages:
o Users can disable cookies.
o Limited size (4KB).
o Security risks if sensitive data is stored.
2. URL Rewriting:
o Appends a unique session ID as a query parameter in the URL.
o The server uses this ID to identify and associate requests with the session.
How it works:
o Server generates a session ID.
o Server encodes the session ID in URLs.
o The client includes the session ID in the query string for each request.
Advantages:
o Works even if cookies are disabled.
Disadvantages:
o Session ID is visible in the URL, which is a security concern.
o Complex to manage manually for every link.
3. Hidden Form Fields:
o Embeds session information as hidden fields in HTML forms.
o When the form is submitted, the hidden field value is sent to the server.
How it works:
o Server generates session information.
o Embeds session information in hidden form fields.
o The client submits the form with the hidden fields.
Advantages:
o Simple for form-based workflows.
o Works without cookies.
Disadvantages:
o Requires forms for every interaction.
o Limited to POST requests.
o Vulnerable to tampering if not validated.
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 9 of 13
Code Example:
// Storing data in session
HttpSession session = request.getSession();
session.setAttribute("username", "JohnDoe");
// Invalidating session
session.invalidate();
Advantages:
o Easy to use.
o Can store any type of object.
o Managed on the server, reducing security risks.
Disadvantages:
o Server memory overhead with many sessions.
o Requires configuration for session timeout and management.
7. HTML FORMS
An HTML form is used to collect user input. The user input is most often sent to a server for processing.
<input type="radio"> Displays a radio button (for selecting one of many choices)
<input type="checkbox"> Displays a checkbox (for selecting zero or more of many choices)
The <form> element is a container for different types of input elements, such as: text fields, checkboxes, radio
buttons, submit buttons, etc.
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 10 of 13
EXAMPLE:
<html>
<body>
<h2>TEXT INPUT FIELDS</h2>
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="New"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="College">
</form>
</body>
</html>
Output
TEXT INPUT FIELDS
First name:
New
Last name:
College
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 11 of 13
Advantages
Enables dynamic server-side data retrieval and processing.
Leverages HTTP for seamless communication.
Disadvantages
Applets are outdated and no longer widely supported by modern browsers.
Security restrictions and compatibility issues with applets.
catch (Exception e)
{
showStatus(e.toString());
}
}
}
Serv.java
import java.io.*;
import java.util.*;
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 12 of 13
import javax.servlet.*;
import javax.servlet.http.*;
public class Serv extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException
{
Date d=new Date();
PrintWriter out=res.getWriter();
out.println(d.toString());
}
}
Output:
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 13 of 13