Servlets - Servlet Overview and Architecture (Unit 5)
Servlets - Servlet Overview and Architecture (Unit 5)
TECHNOLOGY
Content
s
SERVLET– SERVLET
OVERVIEW
SERVLET ARCHITECTURE
APACHE TOMCAT
SERVLET APPLICATION
Server
• A server is a computer that responds to
requests from asclient
– 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.
1
1
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.
.
⚫S
e
c
u
ri
t
y
– Security provided by the server as well
as the Java Security Manager
⚫Powerful
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?
HTTPSERVLE
T
•For creating Http Servlet we
must extend : class,
javax.servlet.http.HttpServlet
is an abstract class. which
•Unlike Generic Servlet,the HTTP
Servlet
doesn’t override the service()
method.
more…
more…
welcome-file-list tag in web.xml file of Project
The tag<welcome-file- is used for specifying the
files that
needs list>
to be invoked by server by default, if you do
not specify a file name while loading the project
on browser.
For e.g. You have created a project named
“MyServletProject” and you have few html pages
and servlet classes defined in the project. However
in browser you have given the url like this:
http://localhost:8080/MyServletProject
Usually we give the complete path like
this:http://localhost:8080/MyServletProject/index.html.
However if you have given the path like above then
the webserver will look for the <welcome-file-list>
<web-app>
....
<welcome-file-list>
<welcome-file>myhome.htm</welcome-file>
<welcome-file>myindex.htm</welcome-file>
<welcome-file>mydefaultpage.htm</welcome-file>
</welcome-file-list>
....
</web-app>
Based on the welcome file list, server would look for the
myhome.htm page if this doesn’t exist then the second
welcome file myindex.html and so on till it finds a valid
welcome
Note file.
If the <welcome-file-list> tag is not defined in
:welcome
web.xml
files defined
or the in the <welcome-file> tags does not
exist then the server would look for the following files in
the given sequence:
1) index.html 2) index.htm 3)
Java Servlet Architecture
• Two packages make up the servlet architecture
– javax.servlet
• Contains generic interfaces and classes that are
implemented and
extended by all servlets
– javax.servlet.http
• Contains classes that are extended when creating HTTP-specific servlets
• The heart of servlet architecture is the interface
class
javax.servlet.Servlet
Enterprise
Client Middle Information
Tier Tier System (EIS) Tier
SQL
applicatio Web Container
n
Servl Databas
et e
browser Servl
et
JSP File
… syste
m
Servlet Name
• Servlet is invoked using its name
–Servlet should be located in
appropriate directory
Loading Servlet Class A Servlet class is loaded when first request for the servlet is
received by the Web Container.
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 instance to initialize the servlet.
void 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
A Simple Servlet That Generates Plain Text
import java.io.*;
import javax.servlet.*;
import
javax.servlet.http.*;
public class
HelloWorld extends
HttpServlet
{
public void
doGet(HttpServletRe
quest request,
HttpServle
tResponse
response)
throws
ServletException,
IOException
{
A Servlet That Generates HTML
public class HelloWWW extends HttpServlet {
public void doGet(HttpServletRequest
request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>Hello
WWW</TITLE></HEAD>\n" +
"<BODY>\n" +
"<H1>Hello WWW</H1>\n"
+ "</BODY></HTML>");
} }
HelloWWW Result
Scalability of servlets
⚫The servlet is only recompiled if it was changed otherwise
the already compiled class is loaded
- Faster response times as servlet does not need to be recompiled
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)
{
public void doGet(HttpServletRequest
request,HttpServletResposne response)
throws ServletException {
3. Compiling a Servlet
• To compile a Servlet a JAR file is required. In
Apache Tomcat server servlet-api.jar file is
required to compile a servlet class.
• Download servlet-api.jar file.
• Paste servlet-api.jar file
inside Java\jdk\jre\lib\ext directory.
• Compile the Servlet class.
• After compiling Servlet class, paste the class
file into WEB-INF/classes/ directory.
4. Create Deployment Descriptor
To create
a simple
web.xml
file for
our web
applicatio
n
.
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
TTomcat
o start with an index file, make it in any editor, save
with extension
.html and keep it parallel to WEB-INF.
other
Resources
FORWARD(
RequestDispatch )
er interface INCLUDE()
HttpServletResponse sendRedirect
interface method
Redirecting Requests to Other
Resources
(1)RequestDispatcher interface(a paít of Seívlet
API)
It defines an object that receives the request from
client and dispatches it to the resource(such as servlet,
JSP, HTML
a) Public voidfile). This interface hasthefollowing
It forwards two
request from
forward(ServletRequest
methods: forward() andreq, one servlet to another
include()
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.
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.
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: