Professional Documents
Culture Documents
Standalone Applications
A standalone application is a program that runs on your computer. It is more or less
like a C or C++ program. It always contains a main method().
Applets
An applet is an application designed to travel over the Internet and to be executed on
the client machine by a Java- Compatible Web browser like Internet Explorer or
Netscape. Applets are also java programs but they reside on the servers. An applet
can not be executed like standalone application. Applet can be executed only by
embedding it into an HTML page like an image or sound file. To run an applet you
need to access an HTML page which has applet embedded into it. When the web
browser downloads such an HTML page, it subsequently loads the executable file,
which contains Applet and then executes it on the local machine. Applet has its own
lifecycle. It does not have main method like standalone application.
Web Applications
Web applications run on the Web server. Web applications are accessed through web
clients i.e. web browser like Internet Explorer or Netscape. Whenever you access
some web site by specifying the URL(Universal Resource Locator), you are accessing
some web application. The main components of a web application written in Java are:
• Java Servlets
• Java Server Pages(JSP) , and HTML
Java Servlets are also java programs, which run on the Server and then send the
result/ response to the client. JSP pages can be thought of as a combination of HTML
and Java Code. The Web Server converts JSP pages into Java Servlets before
execution.
You access the web application by specifying the URL. If the URL corresponds to an
HTML page the web server simply returns the HTML page to the client, which then
displays it. If the URL corresponds to the servlet or JSP then it is executed on the
Server and the result/response is returned to the client, which is then displayed by the
client.
Distributed Application
Java application can be divide into a number of modules/components (Java
programs),which can run on different machines. The java programs/applications
running on different machines can communicate with each other. To be more precise
the Java objects on one machine can invoke methods on the Java objects running on
another machine. Thus has the support for the distributed processing in the language
itself.
Introduction to Web-Applications
A web application is noting but a web-site. A web application can be thought of as a
collection of two types of resources:
• Static Resources
• Dynamic Resource
Web applications are deployed on the web servers (web- containers) and are
normally accessed through the web Clients, which is normally a web browser.
The communication between web client and web server takes place through
HTTP protocol.
Uses the
Mapping
Information
Servlet/JSP
J2EE Web
Container WebInstances
Application
Http
Web Request
Web Static
Browser Resources
Http Browser
Response
Static
Resources
Static Resources :-
These are normally non-executable resources. In some cases static resources may
also be the executable resources but they do not execute on the server.
A typical application might have following types of static resources:
• HTML
• Images, Audio and Video files
• Applets
• Documents
• Spreadsheets
• Text Files
A web client can take ask for any static resource by just specifying the URL. Web
server simply returns the specified resource to the client without any processing.
The client decides what to do with the static resource. The most common static
resource is the HTML page. The web browser parses the HTML page and
displays in the browser window. For other type of static resources the action taken
may differ from browser to browser. The browser either displays the contents of
the resource on its own or with the help of software corresponding to the static
resource. For example, Internet Explorer may open a .doc file using MS-word
software. The browser prompts for saving the contents in case it is not able to
display/process the contents.
Dynamic Resources:-
These are executable resources. A web application can have following types of
dynamic resources:
• Servlets
• Java server page
The dynamic resources are also accessed by directly or indirectly specifying the
URL. But the action taken by web server is different in case of dynamic
resources. The dynamic sources are Java programs. The server executes the
appropriate component and then returns the result to the client normally as HTML
using HTTP protocol.
Servlet:-
Java servlets are small, platform independent server side programs that
programmatically extend the functionality of the web server. The java servlet API
provides a simple framework for building application on such web servers.
As an application – level protocol, HTTP defines the types of request that the clients can
send to serves and the type of response that the servers can send to clients.
The Get Request is the simplest & the most frequently used request method for accessing
static resources such as HTML documents, image etc. The GET method is used when the
resource is accessed by specifying the URL in the web browser or by clicking on a
hyperlink.
Get request can also be used to retrieve dynamic information by using additional query
parameters in the request URL of a dynamic resource.
http://www.domain.com?name=matrix
Normally we send data using Post method through form by specifying “POST” as the
method.
The data is transmitted as part of the body. So it is possible to send the large amount of
data when using the Post request.
With get request, the request parameters are transmitted as a query string appended to the
request URL. In the case of post request parameters are transmitted within the body of the
request.
• Firstly since a Get request contains the complete request info appended to the
URL itself, it allows browser to bookmark the page & revisit later. Depending on
the type & how sensitive the request parameters are this may or may not be
desirable.
• Secondly some servers might pose restrictions on the length of request URL. This
limits the amount of info that can be appended to the request URL.
Note: The HTTP/1.1 does not impose any upper limit on the length.However server /
clients complying only with HTTP/1.0 may not support unreasonably long length.
For building and running web applications, the J2EE provides the following to meet
each of the above requirements:
The design and development processes in web applications are clearly separated from
those of deployment and packing.
The concept of web application was introduced in version 2.2 of the Java Servlet
specification. A web application is organized with a hierarchy of directories, with
particular types of files stored in particular directories.
These directories can then be packaged into a Web Application Archive (WAR) file.
2. Directory Structure
1. A directory WEB-INF that contains the resources, which are not to be directly
downloaded to a client. The Directory is private- the client does not have direct
access to the files in this directory.
Client browsers can download these resources unchanged and render them as required.
For example, when an HTML page include an <APPLET> tag that refers to an applet in a
jar file, the web container delivers that JAR file to the client browser unchanged.
Typically, the container reads the static resources from the file system, and writes the
contents directly to the network connection. The interpretation of the contents of these
resources is the responsibility of the client browser. In order to help the browser render
the file correctly, the container sends the MIME type of the file. These MIME types can
be set in the deployment descriptor of the web application.
Note:- Although JSP pages are included as public resources in a web application; the
container does not show them directly to clients. The Container automatically converts
JSP Pages into Servlets. The Sevlet is then complied and invoked to generate the
response for the client. However, since a JSP Page is often considered more near to an
HTML document than to a java class, JSP Pages are also included under public resources.
2.2 Private Resources
Of course, there are certain resources that clients should not load directly. There may be
files that the client should not view, such as configuration files or they may be files that
the container must perform some processing on before sending the response to the client,
like servlets. These private resources are stored in the WEB-INF directory, or its
subdirectories.
The types of resources that clients should not download directly include:
• Servelts- These components include application logic, and possibly
access to other resources such as databases.
• Any other files in the web application that servlets access directly.
• Resources that are meant for execution or use on the server side, such
as java class files and JAR files for classes used by your servlets.
These resources are private and as such are accessible only to their own web application
and the container. In order to accommodate private resources the web container requires
the WEB-INF directory to be present in your application. If your web application does
not contain this directory it will not work.
• The WEB-INF directory includes:
• When a new application is added to the J2EE server, we can simply add
the appropriate context root in the deploy tool of the reference
implementation, without disturbing any other application.
• The Container knows where to look for classes. This means that you do
not need to explicitly add these classes and JAR files to the
CLASSPATH.
Thus, even if you deployed the same web application twice (each mapping to a different
URL), as for as container is concerned they are two entirely different applications. Such
applications cannot share information. As a result, web containers create a virtual
partitioning of web applications within the container.
3.0 Deploying Web Application
A web application can be deployed simply by creating the directory structure and putting
the files/resources in the appropriate folders as discussed in the previous section. We can
also deploy the application using a WAR file, which is described in the next section.
The folder structure is independent of the web-server (and web-container). But the folder
under which the structure is to be created may differ from server to server. For example,
the structure must be created in the webapps folder if you are using Tomcat as the server.
4.0 Web archive Files
The various directories and files that make up a web application can be packaged into a
web application archive (WAR) file. The process is similar to the packaging of java class
files into JAR files. The purpose of the packaging is the same; it is to provide a simplified
way to distribute Java Class files and their related resources. WAR files can be created
using the same jar tool that is used to create JAR files. The Web application can be
deployed as a War files, rather than the unpackaged collection of directories and files.
Example: jar –cf greet.war*
This command packs all the contents under the current directory, including subdirectories
into an archive file called greet.war.
-c option is used for creating a new archive.
-f option is used to specify the target archive file name.
If the verbose option is specified using –v, the names of the files and directories included
in the archive will be output to the screen.
You can use the following command to view the contents of a WAR file:
Jar -tvf greet.war
Note:- Instead of including all the contents, you may select individual files and
subdirectories while creating WAR files. You can also use a standard ZIP file
manipulation tool such as WinZip to create and manipulate WAR files. Note that jar-tool
automatically create the META-INF sub-directory and its contents.
4.1 Deploying a WAR file
Any Servlet 2.2 or higher compliant server will automatically deploy and application
packaged as WAR file, as long as the location of a WAR file is explicitly stated or war
file is copied into appropriate folder..
When should WAR files be used
• Should be used when deploying the final application.
• During development try to use auto reload feature for java classes.
2. Make sure that you have J2SE 5.0 (JDK1.5) installed on your machine. If
the JDK is installed in folder C:\jdk1.5 then the environment variable
JAVA_HOME should be set to C:\JDK1.5 although it is not must.
3. Double-click on the setup file to install the tomcat. The installer will
guide you through the entire installation process.
5. 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. Specifying password is must. You should remember the
password as only the authorized user can access tomcat
administration site.
6. The installer then asks for the path of J2SE 5.0 JRE installed on the
machine. By default path C:\Program Files\Java\jre1.5.0_04 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 installing JRE
otherwise give the path where you have installed the JRE.
7. Finally click on the install button. After this installation process will
take few seconds to complete.
Note: If the tomcat fails to start after successful installation then make sure that
JAVA_HOME is set properly and the CATALINA_HOME is set to the folder where
you have installed Tomcat i.e. C:\Tomcat5.5 as described above.
5.2 Tomcat Folders w.r.t CATALINA_HOME
1. bin – executable (tomcat5.exe to start the Tomcat)
2. common – har files visible to web applications as well as internal tomcat code.
3. conf – server level configuration.
Server.xml – for configuration tomcat server
Web.xml – contains default configuration for all the web applications.
Application specific resources should not be configured here.
Example: <welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file-list>
4. logs – log files
5. server- server web applications, admin (Server administration),
Manager(deployment)
6. shared- classes visible to all the web applications, but not to internal tomcat code.
7. temp – temporary files
8. webapps – user web applications, tomcat example applications.
9. work – session information, jsp compilation.
6. Web Application : Development to Deployment with Example
Example1 : Greeting Application (index.html, web.xml, GreetingServlet.java)
************************
********index.html************************************
1 <html>
2 <head>
3 <title> ProJava Registration.. </title>
4 </head>
5 <body>
6 <h1>Welcome</h1>\
7 <form action =”GreetingServlet” method =”POST”>
8 <p> Your Name <input type =”text” size =”40” name=”name” /></p>
9 <p> Your Email <input type =”text” size =”40” name=”email” /></p>
10 <input type = “submit” VALUE =”submit”/> </p>
11 </form>
12 </body>
13 </html>
chapter 6
The notion of a session provides this abstraction. In simple term, a session lets you group requests into a collected
group. In addition, session management also involves associating data with each session. The servlet API specifies the
javax.servlet.HttpSession interface to provide this abstraction.
Servlet context
The notion of servlet context is closely associated with the notion of a web application. The interface
javax.servlet.ServletContext allows servlets in an application to share data. It also provides the methods with which
servlets can access the host web container. Using the ServletContext object, a servlet can log events, obtain URL
refrences to resources and set and store attributes that other servlets in the context can access.
Servlet collaboration
The servlet API also provides an interface javax.servlet.Request Dispatcher with which a servlet can invoke another
servlet, a JSP, or even a static resource such as an HTML page. This mechanism helps you to control flow of logic
across multiple servlets and JSP pages programmatically.
Filtering
The servlet API has a mechanism with which we can introduce code (called a filter) to participate in the containers
request / response process. Filters are a new feature of the Java Servlet API version 2.3. They do not generally create
requests/responses; rather, they modify or adapt requests and responses to and from a web resource, which could have
static or dynamic content.
Cookie
When you write a servlet, you must implement this interface directly or indirectly. You will most likely always
implement the interface indirectly by extending either the javax.servlet.GenericServlet or javax.servlet.httpServlet
classes. When implementing the javax.servlet.Servlet interface, the following five methods must be implemented:
The init ( ) method throws a ServletExpection in the event that it does not complete normally.
The Servlet specification guarantees that the init( ) method will be called exactly once on any given instance of the
servlet, and the init( ) method will be allowed to complete (provide that it does not throw a ServletException) before
any requests are passed to the Servlet. Some of the typical tasks that can be implemented in the init ( ) methods are:
• Read configuration data from persistent resources such as configuration files.
• Read initialization parameters using the ServletConfig object.
• Initialization one-time activities such as registering a database driver, a Connection Pool, or a Logging
service.
ThegetServletConfig ( ) Method
The init (ServletConfig config) method stores the ServletConfig object in a private transient instance variable (called
config). You can use the getServletConfig ( ) method to access this object. However, if you choose to override this
method, you should include a call to super. Init (config).
Alternatively, you can override the overloaded no-argument init ( ) method in the GenericServlet class.
The GenericServlet class also implements the ServletConfig interface. This allows the servlet developer to call the
ServletConfig methods directly without having to first obtain a ServletConfig object. These method are:-
• getInitParameter( )
• getInitParameterNames( )
• getServletContext(), and
• getServletName( )
Each of these methods delegates the calls to the respective methods in the stored ServletConfig object.
The GenericServlet class also includes two methods for writing to a servlet log, which call the corresponding methods
on the ServletContext.
The first method, log (String msg), writes the name of the servlet and the msg argument to the web container’s log. The
other method log (String msg, Throwable cause), includes a stack trace for the given Throwable exception in addition
to the servlet name and message. The actual implementation of the logging mechanism is container-specific, although
most of the containers use text files for logging purposes.
The javax.servlet.ServletRequest interface provides a getMethod ( ) method that returns the type of the HTTP
method associated with the request. For instance, for GET request, this method returns”GET” as a string. The
service ( ) method uses this string to delegate the request to one of the methods do XXX ( ). The
javax.servlet.http. HttpServlet provides default implementation of all these methods.
In general, you should avoid overriding this method as it affects the default behavior of the service ( ) method.
The only situation that requires you to override it is when you want to change the default behavior, or when you
want to include additional processing common to doXXX ( ) methods.
The sequence of method calls when the container receives a request for a servlet is :
1. The container calls the public service ( ) method.
2. The public service ( ) method calls the protected service ( ) method after casting the
arguments to HTTPServletRequest and HttpServletResponse respectively.
3. Protected service ( ) method calls one of the doXXX ( ) methods, depending on the type
of the HTTP request method.
However, what is the alternative if the service ( ) method of a servlet is not thread safe?
The java Servlet API specifies the SingleThreadModel interface for this purpose. Servlets can implement the
SingleThreadModel interface ( in addition to implementating he javax.servlet.Servlet interface or extending one of its
implementation classes) in order to inform the container that it should make sure that only one thread is executing the
servlet’s service( ) method at any given moment.
For SingleThreadModel servlets, Containers may follow one of the following approaches to ensure that each servlet
instance is invoked in a separate thread:
Note that the Single ThreadModel is resource intensive, particularly if a large no. of concurrent requests is
expected for the servlet. The effect of the SingleThreadModel is that the container invokes the service ( )
method in a synchronized block. This is equivalent to using the synchronized keyword for the servlet’s
service ( ) method. Accordingly, when there are hundreds or even thousands of concurrent requests to the
web container, the container may either serilize requests to the same instance of the servlet, or create that
many hampered due to serialization. In the later case, the container encounters more object allocation (which
includes more object creation overhead and memory usage).
However, in cases where only a few statements of the service ( ) method are not thread safe, you should
consider reducing the scope of synchronization of the service ( ) method are not thread safe, you should
consider reducing the scope of synchronization, and explicitly synchronize such blocks using the
synchronized keyword. Depending on how short such synchronization blocks are, this approach could
improve performance.
Note: - We should always consider redesigning our applications in order to avoid the SingleThreadModel or
thread synchronization. If we cannot avoid them, it is important to be aware of the performance implications.
With any thread synchronization code, you are potentially blocking a web container thread
<web-app>
<servlet>
<servlet-name>Admin</servlet-name>
<servlet-class>com.wrox.admin.AdminServlet</servlet-class>
<init-param>
<param-name>driverClass</param-name>
< param-value>oracle.jdbc.driver.OracleDriver</param-value>
</init-param>
<init-param>
<param-name>jdbcURL</param-name>
<param-value>jdbc:oracle:thin:@everesr:1521:orcl</param-value>
</init-param>
</servlet>
</web-app>
However, when you are overriding the init( ) method in the GenericServlet class, you should explicity
invoke super.init( ) as follows:
The call to super.init (config) ensures that the GreetongServlet class actually maintains a refrence to the
ServletConfig object. The implementation of the GenericServlet class actually maintains a refrence to the
ServletConfig object (as a private transient instance variable), and requires that super.init( ) be called in
subclass.
The servlet can throw any of these exceptions to the container to indicate that due to some exceptions, servlet can not
continue its execution. The container will according mark that the servlet is either permanently or temporarily
unavailable.
5.1 javax.servlet.ServletException
Defines a general exception a servlet can throw when it encounters difficulty. The container sends the HTPP-500 error
to the client.
Constructors
• Public ServletException ( )
Construct a new Servlet Exception
• Public ServletException (String msg)
Constructs a new servlet exception when the servlet needs to throw an exception and includes a parameter
corresponding to the “root cause” exception that interfered with its normal operation, and a desription
message.
• ServletException (Throwable rootcause)
Constructs a new servlet exception when the servlet needs to throw an exception and includes a parameter
corresponding to the “root cause” exception that interfered with its normal operation.
5.2 javax,servlet.UnavailableException
Defines an exception that a servlet or filter throws to indicate that it is permanently or temporarily unavailable.
A servlet or filter is temporatily unavailable if it cannot handle request momentarily due to some system wide problem.
For example, a third-tier server might not be accessible or there may be insufficient memory or disk storage to handle
requests . A system administrator may need to take corrective action.
A servlet or filter is permanently unavailable if during its execution an exception occurs which can not be recovered.
Servlet containers can safely treat both types of unavailablr\e exceptions in the same way. However, treating temporary
unavailable effectively makes the servlet container more robust. Specifically, the servlet container might block requests
to the servlet or filter for a period of time suggested by the exception rather than rejecting them until the servlet
container restats.
Constructors
• UnavailableException (String msg)
Constructs a new exception with a description message indicating that the servlet is permanently unavailable.
The container sends the HTTP-404 error to the client.
The Servlet interface methods relevant to the servlet lifecycle are init( ) , service ( ), and destroy ( ). The lifecycle
starts with the container calling the init( ) method, and ends with the container calling the destroy method.
2. Initialization
The Container calls the instance’s init( ) method.
3. Service
If the Container has a request for the servlet it calls the servlet instance’s service( ) method.
4. Destroy
Before destroying the instance, the container calls the servlet instance’s destroy ( ) method. After this
servlet instance is garbage collected.
5. Unavailable
The instance is marked as unavailable. The unavailable may be temporary or permanent.
Chapter-7
Request and Response API
1. Introduction
The javax.servlet.HttpServletRequest and javax.servlet.HttpServletResponse interfaces are the classes that servlets
depend on for accessing HTTP requests and responses. The important classes/interfaces in this category are:
o Javax.servlet.ServletRequest
o Javax.servlet.ServletResponse
o Javax.servlet.http.HttpServletRequest
o Javax.servlet.http.HttpServletResponse
The following methods can be used to access the request parameters. In the case of HTTP request, these methods
can be used for both GET and POST requests.
The JSP specification provides an additional mechanism using page context to store and retrieve attributes. Each of
these approaches provides the notion of a scope for the attributes to exit: In the case of attributes attached to the request
objects, the lifetime of these attributes is that of the request itself.
In the servlet parlance, an attribute is a named Java language object. While setting an attribute, you assign a name to the
attribute, and while retrieving the attribute, specify the same name. Names are String objects. The purpose of attributes
in the request scope is to allow the container or another servlet to send additional data to a servlet or JSP. For the
application developers, this is useful when using the Request Dispatcher object to forward request from one servlet to
another. The following methods can be used to manage attributes in the request context.
Multiple controls can have the same name. The most common reason for having multiple
controls with the same name is to be able to build sets of radio buttons and check boxes, and
multiple-selection select controls. The radio button set will return the single selected value, and
checkboxes or multiple selection select controls will return all of selected values.
This method clears content of the underlying buffer without clearing the response headers or the
status code. If the response has already been committed, then method throws an Illegal State
Exception.
o Public void FlushBuffer ( )
o Public Boolean is Committed ( )
o Public void reset ( )
This method clears content of the underlying buffer as well as the response headers.
Chapter-8
Session Handling
1. Introduction
A servlet receives a request object, extracts parameters (if any) from it, processes any application logic (which may
depend on the request parameters), and finally generates the perponse. Extending this model, you could build larger
web applications by having several servlets, with each servlet performing a well-defined independent task.
The model is adequate so long as the application logic in each of these servlets is atomic-that is, so long as the
application logic depends only on the parameters in the request (and, if applicable, any persistent data such as data
stores in a relational database). For instance, in the TechSupport application the servlet gets all the support request data
from the request, and as part of the application logic, writes the request data to a database, and sends a confirmation
back.
This is a typical requirement for web application where a ‘user activity’ happens across multiple requests and
responses, and the server is required to associate some form of uniqueness to each of the users.
A protocol is stateful is response to a given request may depend not only on the current request, but also on
the outcome of previous requests.
But why is it important to be stateful? A stateful protocol helps you develop complex application logic across multiple
requests and responses. Let’s consider an online bank. When you request a page containing balances of all your
accounts, the server should be able to verify that you are a genuine account holder, and that you have established your
credentials with every request-In fact, each business transaction will be required to occur in a single request. This is not
suitable for long business transaction that ought to happen across multiple requests, such as the online bank, or
shopping cart.
For implementing flexible business transaction across multiple requests and responses, we need two facilities.
• Session:
The server should be able to identify that a series of requests are from a single client and responses, we need
single working session.
• State:
The server should be able able to remember information related to previous requests and other business
decisions that are made for requests. That is, the shopping cart application, possible state could include the
user’s favorite item categories, user profile, or even the shopping cart itself.
However, in the case of HTTP, connections are closed at the end request, and hence HTTP servers cannot use the
notion of connections to establish a session. HTTP is a stateless protocol, concerned with requests and responses, which
are simple isolated transactions. This is perfect for simple web browsing, where each request typically results in
downloading static pages. The server does not need to know whether a series of requests come from the same, or from
different clients, or whether those
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 API 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 CGI 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 Container
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(like .html
etc).server container is responsible for maintaining lifecycle of the Servlet
Inexpensive
There are number of free web servers 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.
1. Platform Independence
Servlets 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 server (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. But 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 memory 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. Extensibility
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.
The list below highlights 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 at 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 bother 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 the capability to generate dynamic and user-
based content (e.g. displaying transaction information of credit card or
debit card depending on user’s choice).
Servlet Servlet
Container
Http Request
Browser HTTP
Server
Http Response
Static
Contents
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Tomcat Installation
The installation process is described for tomacat 6.0:
1. Before installing tomcat 5.5 make sure that you have installed JDK1.6 on your
machine. The environment variable JAVA_HOME 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 for 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 installing 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.
star (folder)
index.html(welcome file)
WEB-INF(folder)
classes(folder)
HelloWorld.class
lib(folder)
web.xml(file- deployment descriptor)
Step3:- Compile the java file and put your class 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
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 <servlet-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.
import javax.servlet.*;
import javax.servlet.http.*;
res.setContentType("text/html");
out.println("<html><head>");
out.println("<title>TestServlet</title>");
out.println("</head>");
out.println("<body>");
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 when 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() method, we send our own HTML
content to the client browser. Once we are finished, we call its close() method.
Output:-
Index.html
<html>
<head> <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>
<input 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/javaee
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-name>
<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 void 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.get(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();
}
• 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 ServletException if
an exception has occurred.
service()
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 and IOExceptions exception.
getServletConfig()
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 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 / 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.
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. After 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() must 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 available 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 threads 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
client 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 with the resources for
garbage collection.
Life Cycle of a Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Servlet_LifeCycle extends HttpServlet{
int i;
}
public void destroy()
{
i=0;
Output:-
First time output will be given as above . To appreciate the 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 F5 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 javax.servlet.*;
import javax.servlet.http.*;
Servlets are basically developed for server 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 other 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 all 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 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.
Filtering Javax.servlet.Filter(Interface)
Javax.servlet.FilterChain(Interface)
Javax.servlet..FilterConfig(Interface)
Cookies Javax.servlet..http.Cookie(Interface)
Web servers with java servlet implementation. 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( javax.servlet.Filter) that are left for you to implement when building web
applications.
1.1 Servlets
Servlets are Java technology’s answer to Common Gateway Interface (CGI)
programming. They are programs that run on a Web server, acting as a
middle
layer between a request coming from a Web browser or other HTTP client
and databases or applications on the HTTP server. Their job is to:
1. Read any data sent by the user.
This data is usually entered in a form on a Web page, but could
also come from a Java applet or a custom HTTP client program.
2. Look up any other information about the request that is
embedded in the HTTP request.
This information includes details about browser capabilities,
cookies, the host name of the requesting client, and so forth.
T
6 Chapter 1 Overview of Servlets and JavaServer Pages
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book’s author: courses.coreservlets.com.
© Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
3. Generate the results.
This process may require talking to a database, executing an
RMI or CORBA call, invoking a legacy application, or computing
the response directly.
4. Format the results inside a document.
In most cases, this involves embedding the information inside
an HTML page.
5. Set the appropriate HTTP response parameters.
This means telling the browser what type of document is being
returned (e.g., HTML), setting cookies and caching parameters,
and other such tasks.
6. Send the document back to the client.
This document may be sent in text format (HTML), binary format
(GIF images), or even in a compressed format like gzip that
is layered on top of some other underlying format.
Many client requests can be satisfied by returning pre-built documents,
and these requests would be handled by the server without invoking servlets.
In many cases, however, a static result is not sufficient, and a page needs to
be generated for each request. There are a number of reasons why Web
pages need to be built on-the-fly like this:
• The Web page is based on data submitted by the user.
For instance, the results page from search engines and
order-confirmation pages at on-line stores are specific to
particular user requests.
• The Web page is derived from data that changes
frequently.
For example, a weather report or news headlines page might
build the page dynamically, perhaps returning a previously built
page if it is still up to date.
• The Web page uses information from corporate
databases or other server-side sources.
For example, an e-commerce site could use a servlet to build a
Web page that lists the current price and availability of each
item that is for sale.
In principle, servlets are not restricted to Web or application servers that
handle HTTP requests, but can be used for other types of servers as well. For
1.2 The Advantages of Servlets Over “Traditional” CGI 7
© Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book’s author: courses.coreservlets.com.
example, servlets could be embedded in mail or FTP servers to extend their
functionality. In practice, however, this use of servlets has not caught on, and
I’ll only be discussing HTTP servlets.
1.2 The Advantages of Servlets
Over “Traditional” CGI
Java servlets are more efficient, easier to use, more powerful, more portable,
safer, and cheaper than traditional CGI and many alternative CGI-like
technologies.
Efficient
With traditional CGI, a new process is started for each HTTP request. If the
CGI program itself is relatively short, the overhead of starting the process can
dominate the execution time. With servlets, the Java Virtual Machine stays
running and handles each request using a lightweight Java thread, not a
heavyweight operating system process. Similarly, in traditional CGI, if there
are N simultaneous requests to the same CGI program, the code for the CGI
program is loaded into memory N times. With servlets, however, there would
be N threads but only a single copy of the servlet class. Finally, when a CGI
program finishes handling a request, the program terminates. This makes it
difficult to cache computations, keep database connections open, and
perform
other optimizations that rely on persistent data. Servlets, however,
remain in memory even after they complete a response, so it is
straightforward
to store arbitrarily complex data between requests.
Convenient
Servlets have an extensive infrastructure for automatically parsing and
decoding
HTML form data, reading and setting HTTP headers, handling cookies,
tracking sessions, and many other such high-level utilities. Besides, you
already
know the Java programming language. Why learn Perl too? You’re already
convinced
that Java technology makes for more reliable and reusable code than
does C++. Why go back to C++ for server-side programming?
8 Chapter 1 Overview of Servlets and JavaServer Pages
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book’s author: courses.coreservlets.com.
© Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
Powerful
Servlets support several capabilities that are difficult or impossible to
accomplish
with regular CGI. Servlets can talk directly to the Web server, whereas
regular CGI programs cannot, at least not without using a server-specific
API. Communicating with the Web server makes it easier to translate relative
URLs into concrete path names, for instance. Multiple servlets can also share
data, making it easy to implement database connection pooling and similar
resource-sharing optimizations. Servlets can also maintain information from
request to request, simplifying techniques like session tracking and caching
of previous computations.
Portable
Servlets are written in the Java programming language and follow a standard
API. Consequently, servlets written for, say, I-Planet Enterprise Server can
run virtually unchanged on Apache, Microsoft Internet Information Server
(IIS), IBM WebSphere, or StarNine WebStar. For example, virtually all of
the servlets and JSP pages in this book were executed on Sun’s Java Web
Server, Apache Tomcat and Sun’s JavaServer Web Development Kit
(JSWDK) with no changes whatsoever in the code. Many were tested on
BEA WebLogic and IBM WebSphere as well. In fact, servlets are supported
directly or by a plug-in on virtually every major Web server. They are now
part of the Java 2 Platform, Enterprise Edition (J2EE; see
http://java.sun.com/j2ee/), so industry support for servlets is becoming
even more pervasive.
Secure
One of the main sources of vulnerabilities in traditional CGI programs
stems from the fact that they are often executed by general-purpose
operating
system shells. So the CGI programmer has to be very careful to filter
out characters such as backquotes and semicolons that are treated specially
by the shell. This is harder than one might think, and weaknesses stemming
from this problem are constantly being uncovered in widely used CGI
libraries. A second source of problems is the fact that some CGI programs
are processed by languages that do not automatically check array or string
bounds. For example, in C and C++ it is perfectly legal to allocate a
1.3 JavaServer Pages 9
© Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book’s author: courses.coreservlets.com.
100-element array then write into the 999th “element,” which is really some
random part of program memory. So programmers who forget to do this
check themselves open their system up to deliberate or accidental buffer
overflow attacks. Servlets suffer from neither of these problems. Even if a
servlet executes a remote system call to invoke a program on the local
operating
system, it does not use a shell to do so. And of course array bounds
checking and other memory protection features are a central part of the
Java programming language.
Inexpensive
There are a number of free or very inexpensive Web servers available that
are
good for “personal” use or low-volume Web sites. However, with the major
exception of Apache, which is free, most commercial-quality Web servers are
relatively expensive. Nevertheless, once you have a Web server, no matter
its
cost, adding servlet support to it (if it doesn’t come preconfigured to support
servlets) costs very little extra. This is in contrast to many of the other CGI
alternatives, which require a significant initial investment to purchase a
proprietary
package.