0% found this document useful (0 votes)
8 views13 pages

Unit 1

The document provides study material for Advanced Java Programming, focusing on servlets and web servers. It covers the basics of servlet technology, including its lifecycle, key features, and examples, as well as types of web servers and their uses. Additionally, it discusses servlet chaining, server-side includes, and dynamic content generation in Java web applications.

Uploaded by

rjfdfn8rjd
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)
8 views13 pages

Unit 1

The document provides study material for Advanced Java Programming, focusing on servlets and web servers. It covers the basics of servlet technology, including its lifecycle, key features, and examples, as well as types of web servers and their uses. Additionally, it discusses servlet chaining, server-side includes, and dynamic content generation in Java web applications.

Uploaded by

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

THE NEW COLLEGE (AUTONOMOUS), CHENNAI-14.

Department of Computer Applications – Shift - II


STUDY MATERIAL
Subject: Advanced Java Programming (20BHM407) Class: II BCA
----------------------------------------------------------------------------------------------------------------------------------
INTRODUCTION
In June 1991, a team of engineers at Sun Microsystems, led by James Gosling, began the "Green" project to
develop a programming language for consumer electronics. The project was originally called "Oak", but was
renamed "Java" after the coffee the team enjoyed.
 Java is divided into two parts i.e. Core Java (J2SE) and Advanced Java (J2EE).
 The core Java covers the fundamentals of the Java programming language, i.e. Data types, Functions,
Operators, Loops, Threads, Exception handling, etc.
 It is used to develop General Purpose Applications.
 Whereas Advanced Java covers the standard concepts such as Database Connectivity, JDBC Networking,
Servlet, Web-Services, etc.

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

1.1 Key Features of Servlets


1. Platform-Independent: Written in Java, Servlets are portable across different operating systems and servers.
2. Robust and Scalable: Designed for handling multiple requests in a multi-threaded environment.
3. Lifecycle Management: Managed by the web container, which handles initialization, execution, and
destruction of servlets.
1.2 Servlet Works
Servlets follow the request-response model to process HTTP requests and generate dynamic responses. Here's the
flow:
1. Client Request: A client (typically a web browser) sends a request to the server.
2. Servlet Processing:
o The web server forwards the request to the servlet.
o The servlet processes the request (e.g., fetching data from a database, processing input).
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 1 of 13
3. Response Generation: The servlet generates a response, usually in the form of HTML or JSON, and sends it
back to the client.

1.3 Servlet Lifecycle


The lifecycle of a servlet is managed by the Servlet Container, such as Apache Tomcat. The stages are:
1. Loading and Initialization:
o The container loads the servlet class.
o Calls the init() method for initialization.
Syntax:- public void init(ServletConfig config) throws ServletException
2. Request Handling:
o The service() method is called to handle client requests.
o Based on the type of HTTP request (GET, POST, etc.), the servlet may invoke specific methods like
doGet() or doPost().
Syntax: - public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
3. Destruction:
o The destroy() method is called when the servlet is no longer needed, allowing for cleanup.
Syntax:- public void destroy()

1.4 Example of a Simple Servlet


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

// Extend HttpServlet to create a servlet


public class HelloWorldServlet extends HttpServlet {
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 2 of 13
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
// Set the content type of the response
response.setContentType("text/html");

// Write the response


PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body></html>");
}
}
Output:
Hello, world!

1.5 Key Interfaces and Classes in Servlet API


1. Interfaces:
o Servlet: The basic interface every servlet must implement.
o ServletRequest and ServletResponse: Represent client requests and responses.
o HttpServletRequest and HttpServletResponse: Subinterfaces for handling HTTP-specific details.
2. Classes:
o GenericServlet: A protocol-independent, generic servlet.
o HttpServlet: An abstract class for creating HTTP-specific servlets.

1.6 Advantages of Servlets


 Efficient: Use multithreading to handle multiple requests.
 Secure: Benefit from Java's built-in security features.
 Extensible: Can be integrated with frameworks like Spring and Struts.
 Dynamic Content: Suitable for generating dynamic web pages.

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.

2.4 Static Web Servers vs. Dynamic Web Servers


A web server can be used to store, process or deliver either static or dynamic web pages. Let's understands the
definition of static and dynamic web servers with the help of their difference table given below:

S.No Static Web Servers Dynamic Web Servers


1 Static web servers refer to the servers, which Dynamic web servers refer to the servers where the
serve only the static content i.e., the content is content of the page can be updated and altered.
fixed and being shown as it is.

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. YOUR FIRST SERVLET PROGRAM


To become familiar with the key servlet concepts, we will begin by building and testing a simple servlet. 3.1

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.2 Source Code - Create and Compile the Servlet


To begin, create a file named HelloServlet.java that contains the following program:
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
response.setContentType ("text/html");
PrintWriter pw = response.getWriter ();
pw.println("<B>Hello! 2BCA Guys");
pw.close();
}
}
Output: Hello! 2BCA Guys

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.

Figure 4: Process of Servlet Chaining

4.1 Methods / Techniques / Models of Servlet Chaining


In order to process a client request by many number of servlets then we have two models, they are forward model and
include model Using RequestDispatcher. The RequestDispatcher interface is used to forward requests or include the
output of another servlet.

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.

