Académique Documents
Professionnel Documents
Culture Documents
Servlets
Java has primarily been a language used to implement browser side program,
also known as applets, when it comes to the web. However with the java Servlets API
the power of the Java can be applied to server side software as well. Servlets are
small programs that execute on the server side of a Web connection. Just as applets
dynamically extend the functionality of a Web browser, servlet dynamically extend the
functionality of a Web server. There is that a Servlet run on the server and will
respond to a request from the client either in the form of HTML pages. Servlet are the
java counterpart to non-java dynamic web content technologies such as PHP, ASP and
.Net.
Servlets
The Servlet is small programming unit area of the code that can be executed
when its called. The Servlets are server side components and resides within the
server only, so the performance of server can be increased. And these can accept the
client request from browser and process it and generating the response for sending
to the requested client.
Simply….
Servlets are programs that run on a web server and build web pages
dynamically
Servlets run on server to accept request and send back the response
Servlets are Platform and Server independent
Servlets have access to the entire family of Java API’s (JDBC, HTTP etc...)
Servlet Container
A Servlet container is a specialized web server that supports servlet
execution. Individual servlet are registered with be servlet container. Providing the
container with the information about what functionally should be provided and what
URL or other locator they will to identify themselves. The Servlets container is then
able to initialize the servlet
as necessary and deliver
request to the servlet as
they arrive. Many
containers have the ability
to dynamically add and
remove Servlets from the
system allowing new
servlet to be deployed or
removed without affecting
other Servlets running
from the same container.
Servlet container are also
refers to as web container
or web engines. A servlet
container is a run time environment to provide life cycle management and works in
collaboration with server to delegate request to the corresponding servlet and to send
the response back to the client. Besides life cycle management a container provides
other services such as Communication support, Multi-threading, Security, Session
Management.
Second, this HTTP request is received by the Web server. The server maps this
request to a particular servlet. The servlet is dynamically retrieved and loaded into the
address space of the server.
Third, the server invokes the init( ) method of the servlet. This method is
invoked only when the servlet is first loaded into memory. It is possible to pass
initialization parameters to the servlet so it may configure itself.
Fourth, the server invokes the service( ) method of the servlet. This method is
called to process the HTTP request. You will see that it is possible for the servlet to
read data that has been provided in the HTTP request. It may also formulate an HTTP
response for the client.
The servlet remains in the server’s address space and is available to process
any other HTTP requests received from clients. The service( ) method is called for
each HTTP request.
Finally, the server may decide to unload the servlet from its memory. The
algorithms by which this determination is made are specific to each server. The
server calls the destroy( ) method to relinquish any resources such as file handles
that are allocated for the servlet. Important data may be saved to a persistent store.
The memory allocated for the servlet and its objects can then be garbage collected.
In Brief……
A servlet’s life cycle begins when the servlet container loads the servlet into
memory—normally, in response to the first request that the servlet receives. Before
the servlet can handle that request, the servlet container invokes the servlet’s init
method. After init completes execution, the servlet can respond to its first request. All
requests are handled by a servlet’s service method, which receives the request,
processes the request and sends a response to the client. During a servlet’s life cycle,
method service is called once per request. Each new request typically results in a new
thread of execution (created by the servlet container) in which method service
executes. When the servlet container terminates the servlet, the servlet’s destroy
method is called to release servlet resources.
Development Phase:
In this phase will describe about the creation of the servlet class. Every Servlet
should implement the Servlet interface either directly or indirectly,i.e., we can extend
either javax.servlet.GenericServlet class which implements Servlet interface or we
can extend javax.servlet.http.HttpServlet class which extend GenericServlet class
Servlet API: - The collection of classes and interface is required to build, compile and
run the servlets are called Servlet API. These all are contains in two packages as
follows.
The servlet packages define two abstract classes that implement the interface
Servlet—class GenericServlet (from the package javax.servlet) and class HttpServlet
(from the package javax.servlet.http). These classes provide default implementations
of all the Servlet methods. Most servlets extend either Generic- Servlet or HttpServlet
and override some or all of their methods.
Servlets extend class HttpServlet, which defines enhanced processing
capabilities for servlets that extend the functionality of a Web server. The key method
in every servlet is service, which receives both a ServletRequest object and a
ServletResponse object. These objects provide access to input and output streams
that allow the servlet to read data from the client and send data to the client. These
streams can be either byte based or character based. If problems occur during the
execution of a servlet, either ServletExceptions or IOExceptions are thrown to indicate
the problem.
First, note that it imports the javax.servlet package. This package contains the
classes and interfaces required to build servlets. You will learn more about these later
in this chapter. Next, the program defines HelloServlet as a subclass of
GenericServlet. The GenericServlet class provides functionality that makes it easy to
handle requests and responses.
Inside HelloServet, the service( ) method (which is inherited from
GenericServlet) is overridden. This method handles requests from a client. Notice that
the first argument is a ServletRequest object. This enables the servlet to read data
that is provided via the client request. The second argument is a ServletResponse
object. This enables the servlet to formulate a response for the client.
The call to setContentType( ) establishes the MIME type of the HTTP response.
In this program, the MIME type is text/html. This indicates that the browser should
interpret the content as HTML source code.
Next, the getWriter( ) method obtains a PrintWriter. Anything written to this
stream is sent to the client as part of the HTTP response. Then println( ) is used to
write some simple HTML source code as the HTTP response.
Compile this source code and place the HelloServlet.class file in the Tomcat
class files directory as described
C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib\servlet-api.jar
For example:
javac –classpath “C:\Program Files\Apache Software Foundation\Tomcat
5.5\common\lib\servlet-api.jar” FirstServlet.java
Deployment Phase
After completion of the Development Phase Deployment Phase come into action
which follows following steps:
1. The Creation of a Directory Structure suitable for your application
2. The Creation of the Deployment Descriptor ( web.xml )
<web-app>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
<init-param>
<param-name>User</param-name>
<param-value>saicse</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
</web-app>
Servlets are initialized by method init. Method init is called exactly once in a
servlet’s lifetime, before any client requests are accepted. Method init takes
ServletConfig argument and throws a ServletException. The argument provides the
servlet with information about its initialization parameters (i.e., parameters not
associated with a request, but passed to the servlet for initializing the servlet’s state).
These parameters are specified in the web.xml deployment descriptor file as part of a
servlet element. Each parameter appears in an initparam element of the following
form:
<init-param>
<param-name>parameter name</param-name>
<param-value>parameter value</param-value>
</init-param>
Servlets can obtain initialization parameter values by invoking ServletConfig
method getInitParameter, which receives a string representing the name of the
parameter.For Example in above web.xml user in param name and saicse is value then
String value=getServletConfig().getInitParameter(“user”);
Now it will returns the value of user parameter as “saicse” assigned to the
String value.
Unless You Practice…….
No Use of reading this material …..
Running Phase:
This running phase involves calling the servlet in their context path by URL
pattern specified in the web.xml file.
To run our FirstServlet use the following URL
http://127.0.0.1:8080/MyApp/FirstServlet
http://127.0.0.1:8080/MyApp/FirstServlet
Protocol
Context-Path
IP-Address
1. Protocol
The Web Server offers many protocols. The HTTP (Hypertext Transfer Protocol)
that forms the basis of the World Wide Web uses URLs (Uniform Resource Locators) to
locate resources on the Web Server. The communication model defined by HTTP forms
the foundation for all web application design. A basic understanding of HTTP is key to
developing applications that fit within the constraints of the protocol, no latter which
server-side technology you use.
2. Server IP Address
The server localhost (IP address 127.0.0.1) is a well-known host name on
computers that support TCP/IP-based networking protocols such as HTTP. This host
name can be used to test TCP/IP applications on the local computer.We have to specify
he IP Address of the System at which Tomcat server is running on the LAN.
3. Port Number
The Tomcat server awaits requests from clients on port 8080. This port
number must be specified as part of the URL to request a servlet running in Tomcat
because it is the place where the Exchange of the data takes place.
4. Context Path
Within the container, each web application is represented by a servlet context.
The servlet context is associated with a unique URI path prefix called the context path,
as shown in Figure.This allows one servlet container to distinguish between the
different applications it serves and dispatch requests
Unless You Practice…….
No Use of reading this material …..
Finally, a context can hold objects shared by all components of the application,3
such as database connections and other shared resources needed by multiple servlets
and JSP pages.
5. Requested File Path
The remaining URI path is then used within the selected context to decide how
to process the request by comparing it to path-mapping rules defined by the
application's deployment descriptor. Servlet handles all requests with paths ending
with a specific file extension(such as .jsp) also.
HttpServletRequest
String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post
request. The name argument represents the parameter name.
Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a
post request.
String[] getParameterValues( String name )
For a parameter with multiple values, this method returns an array of
strings containing the values for a specified servlet parameter.
Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server.
Cookie objects can be used to uniquely identify clients to the servlet.
HttpSession getSession( boolean create )
Returns an HttpSession object associated with the client’s current
browsing session. This method can create an HttpSession object (true
argument) if one does not already exist for the client. HttpSession objects
are used in similar ways to Cookies for uniquely identifying clients.
HttpServletResponse
void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client. The
Cookie’s maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client.
ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client.
PrintWriter getWriter() Obtains a character-based output stream for
sending text data to the client.
void setContentType( String type )
Specifies the MIME type of the response to the browser. The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data). For example, MIME type
"text/html" indicates that the response is an HTML document, so the
browser displays the HTML page.
ServletContext
Defines a set of methods that a servlet uses to communicate with its servlet
container, for example, to get the MIME type of a file, dispatch requests, or write to a
log file
There is one context per "web application" per Java Virtual Machine. (A "web
application" is a collection of servlets and content installed under a specific subset of
the server's URL namespace such as /MyApp.)
In the case of a web application marked "distributed" in its deployment
descriptor, there will be one context instance for each virtual machine. In this
situation, the context cannot be used as a location to share global information
(because the information won't be truly global). Use an external resource like a
database instead.
ServletContext vs ServletConfig
ServletContext
1. Contains details for a web application containing several Servlets
2. It is one per application
3. It defines a set of methods that a servlet uses to communicate with its
container or Servlets within application
4. Context wide parameters are specified within <context-param> elements of the
web.xml. they are available to all the servlets within that application using the
methods getServletContext().getInitParameter(“param_name”);
ServletConfig
1. A servlet configuration object used by a servlet container to pass information
to a servlet during initialization.
2. It is one per servlet.
3. Initialization parameters for individual servlet are specified within <init-param>
sub-elements of the <servlet> element in web.xml.
getServletConfig().getInitParameter(“param_name”);
Session Tracking
HTTP is a stateless protocol. Each request is independent of the previous one.
However, in some applications, it is necessary to save state information so that
information can be collected from several interactions between a browser and a
server. Sessions provide such a mechanism.
A session can be created via the getSession( ) method of HttpServletRequest.
An HttpSession object is returned. This object can store a set of bindings that
associate names with objects. The setAttribute(), getAttribute(), getAttributeNames(),
and removeAttribute( ) methods of HttpSession manage these bindings. It is important
to note that session state is shared among all the servlets that are associated with a
particular client.
Provides a way to identify a user across more than one page request or visit to
a Web site and to store information about that user.
The servlet container uses this interface to create a session between an HTTP
client and an HTTP server. The session persists for a specified time period, across
more than one connection or page request from the user. A session usually
corresponds to one user, who may visit a site many times. The server can maintain a
session in many ways such as using cookies or rewriting URLs.
Cookies
Creates a cookie, a small amount of information sent by a servlet to a Web
browser, saved by the browser, and later sent back to the server. A cookie's value can
uniquely identify a client, so cookies are commonly used for session management.
The Cookie class encapsulates a cookie. A cookie is stored on a client and
contains state information. Cookies are valuable for tracking user activities. For
example, assume that a user visits an online store. A cookie can save the user’s name,
address, and other information. The user does not need to enter this data each time he
or she visits the store. A servlet can write a cookie to a user’s machine via the
addCookie( ) method of the HttpServletResponse interface. The data for that cookie is
then included in the header of the HTTP response that is sent to the browser.
A cookie has a name, a single value, and optional attributes such as a comment,
path and domain qualifiers, a maximum age, and a version number. Some Web
browsers have bugs in how they handle the optional attributes
The names and values of cookies are stored on the user’s machine. Some of the
information that is saved for each cookie includes the following:
The name of the cookie
The value of the cookie
The expiration date of the cookie (setMaxAge(int secs))
The comment of the Cookie ( setComment())
The expiration date determines when this cookie is deleted from the user’s machine. If
an expiration date is not explicitly assigned to a cookie, it is deleted when the current
browser session ends. otherwise, the cookie is saved in a file on the user’s machine.
the cookie is then supplied to the Web server. Otherwise, it is not. There is one
constructor for Cookie. It has the signature shown here:
Cookie(String name, String value)
Here, the name and value of the cookie are supplied as arguments to the constructor.