Servlets - Servlet Overview and Architecture (Unit 5)
Servlets - Servlet Overview and Architecture (Unit 5)
KCS-602
by
❑ SERVLET ARCHITECTURE
❑ APACHE TOMCAT
❑ SERVLET APPLICATION
Servers
• A server is a computer that responds to
requests from a client
– Typical requests: provide a web page, upload or
download a file, send email
• A server is also the software that responds to
these requests; a client could be the browser
or other software making these requests
• Any computer can be a server
– It is not unusual to have server software and
client software running on the same computer
3
Web Server: also known as HTTP Server, it
can handle HTTP Requests send by client and
responds the request with an HTTP Response.
9
Servlets
• A servlet is like an applet, but on the server side
10
Servlets vs. CGI scripts
• Advantages:
– Running a servlet doesn’t require creating a separate
process each time
– A servlet stays in memory, so it doesn’t have to be reloaded
each time
– There is only one instance handling multiple requests, not a
separate instance for every request
• Disadvantage:
– Less choice of languages (CGI scripts can be in any language)
11
Cont…
• Servlets are generic extensions to Java-enabled
servers
• Servlets are secure, portable, and easy to use
replacement for CGI
• Servlet is a dynamically loaded module that
services requests from a Web server
• Servlets are executed within the JVM
• Because the servlet is running on the server
side, it does not depend on browser
compatibility
Advantages of Servlets
Efficiency
More efficient – uses lightweight java threads
Persistency
Servlets remain in memory , can maintain state b/w requests
Portability
Servlets are written in Java, so are platform independent
Robustness
Error handling, Garbage collector to prevent problems with
memory leaks
Large class library – network, file, database, distributed
object components, security, etc.
Cont.
.
Security
– Security provided by the server as well as the
Java Security Manager
Powerful
– Servlets can directly talk to web server
– Facilitates db connection pooling, session
tracking etc.
Class and interface of Servlets
- A servlet is any class that implements the
javax.servlet.Servlet interface
– In practice, most servlets extend the
javax.servlet.http.HttpServlet class
– Some servlets extend
javax.servlet.GenericServlet instead
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.
How Generic
Servlet works?
HTTPSERVLET
•For creating Http Servlet we must extend :
javax.servlet.http.HttpServlet class, which
is an abstract class.
•Unlike Generic Servlet, the HTTP Servlet
doesn’t override the service() method.
Enterprise Information
Client Tier Middle Tier System (EIS) Tier
SQL
application Web Container
Servlet Database
Servlet
browser JSP
…
File
system
Servlet Name
• Servlet is invoked using its name
–Servlet should be located in appropriate
directory
Servlet instance creation After the Servlet class is loaded, Web Container creates the
instance of it and that is created only once in the life cycle.
Call to the init() method : init() method is called by the Web Container on servlet
Signature of init() method : public void instance to initialize the servlet.
init(ServletConfig config) throws
ServletException
Call to the service() method This method is called by the containers each time the request
Signature of service() method: for servlet is received. The service() method will then call the
public void service(ServletRequest doGet() or doPost() methods based on the type of the HTTP
request, ServletResponse response) request
throws ServletException, IOException
Call to destroy() method: The Web Container call the destroy() method before removing
servlet instance, giving it a chance for cleanup activity
Cont… Life Cycle
Free Servlet and JSP Engines
• Apache Tomcat
– http://jakarta.apache.org/tomcat/
• Allaire/Macromedia JRun
– http://www.macromedia.com/software/jrun/
• New Atlanta ServletExec
– http://www.servletexec.com/
• Gefion Software LiteWebServer
– http://www.gefionsoftware.com/LiteWebServer/
• Caucho's Resin
– http://www.caucho.com/
Compiling and Invoking Servlets
• Set your CLASSPATH
– C:\xampp\tomcat\lib\servlet-api.jar
– http://host/servlet/ServletName
❑SERVLET APPLICATION
APACHE TOMCAT
• Apache is most common HTTP Web Server on Internet.
• The Tomcat server is a Java-based Web Application
container used to run Servlet and JSP Web applications.
• Tomcat was chosen to be the official Sun Web
Component (JSP/Servlet) Container Reference
Implementation.
• It is an open source Java Servlet application server used
to deploy Java applications after they are built with JSP
and Servlets.
• It can be used as a stand-alone product or it can be
integrated with the Apache server.
45
What is a Container?
• Containers are interface b/w a component
and low-level platform-specific functionality
that supports the component.
Web container :
Manages the execution of JSP page and servlet
components for J2EE applications. Web
components and their container run on the J2EE
server.
46
J2EE Server and Containers
Client Web Server (Apache)
Tomcat
Browser
Servlet JSP page
Application
Client
Database
Client
Container Session Entity
Bean Bean
Client Machine
EJB Container
JBoss,
WebSphere,
WebLogic, etc
47
Installation of Apache Tomcat
• Java is already installed on PCs
The installation guides for TOMCAT:
- Initiate download of Tomcat from the site
http://tomcat.apache.org/
48
Start Up Tomcat
• Tomcat can be started by following command:
C:\xampp\tomcat\bin\startup.bat (Windows)
• All HTML, static files(images, css etc) are kept directly under Web
application folder(here First).
• Make folder WEB-INF inside your web app(First).
• Inside WEB-INF, make 2 folders: Lib and classes
• All the Servlet classes are kept inside classes folder.
• Lib contains two (.jar) files. Copy from their resp. location
i) for servlet, provide→ servlet-api.jar // Copy from:
C:\xampp\tomcat\lib\servlet-api.jar
To create a
simple
web.xml
file for our
web
application
.
5. Start the Server
Or,
execute below command on prompt:
–C:\apache-tomcat-7.0.14\bin\startup.bat
6. Starting Tomcat Server for the first time
Its needed to set JAVA_HOME in the Enviroment variable
•.
7. Run Servlet Application
• Open Browser and type--→
http:localhost:8080/First/hello
Cont… To Run HTML(index.html) in Tomcat
To start with an index file, make it in any editor, save with extension
.html and keep it parallel to WEB-INF.
to
other Resources
FORWARD()
RequestDispatcher
interface INCLUDE()
HttpServletResponse sendRedirect
interface method()
Redirecting Requests to Other Resources
(1)RequestDispatcher interface(a part of Servlet API)
It defines an object that receives the request from client and
dispatches it to the resource(such as servlet, JSP, HTML file). This
interface has following two methods: forward() and include()
a) Public void It forwards the request from
forward(ServletRequest req, one servlet to another
ServletResponse res): resource (such as servlet,
JSP, HTML file).
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletRespo
nse res)
throws ServletException,IOException {
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
res.sendRedirect("http://www.google.com");
pw.close(); }}
ServletConfig Interface
An object of ServletConfig is created by the web container for each servlet.
This object can be used to get configuration information from web.xml file.
Advantage of ServletConfig
Don't need to edit the servlet file if information is modified from the web.xml file.
The servletconfig object refers to the single servlet whereas servletcontext object refers to the whole
web application.
❑ SESSION HANDLING
❑ COOKIES
❑ URL RE-WRITING
❑ HIDDEN FIELDS
Managing Session in Servlets
We all know that HTTP is a stateless protocol. All requests and responses are independent.
But sometimes you need to keep track of client's activity across multiple requests. For eg.
When a User logs into your website, not matter on which web page he visits after logging in,
his credentials will be with the server, until he logs out. So this is managed by creating a
session.
1. Cookies
2. Hidden form field
3. URL Rewriting
4. HttpSession
Session is used to store everything that we can get from the client from all the requests the
client makes.
How Session Works
Basic concept: whenever a user starts using our application, we can save a
unique identification information about him, in an object which is available
throughout the application, until its destroyed. So wherever the user goes,
we will always have his information and we can always manage which user is
doing what. Whenever a user wants to exit from your application, destroy
the object with his information.
1) HttpSession
• HttpSession object is used to store entire session with a specific client. We can store, retrieve
and remove attribute from HttpSession object.
• Any servlet can have access to HttpSession object throughout the getSession() method of the
HttpServletRequest object.
How HttpSession works:
1. On client's first request, the Web Container generates a unique session ID and gives it back to the
client with response. This is a temporary session created by web container.
2. The client sends back the session ID with each request. Making it easier for the web container to
identify where the request is coming from.
3. The Web Container uses this ID, finds the matching session with the ID and associates the session
with the request.
Some Important Methods of Servlet HttpSession
Methods Description
long getCreationTime() returns the time when the session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
String getId() returns a string containing the unique identifier assigned to the
session.
long getLastAccessedTime() returns last time the client sent a request associated with the
session
• Cookies are small pieces of information that are sent in response from web server to client.
• Cookies are the simplest technique used for storing client state.
• Cookies are stored on client's computer.
• They have a lifespan and are destroyed by the client browser at the end of that lifespan.
• Using Cookies for storing client state has one shortcoming though, if the client has turned of
Cookie saving settings in his browser then, client state can never be saved because the
browser will not allow the application to store cookies.
1) Session cookies:
The session cookies do not have any expiration time. It is present in the browser memory.
When the web browser is closed then the cookies are destroyed automatically.
2) Persistent Cookies:
The Persistent cookies have an expiration time. It is stored in the hard drive of the user and it
is destroyed based on the expiry time.
• In URL rewriting, a token(parameter) is added at the end of the URL. The token consist of
name/value pair seperated by an equal(=) sign. For Example:
➢ When the User clicks on the URL having parameters, the request goes to the Web Container with
extra bit of information at the end of URL. The Web Container will fetch the extra part of the
requested URL and use it for session management.
➢ The getParameter() method is used to get the parameter value at the server side.
4) Using Hidden Form Field for Session Management in Servlet
• Hidden form field can also be used to store session information
for a particular client.
• In this case user information is stored in hidden field value and
retrieved from another servlet.
Advantages:
• Does not have to depend on browser whether the cookie is disabled or not.
• Inserting a simple HTML Input field of type hidden is required. Hence, its
easier to implement.
Disadvantage: