Vous êtes sur la page 1sur 15

No Use of reading this material …..

Servlets

The discussion of networking focuses on both sides of a client-server


relationship. The client requests that some action be performed and the server
performs the action and responds to the client. This request-response model of
communication is the foundation for the highest-level views of networking in Java—
servlets and JavaServer Pages (JSP). A servlet extends the functionality of a server,
such as a Web server. Packages javax.servlet and javax.servlet.http provide the
classes and interfaces to define servlets. Packages javax.servlet.jsp and
javax.servlet.jsp.tagext provide the classes and interfaces that extend the servlet
capabilities for JavaServer Pages. Using special syntax, JSP allows Web-page
implementors to create pages that use encapsulated Java functionality and even to
write scriptlets of actual Java code directly in the page.

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.

“A Servlet is a Web component, managed by a container that generates


dynamic content. Servlets are small, platform-independent Java classes compiled to
an architecture-neutral byte code that can be loaded dynamically into and run by a
Web server”

Unless You Practice…….


No Use of reading this material …..

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.

Life Cycle of a Servlet


Three methods are central to the life cycle of a servlet. These are init( ),
service( ), and destroy( ). They are implemented by every servlet and are invoked at
specific times by the server.
First, assume that a user enters a Uniform Resource Locator (URL) to a Web
browser. The browser then generates an HTTP request for this URL. This request is
then sent to the appropriate server.

Unless You Practice…….


No Use of reading this material …..

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.

Unless You Practice…….


No Use of reading this material …..

Life Cycle Methods of the GenericServlet:-


public void init( ServeltConfig config)
The Servlet container calls this methods once during a servlet’s execution
cycle to initialize the servlet. The ServletConfig argument is supplied by the servlet
container that executes the servlet.
public void service( ServletRequest request, ServletResponse response)
The servlet container calls this method to response to a client request to the
servlet

public void destroy()


This is a “Clean Up ” method is called when a servlet is terminated by its
servlet container.

Differences between Servlets and Applets: -

Sno Servlets Applets


1. Server side component and improves that Browser side component that improves
functionality functionality
2. Executes in the browser.
Executes within server space
3. These are not like.
Process the client request and response.
4. These are embedding programs.
These are not embedding in html.

5. These are unable to creating web pages


Servlets can create dynamic web pages dynamically.
Unless You Practice…….
No Use of reading this material …..

Working with Servlets:

Servlet components go through three stages during their execution:


1. Development Phase
2. Deployment Phase
3. Running Phase

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.

Unless You Practice…….


No Use of reading this material …..

// Example of a Servlet file name is FirstServlet.java


import javax.servlet.*;
import java.io.*;
public class FirstServlet extends GenericServlet
{
public void service(ServletRequest rq,ServletResponse rsp)
throws ServletException,IOException
{
PrintWriter pw = rsp.getWriter();
rsp.setContentType("text/html");
pw.write("<html><body><h2 align=center ");
pw.write("style=background:orange>THIS IS MY");
pw.write(" FIRST SERVLET PROGRAM</h2>");
pw.write("</body></html>");
}
}

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

or the alternative is to set the classpath in environment variable as “C:\Program Files\Apache


Software Foundation\Tomcat 5.5\common\lib\servlet-api.jar” can be complied directly
This command will generate the Class file.

Unless You Practice…….


No Use of reading this material …..

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 )

Create the following Directory Structure:

Web applications are deployed in the webapps subdirectory of tomcat-server.


A Web application has a well-known directory structure in which all the files that are
part of the application reside. This directory structure can be created by the server
administrator in the webapps directory or the entire directory structure can be
archived in a Web application archive file. Such an archive is known as a WAR file and
ends with the .war file extension. If a WAR file is placed in the webapps directory, then,
when the Tomcat server begins execution, it extracts the contents of the WAR file into
the appropriate webapps subdirectory structure.

Unless You Practice…….


No Use of reading this material …..

The Creation of the Deployment Descriptor ( web.xml )

A Web application to handle the requests. This configuration occurs in a


