UNIT 2
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
o Servlet is a technology which is used to create a web application.
o Servlet is an API that provides many interfaces and classes including documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic web
page.
What is a web application?
A web application is an application accessible from the web. A web application is composed
of web components like Servlet, JSP, Filter, etc. and other elements such as HTML, CSS, and
JavaScript. The web components typically execute in Web Server and respond to the HTTP
request.
CGI (Common Gateway Interface)
CGI technology enables the web server to call an external program and pass HTTP request
information to the external program to process the request. For each request, it starts a new
process.
CGI (Common Gateway Interface)
CGI technology enables the web server to call an external program and pass HTTP request
information to the external program to process the request. For each request, it starts a new
process.
Disadvantages of CGI
There are many problems in CGI technology:
1. If the number of clients increases, it takes more time for sending the response.
2. For each request, it starts a process, and the web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.
Advantages of Servlet
The advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection, etc.
4. Secure: because it uses java language.
Web Terminology:
Servlet Description
Terminology
Website: static vs It is a collection of related web pages that may contain text, images,
dynamic audio and video.
HTTP It is the data communication protocol used to establish communication
between client and server.
HTTP Requests It is the request send by the computer to a web server that contains all
sorts of potentially interesting information.
Get vs Post It gives the difference between GET and POST request.
Container It is used in java for dynamically generating the web pages on the
server side.
Server: Web vs It is used to manage the network resources and for running the program
Application or software that provides services.
Content Type It is HTTP header that provides the description about what are you
sending to the browser.
Website
Website is a collection of related web pages that may contain text, images, audio and video.
The first page of a website is called home page. Each website has specific internet address
(URL) that you need to enter in your browser to access a website.
Website is hosted on one or more servers and can be accessed by visiting its homepage using
a computer network. A website is managed by its owner that can be an individual, company
or an organization.
A website can be of two types:
o Static Website
o Dynamic Website
Static website
Static website is the basic type of website that is easy to create. You don't need the
knowledge of web programming and database design to create a static website. Its web pages
are coded in HTML.
Dynamic website
Dynamic website is a collection of dynamic web pages whose content changes dynamically.
It accesses content from a database or Content Management System (CMS). Therefore, when
you alter or update the content of the database, the content of the website is also altered or
updated.
Dynamic website uses client-side scripting or server-side scripting, or both to generate
dynamic content.
Client side scripting generates content at the client computer on the basis of user input. The
web browser downloads the web page from the server and processes the code within the page
to render information to the user.
In server side scripting, the software runs on the server and processing is completed in the
server then plain pages are sent to the user.
Static vs Dynamic website
Static Website Dynamic Website
Prebuilt content is same every time the page is Content is generated quickly and changes
loaded. regularly.
It uses the HTML code for developing a website. It uses the server side languages such
as PHP,SERVLET, JSP, and ASP.NET etc. for
developing a website.
It sends exactly the same response for every It may generate different HTML for each of the
request. request.
The content is only changed when someone The page contains "server-side" code which
publishes and updates the file (sends it to the web allows the server to generate the unique content
server). when the page is loaded.
Flexibility is the main advantage of static website. Content Management System (CMS) is the main
advantage of dynamic website.
HTTP (Hyper Text Transfer Protocol)
The Hypertext Transfer Protocol (HTTP) is application-level protocol for collaborative,
distributed, hypermedia information systems. It is the data communication protocol used to
establish communication between client and server.
HTTP is TCP/IP based communication protocol, which is used to deliver the data like image
files, query results, HTML files etc on the World Wide Web (WWW) with the default port is
TCP 80. It provides the standardized way for computers to communicate with each other.
Characteristics of HTTP (Hyper Text Transfer Protocol):
o It is the protocol that allows web servers and browsers to exchange data over the web.
o It is a request response protocol.
o It uses the reliable TCP connections by default on TCP port 80.
o It is stateless means each request is considered as the new request. In other words,
server doesn't recognize the user by default.
Features of HTTP (Hyper Text Transfer Protocol):
There are three fundamental features that make the HTTP a simple and powerful protocol
used for communication:
o HTTP is media independent: It specifies that any type of media content can be sent
by HTTP as long as both the server and the client can handle the data content.
o HTTP is connectionless: It is a connectionless approach in which HTTP client i.e., a
browser initiates the HTTP request and after the request is sent the client disconnects
from server and waits for the response.
o HTTP is stateless: The client and server are aware of each other during a current
request only. Afterwards, both of them forget each other. Due to the stateless nature
of protocol, neither the client nor the server can retain the information about different
request across the web pages.
Architecture of HTTP (Hyper Text Transfer Protocol):
The below diagram represents the basic architecture of web application and depicts where
HTTP stands:
HTTP Requests
The request sent by the computer to a web server, contains all sorts of potentially interesting
information; it is known as HTTP requests.
The HTTP client sends the request to the server in the form of request message which
includes following information:
o The Request-line
o The analysis of source IP address, proxy and port
o The analysis of destination IP address, protocol, port and host
o The Requested URI (Uniform Resource Identifier)
o The Request method and Content
o The User-Agent header
o The Connection control header
o The Cache control header
The HTTP request method indicates the method to be performed on the resource identified by
the Requested URI (Uniform Resource Identifier). This method is case-sensitive and
should be used in uppercase.
HTTP Request Description
GET Asks to get the resource at the requested URL.
POST Asks the server to accept the body info attached. It is like GET request with
extra info sent with the request.
HEAD Asks for only the header part of whatever a GET would return. Just like GET
but with no body.
TRACE Asks for the loopback of the request message, for testing or troubleshooting.
PUT Says to put the enclosed info (the body) at the requested URL.
DELETE Says to delete the resource at the requested URL.
OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can
respond
Get vs. Post
There are many differences between the Get and Post request. Let's see these differences:
GET POST
1) In case of Get request, only limited amount In case of post request, large amount of data can
of data can be sent because data is sent in be sent because data is sent in body.
header.
2) Get request is not secured because data is Post request is secured because data is not exposed
exposed in URL bar. in URL bar.
3) Get request can be bookmarked. Post request cannot be bookmarked.
4) Get request is idempotent . It means second Post request is non-idempotent.
request will be ignored until response of first
request is delivered
5) Get request is more efficient and used more Post request is less efficient and used less than get.
than Post.
GET and POST
Two common methods for the request-response between a server and client are:
o GET- It requests the data from a specified resource
o POST- It submits the processed data to a specified resource
Anatomy of Get Request
The query string (name/value pairs) is sent inside the URL of a GET request:
1. GET/RegisterDao.jsp?name1=value1&name2=value2
Some other features of GET requests are:
o It remains in the browser history
o It can be bookmarked
o It can be cached
o It have length restrictions
o It should never be used when dealing with sensitive data
o It should only be used for retrieving the data
Anatomy of Post Request
The query string (name/value pairs) is sent in HTTP message body for a POST request:
1. POST/RegisterDao.jsp HTTP/1.1
2. Host: www. javatpoint.com
3. name1=value1&name2=value2
Some other features of POST requests are:
o This requests cannot be bookmarked
o This requests have no restrictions on length of data
o This requests are never cached
o This requests do not retain in the browser history
Servlet Container
It provides the runtime environment for JavaEE (j2ee) applications. The client/user can
request only a static WebPages from the server. If the user wants to read the web pages as per
input then the servlet container is used in java.
The servlet container is the part of web server which can be run in a separate process. We can
classify the servlet container states in three types:
Servlet Container States
The servlet container is the part of web server which can be run in a separate process. We can
classify the servlet container states in three types:
o Standalone: It is typical Java-based servers in which the servlet container and the
web servers are the integral part of a single program. For example:- Tomcat running
by itself
o In-process: It is separated from the web server, because a different program runs
within the address space of the main server as a plug-in. For example:- Tomcat
running inside the JBoss.
o Out-of-process: The web server and servlet container are different programs which
are run in a different process. For performing the communications between them, web
server uses the plug-in provided by the servlet container.
The Servlet Container performs many operations that are given below:
o Life Cycle Management
o Multithreaded support
o Object Pooling
o Security etc.
Server: Web vs. Application
Server is a device or a computer program that accepts and responds to the request made by
other program, known as client. It is used to manage the network resources and for running
the program or software that provides services.
There are two types of servers:
1. Web Server
2. Application Server
Web Server
Web server contains only web or servlet container. It can be used for servlet, jsp, struts, jsf
etc. It can't be used for EJB.
It is a computer where the web content can be stored. In general web server can be used to
host the web sites but there also used some other web servers also such as FTP, email,
storage, gaming etc.
Examples of Web Servers are: Apache Tomcat and Resin.
Web Server Working
It can respond to the client request in either of the following two possible ways:
o Generating response by using the script and communicating with database.
o Sending file to the client associated with the requested URL.
The block diagram representation of Web Server is shown below:
Important points
o If the requested web page at the client side is not found, then web server will sends
the HTTP response: Error 404 Not found.
o When the web server searching the requested page if requested page is found then it
will send to the client with an HTTP response.
o If the client requests some other resources then web server will contact to application
server and data is store for constructing the HTTP response.
Application Server
Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf,
ejb etc. It is a component based product that lies in the middle-tier of a server centric
architecture.
It provides the middleware services for state maintenance and security, along with persistence
and data access. It is a type of server designed to install, operate and host associated services
and applications for the IT services, end users and organizations.
The block diagram representation of Application Server is shown below:
The Example of Application Servers are:
1. JBoss: Open-source server from JBoss community.
2. Glassfish: Provided by Sun Microsystem. Now acquired by Oracle.
3. Weblogic: Provided by Oracle. It more secured.
4. Websphere: Provided by IBM.
Content Type
Content Type is also known as MIME (Multipurpose internet Mail Extension)Type. It is
a HTTP header that provides the description about what are you sending to the browser.
MIME is an internet standard that is used for extending the limited capabilities of email by
allowing the insertion of sounds, images and text in a message.
The features provided by MIME to the email services are as given below:
o It supports the non-ASCII characters
o It supports the multiple attachments in a single message
o It supports the attachment which contains executable audio, images and video files
etc.
o It supports the unlimited message length.
List of Content Types
There are many content types. The commonly used content types are given below:
o text/html
o text/plain
o application/msword
o application/vnd.ms-excel
o application/jar
o application/pdf
o application/octet-stream
o application/x-zip
o images/jpeg
o images/png
o images/gif
o audio/mp3
o video/mp4
o video/quicktime etc.
Servlet Interface
Servlet interface provides common behaviour to all the servlets. Servlet interface defines
methods that all servlets must implement.
Servlet interface needs to be implemented for creating any servlet (either directly or
indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to service the
requests, and to destroy the servlet and 2 non-life cycle methods.
Methods of Servlet interface
There are 5 methods in Servlet interface. The init, service and destroy are the life cycle
methods of servlet. These are invoked by the web container.
Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle
method of servlet and invoked by the web
container only once.
public void service(ServletRequest provides response for the incoming request.
request,ServletResponse response) It is invoked at each request by the web
container.
public void destroy() is invoked only once and indicates that
servlet is being destroyed.
public ServletConfig getServletConfig() returns the object of ServletConfig.
public String getServletInfo() returns information about servlet such as
writer, copyright, version etc.
GenericServlet class
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It
provides the implementation of all the methods of these interfaces except the service method.
GenericServlet class can handle any type of request so it is protocol-independent.
Methods of GenericServlet class
There are many methods in GenericServlet class. They are as follows:
1. public void init(ServletConfig config) is used to initialize the servlet.
2. public abstract void service(ServletRequest request, ServletResponse
response) provides service for the incoming request. It is invoked at each time when
user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and indicates
that servlet is being destroyed.
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
5. public String getServletInfo() returns information about servlet such as writer,
copyright, version etc.
6. public void init() it is a convenient method for the servlet programmers, now there is
no need to call super.init(config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for the
given parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters defined in
the web.xml file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in the
servlet log file and a stack trace.
Servlet Example by inheriting the Generic Servlet class
import java.io.*;
import javax.servlet.*;
public class First extends GenericServlet{
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
HttpServlet class
The HttpServlet class extends the GenericServlet class and implements Serializable
interface. It provides http specific methods such as doGet, doPost, doHead, doTrace etc.
Methods of HttpServlet class
There are many methods in HttpServlet class. They are as follows:
1. public void service(ServletRequest req,ServletResponse res) dispatches the request
to the protected service method by converting the request and response object into
http type.
2. protected void service(HttpServletRequest req, HttpServletResponse
res) receives the request from the service method, and dispatches the request to the
doXXX() method depending on the incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles
the GET request. It is invoked by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles
the POST request. It is invoked by the web container.
5. protected void doHead(HttpServletRequest req, HttpServletResponse
res) handles the HEAD request. It is invoked by the web container.
6. protected void doOptions(HttpServletRequest req, HttpServletResponse
res) handles the OPTIONS request. It is invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles
the PUT request. It is invoked by the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse
res) handles the TRACE request. It is invoked by the web container.
9. protected void doDelete(HttpServletRequest req, HttpServletResponse
res) handles the DELETE request. It is invoked by the web container.
10. protected long getLastModified(HttpServletRequest req) returns the time when
HttpServletRequest was last modified since midnight January 1, 1970 GMT.
Life Cycle of a Servlet (Servlet Life Cycle)
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
There are three states of a servlet: new, ready and end. The servlet is in new state if
servlet instance is created. After invoking the init() method, Servlet comes in the ready
state. In the ready state, servlet performs all the tasks. When the web container invokes
the destroy() method, it shifts to the end state.
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded when the
first request for the servlet is received by the web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after creating the servlet instance. The init method is
servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given belo
1. public void init(ServletConfig config) throws ServletException
4) service method is invoked
The web container calls the service method each time when request for the servlet is received.
If servlet is not initialized, it follows the first three steps as described above then calls the
service method. If servlet is initialized, it calls the service method. Notice that servlet is
initialized only once. The syntax of the service method of the Servlet interface is given
below:
1. public void service(ServletRequest request, ServletResponse response)
2. throws ServletException, IOException
5) destroy method is invoked
The web container calls the destroy method before removing the servlet instance from the
service. It gives the servlet an opportunity to clean up any resource for example memory,
thread etc. The syntax of the destroy method of the Servlet interface is given below:
1. public void destroy()