SERVLETS 01 - Introduction To Servlets
SERVLETS 01 - Introduction To Servlets
Introduction
1
Objectives
At the end of this module, you will be able to:
2
Server-side Programming
Static HTTP transaction - Browser requests for index.html, and Server responds with HTML
file
index.html
1. Browser 2. Server Finds
Request File
Reads the File
<html> ….
</html>
4. Browser Displays 3. Server
Page Response
.php /
.cgi 2. Executes Server Program
1. Browser Request
3. May Communicate with Database
4. Creates HTML
<html> …. 5. Server returns HTML Response
6. Browser Displays Page </html>
5
3
Database
4
Web Server
A computer having server software installed within it which serves up web pages
A program that uses client/ server model and World Wide Web’s Hypertext Transfer
Protocol (HTTP)
Responsible for accepting HTTP requests from clients (web browsers) and serving HTTP
responses which are web pages such as HTML documents
Popular web servers
Apache HTTP Server (Apache)
Microsoft Internet Information Server (IIS)
Sun Java System Web Server
5
Java server-side web components
A web component is a software entity that runs on a web server
Provides it with the capabilities needed for dynamically handling client requests and
generating web presentation content
The J2EE specification defines two types of web components
Servlets
Java Server Pages(JSPs)
Database
Application Client EJB
6
What are Servlets?
A Java class that runs on a web server and dynamically handles client requests
7
Uses of Servlets
Processing and/or storing data submitted by an HTML form
Example: Processing data of a login form
8
Servlet Architecture
Overview
Java Servlet API are in packages javax.servlet
and javax.servlet.http
Provide interfaces and classes for Servlet interface
writing servlets
LoginServlet
Extend HttpServlet class (a user-defined servlet)
To implement HTTP-specific services
9
Servlets
Deploying a Simple Servlet
10
Steps for writing and deploying simple servlet
1. Set environment variables: JAVA_HOME, CATALINA_HOME, CLASSPATH, and PATH
2. Create a directory, say “MyWebApplication” in C:\Program Files\ Software
Apache Foundation\Tomcat 5.0\webapps
3. Compile your servlet say “WelcomeServlet.java” in C:\Program Files\ Software
Apache
Foundation\Tomcat5.0\webapps\MyWebApp\WEB-INF\classes directory
4. Create web.xml file and place it in C:\Program Files\Apache Software Foundation\Tomcat
5.0\webapps\MyWebApplication\WEB-INF folder
5. Start Tomcat server by double-clicking C:\Program Files\Apache Software Foundation\Tomcat
5.0\bin\startup.batch file OR by selecting Start -> Programs -> Apache Tomcat 5.0 ->
Monitor Tomcat
6. Open browser with URL: http://localhost:10000/ to check Tomcat is successfully installed
7. Give URL as http://localhost:10000/MyWebApplication/WelcomeServlet to test your servlet
11
Directory Structure of a Web application
MyWebApplication
WEB-INF
web.xml
*.tld
12
Demo for a Simple Servlet
A simple HTTP Servlet that displays a Welcome message on the web
page
Files required:
WelcomeServlet.java
web.xml
13
Demo for a Simple Servlet (Contd.).
An HTTP Servlet that displays a Welcome message
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
14
The Web Deployment Descriptor – web.xml
An XML file web.xml is a deployment descriptor that
describes
mapping from URIs to application resources
initialization parameters
security constraints
registration of listeners and filters
Example: web.xml
<web-app>
<display-name>A Small Web Application</display-name>
<servlet>
<servlet-name>MyFirstServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyFirstServlet</servlet-name>
<url-pattern>/welcome.msg</url-pattern>
</servlet-mapping>
</web-app>
15
Web Container
Web components and their container run on J2EE server
Provides execution environment for servlets and JSPs of a web application
Manages execution of JSP and servlet components for J2EE applications
16
Role of a Web Container
Communication Support
Provides an easy way for servlets to talk to web server
Lifecycle Management
Controls lifecycle of servlets
Multithreading Support
Automatically creates a new Java thread for every servlet request it receives
Declarative Security
Enables to configure security in an XML deployment descriptor thereby avoiding hard-coding it in
servlet or any other class code
JSP Support
Does JSP processing
17
How web container handles Servlet
requests
Container creates 2 objects on receiving a for a servlet: HttpServletRequest and
request
HttpServletResponse
Finds right servlet based on URL in the request
Creates a thread for that request
Passes request and response objects to the servlet thread
Calls
servlet’s service() method
The service() method in turn calls doGet or doPost based on type of request (Assume request
was an HTTP GET)
The doGet method generates dynamic page and captures it in response object
Converts response object into an HTTP response on completion of thread
Sends this response to the client
Finally deletes the request and response objects
18
Knowledge Checkpoint
1. Suppose you are a web developer working for an Online Movie Service. You want to use a
servlet called MovieServlet so that clients can access the latest film shows for the day in a
particular city from your movie database. Determine the correct sequence of following steps
carried out by MovieServlet when processing a request from a client
Sl.No Description
1 Check information included in the Http request
2 Access any necessary business components or data
storage
3 Set the appropriate Http response parameters
4 Read data submitted by the client
5 Send the response to the client
6 Format the results in a response
19
Servlets
Servlet Life Cycle
20
Life Cycle of a Servlet
An HTTP servlet's life cycle is controlled by the web container where it is
deployed
Source: http://www.iam.ubc.ca/guides/javatut99/servlets/lifecycle/index.html
21
Servlet interface
Provides methods that manage the servlet and its communications with clients
init(ServletConfig)
Initializes the servlet. Runs once before any requests can be serviced
service(ServletRequest, ServletResponse)
Processes a single request from the client
destroy()
This method releases all the resources
getServletConfig()
Returns a servlet config object and this object
contains any initialization parameters and
startup configuration information for this servlet
getServletInfo()
Returns a string containing information about the
servlet, such as its author, version, and
copyright
22
Lifecycle Methods
Interaction between a web server, a servlet, and a client is controlled using the life-cycle
methods
A servlet's life cycle methods are
init()
service()
destroy()
The init() and destroy() methods will be called only once during the life time of your Servlet
The service() and it's broken down methods ( doGet(), doPost() etc ) will be called as many
times as requests are received for them by the web container
23
Initializing a servlet
Web container initializes servlet after web container loads and instantiates servlet class and before it
delivers requests from clients
The init method is invoked only once during servlet's lifetime – when servlet is first created
Two versions of init method – one that takes no arguments and one that takes a ServletConfig object
as an argument
init( ) - use this when your servlet does not need any specific initialization
init(ServletConfig) - use this when your servlet needs to check specific settings before completing
initialization
24
Servicing client requests
Once servlet is loaded and initialized, the servlet is able to handle client requests
Web container processes the requests in servlet’s service method
Every time the server receives an incoming request for a servlet, it generates a new thread and calls the
service method
The service method then checks the HTTP request type and calls the appropriate doXXX method
Syntax: public void service(ServletRequest req, ServletResponse res)
Role of service method
To extract information from the request
Access external resources
Populate the response based on that information
25
Destroying a Servlet
Server may unload a servlet instance
If the servlet has been idle for some time (default is 30 minutes) or
If the web application is undeployed or
If server shuts down
28