5.1 Key Features of Server Side Includes


1. Dynamic Inclusion: SSI allows content to be dynamically included, making it easier to reuse and maintain.
2. Performance: Content is included at the server side before sending the response to the client, optimizing
delivery.
3. Separation of Concerns: SSI encourages modular design by breaking large files into smaller, reusable
components.

5.2 Including Files in Java Web Applications


Java provides two primary ways to include content dynamically in a JSP:
1. <jsp:include> Tag (Dynamic inclusion):
Includes a resource dynamically at request time. Any changes to the included file are reflected without
redeployment.
2. @include Directive (Static inclusion):
Includes the content at translation time, effectively merging the content into the JSP.

Example: Using <jsp:include> in JSP


Here is an example where a header, footer, and main content are included dynamically:
File: header.jsp
<header>
<h1>Welcome to My Website</h1>
</header>
File: footer.jsp
<footer>
<p>© 2024 My Website. All rights reserved.</p>
</footer>
File: main.jsp
<main>
<p>This is the main content of the page.</p>
</main>
File: index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<jsp:include page="main.jsp" />
<jsp:include page="footer.jsp" />

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.

Example: Using @include Directive


File: index.jsp
<%@ include file="header.jsp" %>
<main>
<p>This is the main content of the page.</p>
</main>
<%@ include file="footer.jsp" %>

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

5.3 Key Differences Between <jsp:include> and @include


Feature <jsp:include> @include
Inclusion Time Request time (dynamic) Translation time (static)
Reflection of Changes Immediate Requires recompilation/deployment
Use Case Dynamic or frequently changing content Static or rarely changing content

5.4 Use Cases


1. Reusing Headers and Footers: Include common page elements like navigation bars, headers, and footers.
2. Localization: Dynamically load language-specific content.
3. Modularity: Break down large JSP files into smaller, manageable components.

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.

6. SESSION TRACKING MANAGEMENT


Session means a particular interval of time. Session tracking is a way to maintain state (Data) of a user. It is also
known as session management in Servlet.

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.

6.1 Why is Session Tracking Needed?


1. Statelessness of HTTP: HTTP does not retain user data between requests.
2. User Identification: To identify users and their interactions across multiple requests.
3. Personalized Experience: To maintain user-specific data (like authentication, preferences, or session-specific
information).

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.

4. HttpSession (Preferred Method):


o Java's built-in session management provided by the HttpSession interface.
o Maintains session information on the server-side, identified by a unique session ID.
How it works:
o A session object is created for each user when they interact with the server.
o The session object can store user-specific data like attributes and preferences.

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

// Retrieving data from session


HttpSession session = request.getSession(false);
if (session != null) {
String username = (String) session.getAttribute("username");
}

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

The <form> Element


The HTML <form> element is used to create an HTML form for user input:
<form>
form elements
</form>
The <input> Element
The HTML <input> element is the most used form element.
An <input> element can be displayed in many ways, depending on the type attribute.

Here are some examples:


Type Description

<input type="text"> Displays a single-line text input field

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

<input type="submit"> Displays a submit button (for submitting the form)

<input type="button"> Displays a clickable button

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

8. APPLET TO SERVLET COMMUNICATION


Applet to Servlet Communication in Java refers to the process where a Java applet (running on a client-side
browser) interacts with a servlet (running on a server) to send or receive data.

8.1 Steps for Applet to Servlet Communication


1. Applet Sends a Request:
o The applet uses HTTP to send data to the servlet, typically using the URLConnection or
HttpURLConnection class.
2. Servlet Processes the Request:
o The servlet processes the received data and generates a response (e.g., HTML, JSON, or plain text).
3. Applet Receives the Response:
o The applet reads the response from the servlet and performs client-side operations based on the data.

8.2 Key Components


1. Applet: The client-side program embedded in an HTML page and executed in a browser or applet viewer.
2. Servlet: The server-side component that handles HTTP requests and responses.

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.

Example: Program for Applet to Servlet Communication


Apps.java import java.awt.*;
import java.net.*;
import java.io.*;
import java.awt.event.*;
import java.applet.*;
import java.lang.*;
/*<applet code="Apps" width=400 height=460> </applet>*/
public class Apps extends Applet implements ActionListener
{
Button b;
TextField tf;
public void init()
{
b=new Button("call Servlet");
b.addActionListener(this);
add(b);tf=new TextField(25);
add(tf);
}
public void actionPerformed(ActionEvent ae)
{
try
{
URL u=new URL("http://localhost:8080/WebApplication11/Serv");
URLConnection urlc=u.openConnection();
InputStream isr=urlc.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(isr));
tf.setText(br.readLine());
}

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:

DIFFERENCE BETWEEN APPLET AND SERVLET


APPLET SERVLET
Used to develop client side web-resource Used to develop server side web-resource program to
program to generate static web page. generate dynamic web-page.
Needs browser window or applet viewer for Needs servlet container for execution.
execution.
Applet program comes to browser window from Servlet program reside and execute in web resource.
server for execution.
The life cycle methods are The life cycle methods are
init(), start(), stop() and destroy(). init(-), service(-,-) and destroy().

~~~~- End of Unit - I~~~~-

The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 13 of 13

You might also like