deployment descriptor, which is stored in a file called web.xml. The deployment
descriptor specifies various configuration parameters such as the name used to
invoke the servlet (i.e., its alias), a description of the servlet, the servlet’s fully
qualified class name and a servlet mapping (i.e., the path or paths that cause the
servlet container to invoke the servlet). You must create the web.xml file for this
example. As follows…

<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

This URL pattern is having 5 components


1. Protocol
2. Server IP Address
3. Port Number at which exchange of the data takes place
4. Context
5. Requested File path
Port-Number
Requested-File Path

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.

Advantages over Other Server-Side Technologies


In simple terms, a servlet is a piece of code that adds new functionality to a
server But compared to other technologies, servlets have a number of advantages:
All the major web servers and application servers support servlets And, since
servlets are written in the Java programming language, they can be used on any
operating system with a Java runtime environment.
 Integration
Servlets are developed in Java and can therefore take advantage of all other
Java technologies, such as JDBC for database access, JNDI for directory access, RMI
for remote resource access, etc. Starting with Version 2.2, the servlet specification is
part of the Java 2 Enterprise Edition (J2EE), making servlets an important ingredient
of any large-scale enterprise application, with formalized relationships to other
serverside technologies such as Enterprise JavaBeans.
 Efficiency
Servlets execute in a process that is running until the servlet-based
application is shut down. Each servlet request is executed as a separate thread in this
permanent process.
 Scalability
By virtue of being written in Java and the broad support for servlets, a servlet-
based application is extremely scalable. You can develop and test the application on a
Windows PC using the standalone servlet reference implementation, and deploy it on
anything from a more powerful web server
 Robustness and security
Java is a strongly typed programming language. This means that you catch a
lot of mistakes in the compilation phase that you would only catch during runtime if you
used a script language such as Perl. Java's error handling is also much more robust
than C/C++, where an error such as division by zero typically brings down the whole
server. In addition, Servlets use specialized interfaces to server resources that aren't
vulnerable to the traditional security attacks.

Unless You Practice…….


No Use of reading this material …..

Reading Servlet Parameters


The parameter of a servlet are attach to the request URL of the browser and
these parameters are from HTML forms. The names and values of the form
components are the names and values of the parameter to a servlet.
The target servlet is specified by action attribute, type of request (they are
two type of requests GET and POST) is specified by METHOD attribute of a FORM
tag.These parameters of read by a servlet using ServletRequest interface which is a.
argument to the service method. Such as……
public void service(ServletRequest req, ServletResponse res)
{
String parameter_value=req.getParameter(“parameter_name”);
}

The javax.servlet.http Package

Web-based servlets typically extend class HttpServlet. Class HttpServlet


overrides method service to distinguish between the types of requests received from
a client Web browser. The two most common HTTP request types (also known as
request methods) are get and post. Class HttpServlet defines methods doGet and
doPost to respond to get and post requests from a client, respectively. These methods
are called by method service, which is called when a request arrives at the server.
Method service first determines the request type, then calls the appropriate method
for handling such a request.

Methods doGet and doPost receive as arguments an HttpServletRequest object


and an HttpServletResponse object that enable interaction between the client and the
server. The methods of HttpServletRequest make it easy to access the data supplied
as part of the request. The HttpServletResponse methods make it easy to return the
servlet’s results to the Web client.

Every call to doGet or doPost for an HttpServlet receives an object that


implements interface HttpServletRequest. The Web server that executes the servlet
creates an HttpServletRequest object and passes this to the servlet’s service method
A variety of methods are provided to enable the servlet to process the client’s
request.

Unless You Practice…….


No Use of reading this material …..

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.

Unless You Practice…….


No Use of reading this material …..

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”);

Unless You Practice…….


No Use of reading this material …..

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.

This interface allows servlets to


1. View and manipulate information about a session, such as the session
identifier, creation time, and last accessed time
2. Bind objects to sessions, allowing user information to persist across multiple
user connections

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

Unless You Practice…….


No Use of reading this material …..

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.

--:: My Best Wishes ::--

Unless You Practice…….

Vous aimerez peut-être aussi