SERVLET PROGRAMMING
Servlets:
-
Java servlet are small, plateform
-
independent Java programs that runs in a web
server or application server and provides server
-
side processing such as accessing a
database and e
-
commerce transactions.The java servlet A
PI provides a simple framework
for building web applications .
Servlets are widely used for web processing. Servlets are designed
to handle
HTTP requests (get, post, etc) and are the standard Java replacement for a variety of other
methods, including CG
I scripts, Active Server Pages(ASPs).
Java Servlets are server side Java programs that require either a Web Server or an
Application Server for execution. Examples for Web Servers include Apache’s Tomcat
Server and Macromedia’s JRun.
Servlet
Contain
er
Servlets always run inside a Servlet Container. A server container is nothins but a
web server, which handles user requests and generates response. Servlet Container is
diffent from Web Server because it is only meant for Servlet and not other files(li
ke .html
etc).server container is responsible for maintaining lifecycle of the Servlet
A web container is an application framework with a runtime environment. In the
framework, application objects are created and invoked by the runtime. While invoki
ng
methods on the application objects, the container has to construct the objects for the
arguments. For instance, in GreetingServlet, the Container creates and passes the
HttpServletRequest and HttpServletResponse objects as arguments to the doPost()
meth
od
It also provides the following features and functanalities:
The network services over which request and response are sent
Registers servlet against one or more URLs
Manages the servlet lifecycle
Decodes MIME based requests
Construct MIME based respons
es
Supports the HTTP (also supports other protocols)
A servlet servlet container can also enforce security restrictions on the environment, such
as requesting the user to login to access a web page
Advantages of Java Servlets
1.
Portability
2.
Powerful
3.
Efficienc
y
4.
Safety
5.
Integration
6.
Extensibilty
7.
Inexpensive
Each of the points are defined below:
Portability
As we know that the servlets are written in java and follow well known standardized
APIs so they are highly portable across operating
systems
and server implementations.
We can develop a servlet on Windows machine running the tomcat server or any
other
server
and later we can deploy that servlet effortlessly on any other operating
system like Unix server running on the iPlanet/Netscape Application server. So
servlets are
write once, run anywhere (WORA)
program.
Powerful
We can do severa
l things with the servlets which were difficult or even impossible to
do with CGI, for example the servlets can talk directly to the web server while the CGI
programs can't do. Servlets can share data among each other, they even make
the
database
connection pools easy to implement. They can maintain the session by
using the session tracking mechanism which helps them to maintain information from
request to
request. It
can do many other things which are difficult to implement in the
CGI programs.
Efficiency
As compared to CGI the servlets invocation is highly efficient. When the servlet get
loaded in the server, it remains in the server's memory as a single object insta
nce.
However with servlets there are N threads but only a single copy of the servlet class.
Multiple concurrent requests are handled by separate threads so we can say that the
servlets are highly scalable.
Safety
As servlets are written in java, servlets
inherit the strong type safety of java language.
Java's automatic garbage collection and a lack of pointers means that servlets are
generally safe from memory management problems. In servlets we can easily handle
the errors due to
Java's exception handlin
g mechanism. If any exception occurs then it
will throw an exception.
Integration
Servlets are tightly integrated with the server. Servlet can use the server to translate the
file paths, perform logging, check authorization, and MIME type mapping etc.
Exte
nsibility
The servlet API is designed in such a way that it can be easily extensible. As it stands
today, the servlet API support Http Servlets, but in later date it can be extended for
another type of servlets.
Inexpensive
There are number of
free web se
rvers available for personal use or for commercial
purpose. Web servers are relatively expensive. So by using the free available web servers
you can add servlet support to it.
Advantages of Servlets over CGI
Servlets are server side components t
hat provides a powerful mechanism for
developing server web applications for server side. Earlier CGI was developed to
provide server side capabilities to the web applications. Although CGI played a major
role in the explosion of the
Internet
, its performance, scalability and reusability issues
make it less than optimal solutions.
Java
Servlets
changes all that. Built from ground
up using Sun's write once run anywhere
technology
java servlets provide excellent
f
ramework for server side processing.
Using servlets
web
developers
can create fast and efficient server side applications and
can run it on any servlet ena
bled web server. Servlet runs entirely inside the Java
Virtual Machine. Since the servlet runs on server side so it does not depend on browser
compatibility.
Servlets have a number of advantages over CGI and other API's. They are:
1.
Platform Independence
Ser
vlets are written entirely in java so these are platform independent. Servlets
can run on any Servlet enabled web server. For example if you develop an web
application in windows machine running Java web server, you can easily run the
same on apache web se
rver (if Apache Serve is installed) without modification or
compilation of code. Platform independency of servlets provide a great
advantages over alternatives of servlets.
2.
Performance
Due to interpreted nature of java, programs written in java are slow. B
ut the java
servlets runs very fast. These are due to the way servlets run on web server. For
any program initialization takes significant amount of time. But in case of servlets
initialization takes place first time it receives a request and remains in me
mory till
times out or server shut downs. After servlet is loaded, to handle a new request it
simply creates a new thread and runs service method of servlet. In comparison to
traditional CGI scripts which creates a new process to serve the request.
3.
Extens
ibility
Java Servlets are developed in java which is robust, well
-
designed and object
oriented language which can be extended or polymorphed into new objects. So
the java servlets take all these advantages and can be extended from existing class
to provide
the ideal solutions.
4.
Safety
Java provides very good safety features like memory management, exception
handling etc. Servlets inherits all these features and emerged as a very powerful
web server extension.
5.
Secure
Servlets are server side components, so it
inherits the
security
provided by the
web server. Servlets are also benefited with Java Security Manager.
Introduction to Server Side Programming
All of u
s (or most of us) would have started programming in Java with the ever famous
“Hello World!” program. If you can recollect, we saved this file with a .java extension
and later compiled the program using javac and then executed the class file with java.
Apa
rt from introducing you to the language basics, the point to be noted about this
program is that
–
“It is a client side program”. This means that you write, compile and
also execute the program on a client machine (e.g. Your PC). No doubt, this is the
easi
est and fastest way to write, compile and execute programs. But, it has little
practical significance when it comes to real world programming.
1.
Why Server Side Programming?
Though it is technically feasible to implement almost any business logic using
clie
nt side programs, logically or functionally it carries no ground when it comes
to enterprise applications (e.g. banking, air ticketing, e
-
shopping etc.). To further
explain, going by the client side programming logic; a bank having 10,000
customers would m
ean that each customer should have a copy of the program(s)
in his or her PC which translates to 10,000 programs! In addition, there are issues
like
security
, res
ource pooling, concurrent access and manipulations to
the
database
which simply cannot be handled by client side programs. The answer
to most of the issues cited
above is
–
“
Server
Side Programming”. Figure
-
1
illustrates Server side architecture in the simplest terms.
2.
Advantages of Server Side Programs
The list below h
ighlights some of the important advantages of Server Side
programs.
i.
All programs reside in one machine called the Server. Any number of
remote machines (called clients) can access the server programs.
ii.
New functionalities to existing programs can be added a
t the server side
which the clients’ can advantage without having to change anything from
their side.
iii.
Migrating to newer versions, architectures, design patterns, adding
patches, switching to new databases can be done at the server side without
having to b
other about clients’ hardware or software capabilities.
iv.
Issues relating to enterprise applications like resource management,
concurrency, session management, security and performance are managed
by service side applications.
v.
They are portable and possess t
he capability to generate dynamic and user
-
based content (e.g. displaying transaction information of credit card or
debit card depending on user’s choice).
3.
Types of Server Side Programs
i.
Active Server Pages (
ASP
)
ii.
Java Servlets
iii.
Java Server Pages (
JSPs
)
iv.
Enterprise
Java Beans (EJBs)
v.
PHP
To summarize, the objective of server side programs is to centrally manage all
programs relating to a particular application (e.g. Banking, Insurance, e
-
shopping,
etc). Clients with bare minimum requir
ement (e.g. Pentium II, Windows XP
Professional, MS Internet Explorer and an internet connection) can experience the
power and performance of a Server (e.g. IBM Mainframe, Unix Server, etc) from a
remote location without having to compromise on security or
speed. More
importantly, server programs are not only portable but also possess the capability to
generate dynamic responses based on user’s request.
Servlet Application Architecture
A servlet is a Java class that can be loaded dynamically into and run
by a special web
server. This
servlet
-
aware web server is called a
servlet container
, which also was called a
servlet
engine
in the
early days of the servlet technology.
Servlets interact with clients via a request
-
response model based on HTTP. Because
se
rvlet
technology works on top of HTTP, a servlet container must support HTTP as the protocol
for
client requests and server responses. However, a servlet container also can support
similar
protocols, such as HTTPS (HTTP over SSL) for secure transactions.
Http Request
Http Response
Basic Servlet Structure
As seen earlier, Java servlets are server side prog
rams or to be more specific; web
applications that run on servers that comply HTTP protocol. The javax.servlet and
javax.servlet.http packages provide the necessary interfaces and classes to work with
servlets. Servlets generally extend the HttpServlet cla
ss and override the doGet or the
doPost methods. In addition, other methods such as init, service and destroy also called as
life cycle methods might be used which will be discussed in the following section. The
skeleton of a servlet is given in Figure
Browser
Servlet
Container
Static
Contents
HTTP
Server
Servlet
A Servlet’s Life Cycle
The first time a servlet is invoked, it is the init method which is called. And remember
that this is called only once during the lifetime of a servlet. So, you can put all your
initialization code here. This method next calls
the service method. The service method in
turn calls the doGet or doPost methods (whichever the user has overridden). Finally, the
servlet calls the destroy method. It is in a sense equivalent to the finally method. You can
reset or close references / conn
ections done earlier in the servlet’s methods (e.g. init,
service or doGet /doPost). After this method is called, the servlet ceases to exist for all
practical purposes. However, please note that it is not mandatory to override all these
methods. More ofte
n than not, it is the doGet or doPost method used with one or more of
the other life cycle methods.
A Simple Java Servlet Example:
-
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet
{
Pub
lic void doGet(HttpServletRequest req, HttpServletReaponse res) throws
ServletException,IOException
{
Res.setContentType(“text/html”);
PrintWriter out=res.getWriter();
out.println(“<HTML>”);
out.println(“<HEAD><TITLE>Hello, welcome to the world of
servlet
programming</TITLE></HEAD>”);
out.println(“<BODY
BGCOLOR=RED
>”);
out.println(“
<H1>
Hello world
!</H1>
”);
out.pritpln(“</BODY></HTML>”);
out.close();
}
}
Tomcat Web Server
Tomcat is one of the most popular open source web server (including
web
-
container) for
deploying and running web applications
Tomcat Installation
The installa
tion process is des
cribed for tomacat 6.0
:
1.
Before installing tomcat 5.5 make sur
e that you have installed
JD
K1.6 on your
machine. The
environment variable JAVA_H
OME should be set to
C:
\
Program
Files
\
Java
\
jdk1.6.0_01
.
2.
Double click on the setup file to install the tomcat. Click on next
-
> select I agree
.
3.
The installer then prompts for port number, user and password. The default port
number on which the tomcat server
runs is 8080; you can leave it as it is. The
default user name is admin; you can leave this also as it is. Specify your
password. And password must be remembered as only the authorized user can
access tomcat administration site.
4.
The installer then asks f
or the path of J2SE 6.0 JRE installed on the machine. By
default path C:
\
program Files
\
Java
\
jre1.6.0_01 is selected, which is the default
path where the JRE is installed. Leave the selection as it is if you have not
changed the default path while installin
g JRE otherwise give the path where you
have installed the JRE.
5.
Finally click on the install button.After this installation process will take few
seconds to complete.
Six Steps to Running Your First Servlet
After you have installed and configured Tomcat
, you can put it into service. Basically,
you need to
follow six steps to go from writing your servlet to running it. These steps are summarized
as
follows:
1. Create a directory structure under Tomcat for your application.
2. Write the servlet source code
.
3. Compile your source code.
4. Create a deployment descriptor.
5. Run Tomcat.
6. Call your servlet from a web browser.
Step1:
-
Create the following directory structure for your Web Application “star”
In
webapps
star
(folder)
index.htm
l(welcome file)
WEB
-
INF
(folder)
classes
(folder)
HelloWorld.class
lib
(folder)
web.xml(file
-
deployment descriptor)
Step2:
-
Write your code in HelloWorld.java and save it.
Step3
:
-
Compile the java file and put your cl
ass in folder classes. Remember before
compile the
code %CATALINA%
\
lib
\
servlet
-
api.jar should be in class path
Step4
:
-
Create a web.xml which is known as deployment descriptor
and save it
in WEB
-
INF
A deployment descriptor is an optional component in a s
ervlet application. The descriptor takes
the form of an XML document called web.xml and must be located in the WEB
-
INF directory of
the servlet application. When present, the deployment descriptor contains configuration settings
specific to that applicatio
n
The web.xml for above example application must have the following content.
<?
xml version="1.0"
?>
-
<
web
-
app
xmlns
="
http://java
.sun.com/xml/ns/javaee
"
xmlns:xsi
="
http://www.w3.org/2001/XMLSchema
-
instance
"
xsi:schemaLocation
="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web
-
app_2_5.xsd
"
version
="
2.5
">
-
-
<
servlet
>
<
servlet
-
name
>
HelloWorld
</
servlet
-
name
>
<
servl
et
-
class
>
HelloWorld
</
servlet
-
class
>
</
servlet
>
-
<
servlet
-
mapping
>
<
servlet
-
name
>
HelloWorld
</
servlet
-
name
>
<
url
-
pattern
>
/Hel
loWorld
</
url
-
pattern
>
</
servlet
-
mapping
>
</
web
-
app
>
The tags for the 'web.xml' file above are pretty simple to understand. First we define a
<servlet> tag within <web
-
app></web
-
app> tags. In <servlet
-
name> we provide name of
our Servlet and in <servle
t
-
class>, the complete package and class name of
HelloWorld
class. The <servlet
-
mapping> tag allows us to specify a a URL pattern which
when requested by the client browser, will result in the delegation of the response
generation by the Servlet Container
to our HelloWorld.
This is all for 'web.xml' file.
Step5
:
-
Now run Tomcat by click o
n tomcat6.exe available in
C:
\
Program Files
\
Apache
Software Foundation
\
Tomcat 6.0
\
bin
.
Step6
:
Now open your browser and point to this
address:
http://localhost:8080/star/
H
elloWorld
. You should a get response like following
image in your browser window:
Example:
-
2
:
-
In given example we have shown how to display Current date .
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax
.servlet.*;
import javax.servlet.http.*;
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType("text/html");
PrintWriter out =
res.getWriter();
/* Display some response to the user */
out.println("<html><head>");
out.println("<title>TestServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>Current Date/Time: " +
new Date().toStri
ng() + "</p>");
out.println("</body></html>");
out.close();
}
}
Explanation
Our
TestServlet
is extremely simple. It displays the current date and time on the server to
the user.
We overrode just one method of
HttpServlet
class.
doGet()
is called whe
n a HTTP GET
request is received by the Servlet Container. In this method we set the content type of our
response to 'text/html' (informing the client browser that it is an HTML document). Then
we get hold of
PrintWriter
object and using its
println()
meth
od, we send our own HTML
content to the client browser. Once we are finished, we call its
close()
method.
Output:
-
Example:
-
In given example we will create
an application name greeting application in
which we fill a form an on the basis of that we wil
l display contents:
In this program we have created three files index.html which is stored in Greeting folder
parallel to WEB
-
INF , web.xml which is stored in WEB
-
INF, and GreetingServlet.class
stored in classes folder in WEB
-
INF
Index.html
<html>
<hea
d> <title>Projava registration</title></head>
<body >
<h1>Welcome</h1>
<form action="GreetingServlet" method="POST">
<p> Your Name<input type="text"size="40" name="name"/></p>
<p> Your email<input type="text" siez="40" name="email"/></p>
<inp
ut type="submit" value="Submit"/></p>
</form>
</body>
</html>
web.xml
<?xml version="1.0"?>
<web
-
app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema
-
instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javae
e
http://java.sun.com/xml/ns/javaee/web
-
app_2_5.xsd"
version="2.5">
<servlet>
<servlet
-
name>GreetingServlet</servlet
-
name>
<servlet
-
class>GreetingServlet</servlet
-
class>
</servlet>
<servlet
-
mapping>
<servlet
-
name>GreetingServlet</servlet
-
nam
e>
<url
-
pattern>/GreetingServlet</url
-
pattern>
</servlet
-
mapping>
</web
-
app>
GreetingServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class GreetingServlet extends HttpServlet
{
public vo
id doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
String name=req.getParameter("name");
String email=req.getParameter("email");
String message=null;
GregorianCalendar cal=new GregorianCalendar();
if(cal.ge
t(Calendar.AM_PM)==Calendar.AM)
message="Good Morning";
else
message="Good Evening";
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<p>"+message+","+name+"</p>");
out.
println("<p> Thanks for registering your email("+email+")with us.</p>");
out.println("<p>
-
The project Java Team.</p>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
Accessing Greeting Application:
Step1:
-
type
http://localhost:8080/Greeting
or
http://localhost:8080/Greeting
/index.html
Step2:
-
fill the name and email
Step3:
-
Click on the sublit button
Step4:
-
GreetingServlet will be invo
ked and will give the following response
Methods of Servlets
A Generic servlet contains the following five methods:
init()
public void init(ServletConfig config) throws ServletException
The
init() method
is called only once by the servlet container t
hroughout the life of a
servlet. By this init() method the servlet get to know that it has been placed into
service.
The servlet cannot be put into the service if
The init() method does not return within a fix time set by the web
server
.
It throws a ServletException
Parameters
-
The init() method takes
a
ServletConfig
object that contains the
initialization parameters and servlet's configuration and throws a
ServletEx
ception
if
an exception has occurred.
service()
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException
Once the servlet starts getting the requests, the service() method is called by the servlet
container to re
spond. The servlet services the client's request with the help of two
objects. These two
objects
javax.servlet.ServletRequest
and
javax.servlet.ServletResponse
are passed
by the servlet container.
The status code of the response always should be set for
a servlet that throws or sends
an error.
Parameters
-
The service() method takes
the ServletRequest
object that contains the
client's request and the object
ServletResponse
contains the servlet's response. The
service() method throws
ServletException an
d IOExceptions
exception.
getServletConfig()
public ServletConfig getServletConfig()
This method contains parameters for initialization and startup of the servlet and returns
a
ServletConfig object.
This object is then passed to the init method. When th
is
interface is implemented then it stores
the ServletConfig object
in order to return it. It
is done by the generic class which implements this inetrface.
Returns
-
the ServletConfig object
getServletInfo()
public String getServletInfo()
The informatio
n about the servlet is returned by this method like version, author etc.
This method returns a string which should be in the form of plain text and not any kind
of markup.
Returns
-
a string that contains the information about the servlet
destroy()
publ
ic void destroy()
This method is called when we need to close the servlet. That is before removing a
servlet instance from service, the servlet container calls the destroy() method. Once the
servlet container calls the destroy() method, no service methods
will be then called .
That is after the exit of all the threads running in the servlet, the destroy() method is
called. Hence, the servlet gets a chance to clean up all the resources like memory,
threads etc which are being held.
Life cycle of Servlet:
-
The first time a servlet is invoked, it is the init method
which is called. And remember that this is called only once during the lifetime of a
servlet. So, you can put all your initialization code here. This method next calls the
service method. The serv
ice method in turn calls the doGet or doPost methods
(whichever the user has overridden). Finally, the servlet calls the destroy method. It is in
a sense equivalent to the finally method. You can reset or close references / connections
done earlier in the
servlet’s methods (e.g. init, service or doGet /doPost). After this
method is called, the servlet ceases to exist for all practical purposes. However, please
note that it is not mandatory to override all these methods. More often than not, it is the
doGet
or doPost method used with one or more of the other life cycle methods.
The life cycle of a servlet can be categorized into four parts:
1.
Loading and Inatantiation:
The servlet container loads the servlet during startup
or when the first request is made. The
loading of the servlet depends on the
attribute <load
-
on
-
startup> of web.xml file. If the attribute <load
-
on
-
startup> has
a positive value then the servlet is load with loading of the container otherwise it
load when the first request comes for service. A
fter loading of the servlet, the
container creates the instances of the servlet.
2.
Initialization:
After creating the instances, the servlet container calls the init()
method and passes the servlet initialization parameters to the init() method. The
init() m
ust be called by the servlet container before the servlet can service any
request. The initialization parameters persist untill the servlet is destroyed. The
init() method is called only once throughout the life cycle of the servlet.
The servlet will be a
vailable for service if it is loaded successfully otherwise the
servlet container unloads the servlet.
3.
Servicing the Request:
After successfully completing the initialization process,
the servlet will be available for service. Servlet creates seperate thre
ads for each
request. The sevlet container calls the service() method for servicing any request.
The service() method determines the kind of request and calls the appropriate
method (doGet() or doPost()) for handling the request and sends response to the
c
lient using the methods of the response object.
4.
Destroying the Servlet:
If the servlet is no longer needed for servicing any
request, the servlet container calls the destroy() method . Like the init() method
this method is also called only once throughout
the life cycle of the servlet.
Calling the destroy() method indicates to the servlet container not to sent the any
request for service and the servlet
releases all the resources associated with it.
Java Virtual Machine claims for the memory associated wit
h the resources for
garbage collection.
Life Cycle of a Servlet
Example:
-
example given below shows the life cycle of a servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Servlet_LifeCycle e
xtends HttpServlet{
int i;
public void init() throws ServletException
{
i=0;//initializing i value
}
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
IOException,ServletException
{
res.setContentType("text/html");
Prin
tWriter out=res.getWriter();
if(i==0)
{
out.println("<HTML><HEAD><TITLE>Servlet's life
cycle</TITLE>");
out.println("</HEAD><BODY><h1>i value initializzed in init
method");
out.println("</h1>"+"<h1>"+i+"</h1>");
out.println("</body>");
out.println("</html>");
}
i=i+1;
if(i==10)
{
out.println("<HTML><HEAD><TITLE>Servlet's life cycle</TITLE>");
out.println("</HEAD><BODY><h1>i value initializzed 10,");
out.println("hencecalling destroy method to reset it in init
method");
out.println("</h1>"+"<h1>"+i+"</h1>");
out.println("</body>");
out.println("</html>");
destroy();
}
else
if(i<10)
{out.println("<HTML><HEAD><TITLE>Servlet's life
cycle</TITLE>");
out.println("</HEAD><BODY><h1>i value initializz
ed in doGet
method");
out.println("</h1>"+"<h1>"+i+"</h1>");
out.println("</body>");
out.println("</html>");
}
}
public void destroy()
{
i=0;
}
}
Output:
-
First time output will be given as above .
To appreciate th
e execution of the servlet life
cycle methods, keep refreshing the browser (F5 in Windows). In the background, what
actually happens is
–
with each refresh, the doGet method is called which increments
i’s value and displays the current value.
After press F
5 56 times output will be as
given
after press F5 10 times output is:
Example:
-
In this example we are going to know how we can make a program on
counter which will keep track how many times the servlet has been accessed.
import java.io.*;
import j
avax.servlet.*;
import javax.servlet.http.*;
public class SimpleCounter extends HttpServlet{
static int counter = 0;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOExcept
ion {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
counter++;
pw.println("At present the value of the counter is " + counter);
}
}
Output:
-
Java Servlet API:
-
Servlets are basically developed for serv
er side applications and designed to
handle http requests. The servlet
-
programming interface (Java Servlet API) is a standard
part of the J2EE plateform and has the following advantage over other comman server
extension mechanisms:
They are faster than ot
her server extensions, like,CGI scripts because they
use a different process model.
They use a standards API that is supported by many Web servers.
Since servlets are written in java, servlets are portable between servers and
operating systems. They have a
ll of the advantage of the java language,
including ease of development.
They can access the large set of APIs available for the java plateform.
The Servlet API is specified in two Java extension packages.
1.
javax.servlet
2.
javax.servlet.http
The classes and
interface in the
javax.servlet
package are protocol
–
independent. While
the second package
javax.servlet.http
contains classes and interfaces that are specified
to HTTP. Some of the classes/ interfaces in the
javax.servlet.http
extend those in the
javax
.servlet
package.
Overview of the java servlet API
The most commonly used classes/ interfaces of the Servlet are described below:
Purpose
Class/Interface
Servlet Implementation
javax.servlet.Servlet(Interface)
javax.servlet.SingleThreadModel(Interf
ace)
javax.servlet.Genericservlet (Abstract class)
javax.servlet.http.HttpServlet(Abstract class)
Servlet Exception
Javax.servlet.ServletException(Generic
Exception)
Javax.servlet.UnavailableException(Temp or
Parmanent)
Servlet Configurations
Javax.ser
vlet.ServletConfig(Interface)
Request and Responses
Javax.servlet.Servletrequest(Interface)
Javax.servlet.ServletResponse(Interface)
Javax.servlet.ServletInputStream(class)
Javax.servlet.ServletOutputStream(class)
Javax.servlet.http.HttpServletRequest(In
terface)
Javax.servlet.http.HttpServletResponse(Interface)
Session Tracking
Javax.servlet.http.HttpSession(Interface)
Servlet Context
Javax.servlet.ServletContext(Interface)
Servlet Collaboration
Javax.servlet.RequestDispatcher
Filtering
Javax.serv
let.Filter(Interface)
Javax.servlet.FilterChain(Interface)
Javax.servlet..FilterConfig(Interface)
Cookies
Javax.servlet..http.Cookie(Interface)
Web servers with java servlet i
mplementation. Such as tomcat, Weblogic, Orion, iPlanet,
JRUN etc use most of the interfaces and classes in the above table. In fact apart from the
various listener interfaces, there is only one class (javax.servlet.http.HttpServlet) and one
interface( jav
ax.servlet.Filter) that are left for you to implement when building web
applications.
Enter the password to open this PDF file:
File name:
-
File size:
-
Title:
-
Author:
-
Subject:
-
Keywords:
-
Creation Date:
-
Modification Date:
-
Creator:
-
PDF Producer:
-
PDF Version:
-
Page Count:
-
Preparing document for printing…
0%
Σχόλια 0
Συνδεθείτε για να κοινοποιήσετε σχόλιο