You are on page 1of 61

Unit – 2 CS-25 - Advance Java Programming (J2ee)

 RMI overview

 RMI stands for “Remote Method Invocation”


 RMI is a framework for developing Java centric distributed applications
 Using the RMI infrastructure and packages, RMI based Java clients can remotely invoke
methods on RMI based Java server objects. These RMI based server objects can be
running in separate JVM’s either on the same machine or on another host

 RMI architecture

RMI stands for Remote Method Invocation. It is a mechanism that allows


an object residing in one system (JVM) to access/invoke an object running
on another JVM.

RMI is used to build distributed applications; it provides remote


communication between Java programs. It is provided in the
package java.rmi.

In an RMI application, we write two programs, a server program (resides


on the server) and a client program (resides on the client).

 Inside the server program, a remote object is created and reference of that
object is made available for the client (using the registry).

 The client program requests the remote objects on the server and tries to invoke
its methods.

The following diagram shows the RMI Architecture:

Understanding stub and skeleton

RMI uses stub and skeleton object for communication with the remote object.

A remote object is an object whose method can be invoked from another JVM. Let's understand
the stub and skeleton objects:

stub

The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed
through it. It resides at the client side and represents the remote object. When the caller invokes
method on the stub object, it does the following tasks:
Unit – 2 CS-25 - Advance Java Programming (J2ee)
1. It initiates a connection with remote Virtual Machine (JVM),
2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.

skeleton

The skeleton is an object, acts as a gateway for the server side object. All the incoming requests
are routed through it. When the skeleton receives the incoming request, it does the following
tasks:

1. It reads the parameter for the remote method


2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.
Unit – 2 CS-25 - Advance Java Programming (J2ee)

Let us now discuss the components of this architecture.

 Transport Layer − This layer connects the client and the server. It manages
the existing connection and also sets up new connections.

 RRL(Remote Reference Layer) − It is the layer which manages the


references made by the client to the remote object.

Class Naming
 java.lang.Object
 java.rmi.Naming

public final class Naming


extends Object

The Naming class provides methods for storing and obtaining references to remote objects in a remote object
registry. Each method of the Naming class takes as one of its arguments a name that is a java.lang
Unit – 2 CS-25 - Advance Java Programming (J2ee)

lookup
public static Remote lookup(String name)
throws NotBoundException,
MalformedURLException,
RemoteException
Returns a reference, a stub, for the remote object associated with the specified name. It is basically looking for an
object in the server object pool registered with a name //localhost/Hello

Parameters:

name - a name in URL format (without the scheme component)

Returns:
a reference for a remote object

Throws:

NotBoundException - if name is not currently bound

RemoteException - if registry could not be contacted


AccessException - if this operation is not permitted
MalformedURLException - if the name is not an appropriately formatted URL

rebind
public static void rebind(String name,
Remote obj)
throws RemoteException,
MalformedURLException
Rebinds the specified name to a new remote object. Any existing binding for the name is replaced. The rebind
method always binds the name to the object even if the name is already bound. The old binding is lost.

Parameters:

name - a name in URL format (without the scheme component)


obj - new remote object to associate with the name
Throws:

MalformedURLException - if the name is not an appropriately formatted URL

RemoteException - if registry could not be contacted


AccessException - if this operation is not permitted (if originating from a non-local host, for example)
Unit – 2 CS-25 - Advance Java Programming (J2ee)

public class UnicastRemoteObject

extends RemoteServer

The UnicastRemoteObject class defines a non-replicated remote object whose


references are valid only while the server process is alive. The UnicastRemoteObject
class provides support for point-to-point active object references (invocations,
parameters, and results) using TCP streams.

 Developing and Executing RMI application

1. Steps for developing RMI applications are as follows:


Create the remote interface

2. Provide the implementation of the remote interface

3. Compile the implementation class and create the stub and skeleton objects using the
rmic tool
4. Start the registry service by rmiregistry tool

5. Create and start the remote application

6. Create and start the client application

1. Defining the Remote Interface


An interface manifests the exposed operations and the client programmer need not be aware of the
implementation (the interface in this case also serves as a marker to the JVM). A remote Interface by
definition is the set of methods that can be invoked remotely by a client:

• The remote interface must be declared public or the client will get an error when it tries to load a
remote object that implements the remote interface.
• The remote interface must extend the java.rmi.Remote interface.
• Each method must throw a java.rmi.RemoteException (or a superclass of RemoteException)
• If the remote methods have any remote objects as parameters or return types, they must be interface
types not the implementation classes.

Note: java.rmi.Remote interface has no methods. It is just a marker interface.


Example: The example discussed in the following sections illustrates how to define and invoke methods
on a remote object. We will define our Remote Interface (HelloInterface.java) as follows:
Unit – 2 CS-25 - Advance Java Programming (J2ee)

2. Implementing the Remote Interface

The implementing class is the actual class that provides the implementation for methods defined in the
remote interface. The java.rmi.server.RemoteObject extends the functionality provided by the
java.lang.Object class into the remote domain by overriding the equals(), hashcode() and toString()
methods. The generic java.rmi.server.RemoteObject is an abstract class and describes the behavior of
remote objects.

The abstract subclass java.rmi.server.RemoteServer describes the behavior associated with the server
implementation and provides the basic semantics to support remote references.

java.rmi.RemoteServer has two concrete sub-classes

• java.rmi.server.UnicastRemoteObject
It designs a non-replicated remote object whose reference is valid only when the server is alive.
• java.rmi.activation.Activatable
It is the concrete class that defines behavior for on demand instantiation of remote objects.

In addition to one of the above classes, the class corresponding to the remote interface must implement
one or more interfaces that define the remote methods. A remote class can define any methods but
only methods in the remote interface can be invoked remotely.
Unit – 2 CS-25 - Advance Java Programming (J2ee)

3. Registering the Remote Object


Now that we have the interface and the implementation, we need to make this object available to
clients by binding it to a registry. This will allow the clients to look the object up on the host by a String
name. The stubs and skeletons (if any) are needed for registration. After all it is the object stub that is
going to be passed around from the registry to the clients.
Unit – 2 CS-25 - Advance Java Programming (J2ee)

4. Writing the Client that uses the Remote Object


The client performs a lookup on the registry on the host and obtains a reference to the remote object.
Note that casting to the remote object is critical. In RMI, clients always interact with the interface, never
with the object implementation.
Unit – 2 CS-25 - Advance Java Programming (J2ee)

5. Generating Stubs and Skeletons


Now that we have the remote interface and implementation, we can generate the skeletons and stubs
(or only stubs in java 1.2 or higher version) with the rmic tool after we have compiled the classes.
Remember to set the directory that you are working from in your classpath; you can then use the
following line in a command window:

rmic -v1.2 HelloServer

This will generate stub class “HelloServer_Stub.class”.


Unit – 2 CS-25 - Advance Java Programming (J2ee)

Note: It is worth keeping in mind that while starting the registry all classes and stubs must be available
in the classpath or the classpath should not be set at all, to support dynamic loading.

6. Running the RMI Registry, Client and the Server


The steps for running the RMI application are:

1. Start RMI Registry: Ensure that the following classes are present in the current folder or the
classpath:
• HelloInterface.class
• HelloServer_Stub.class

Start the RMI Registry by giving the command:


rmiregistry

2. Start Server: Ensure that the following classes are in the current folder or the classpath:
• HelloInterface.class
• HelloServer.class
• HelloServer_Stub.class
• MyRMI.class

Run the MyRMI program.


D:sumit miin>java -Djava.rmi.server.codebase="file:///d:/sumit/rmi/bin/" org
.test.MyRMI

3. Run Client: Ensure that the following classes are in the current folder or the classpath:
• HelloInterface.class
• HelloServer_Stub.class
• HelloClient.class

Run the HelloClient program :)


Unit – 2 CS-25 - Advance Java Programming (J2ee)

 Architecture of a Servlet
Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a requests coming from a Web browser or other HTTP client and databases or
applications on the HTTP server.

Using Servlets, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.

Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.

 Performance is significantly better.


 Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.
 Servlets are platform-independent because they are written in Java.
 Java security manager on the server enforces a set of restrictions to protect the resources
on a server machine. So servlets are trusted.
 The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already.

Servlets Architecture
The following diagram shows the position of Servlets in a Web Application.
Unit – 2 CS-25 - Advance Java Programming (J2ee)

Servlets Tasks
Servlets perform the following major tasks −

 Read the explicit data sent by the clients (browsers). This includes an HTML form on a
Web page or it could also come from an applet or a custom HTTP client program.
 Process the data and generate the results. This process may require talking to a database,
executing an RMI , invoking a Web service, or computing the response directly.
 Send the explicit data (i.e., the document) to the clients (browsers). This document can be
sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel,
etc.

Servlets Packages
Java Servlets are Java classes run by a web server that has an interpreter that supports the Java
Servlet specification.

Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a
standard part of the Java's enterprise edition, an expanded version of the Java class library that
supports large-scale development projects.

Java servlets have been created and compiled just like any other Java class. After you install the
servlet packages and add them to your computer's Classpath, you can compile servlets with the
JDK's Java compiler or any other current compiler.

 Servlet API

1. Servlet API
2. Interfaces in javax.servlet package
3. Classes in javax.servlet package
4. Interfaces in javax.servlet.http package
5. Classes in javax.servlet.http package

The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.

The javax.servlet package contains many interfaces and classes that are used by the servlet or
web container. These are not specific to any protocol.

The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.

Let's see what are the interfaces of javax.servlet package.


Unit – 2 CS-25 - Advance Java Programming (J2ee)
Interfaces in javax.servlet package

There are many interfaces in javax.servlet package. They are as follows:

Interface Summary
A filter is an object that performs filtering tasks on either the request
Filter to a resource (a servlet or static content), or on the response from a
resource, or both.

A FilterChain is an object provided by the servlet container to the


FilterChain developer giving a view into the invocation chain of a filtered request
for a resource.

A filter configuration object used by a servlet container to pass


FilterConfig
information to a filter during initialization.

Defines an object that receives requests from the client and sends
RequestDispatcher them to any resource (such as a servlet, HTML file, or JSP file) on the
server.

Servlet Defines methods that all servlets must implement.

A servlet configuration object used by a servlet container to pass


ServletConfig
information to a servlet during initialization.

Defines a set of methods that a servlet uses to communicate with its


ServletContext servlet container, for example, to get the MIME type of a file, dispatch
requests, or write to a log file.

Implementations of this interface receive notifications of changes to


ServletContextAttributeListener
the attribute list on the servlet context of a web application.

Implementations of this interface receive notifications about changes


ServletContextListener
to the servlet context of the web application they are part of.

ServletRequest Defines an object to provide client request information to a servlet.

A ServletRequestAttributeListener can be implemented by the


ServletRequestAttributeListener
developer interested in being notified of request attribute changes.
Unit – 2 CS-25 - Advance Java Programming (J2ee)

A ServletRequestListener can be implemented by the developer


ServletRequestListener interested in being notified of requests coming in and out of scope in
a web component.

Defines an object to assist a servlet in sending a response to the


ServletResponse
client.

SingleThreadModel Deprecated. As of Java Servlet API 2.4, with no direct replacement.

Classes in javax.servlet package


There are many classes in javax.servlet package. They are as follows:
Class Summary
GenericServlet Defines a generic, protocol-independent servlet.

This is the event class for notifications about changes to the attributes
ServletContextAttributeEvent
of the servlet context of a web application.

This is the event class for notifications about changes to the servlet
ServletContextEvent
context of a web application.

Provides an input stream for reading binary data from a client request,
ServletInputStream including an efficient readLine method for reading data one line at a
time.

ServletOutputStream Provides an output stream for sending binary data to the client.

This is the event class for notifications of changes to the attributes of


ServletRequestAttributeEvent
the servlet request in an application.

ServletRequestEvent Events of this kind indicate lifecycle events for a ServletRequest.

Provides a convenient implementation of the ServletRequest interface


ServletRequestWrapper that can be subclassed by developers wishing to adapt the request to a
Servlet.

ServletResponseWrapper Provides a convenient implementation of the ServletResponse interface


that can be subclassed by developers wishing to adapt the response
Unit – 2 CS-25 - Advance Java Programming (J2ee)

from a Servlet.

Exception Summary
ServletException Defines a general exception a servlet can throw when it encounters difficulty.

Defines an exception that a servlet or filter throws to indicate that it is


UnavailableException
permanently or temporarily unavailable.

Interfaces in javax.servlet.http package

There are many interfaces in javax.servlet.http package. They are as follows:

Interface Summary
Extends the ServletRequest interface to provide request information
HttpServletRequest
for HTTP servlets.

Extends the ServletResponse interface to provide HTTP-specific


HttpServletResponse
functionality in sending a response.

Provides a way to identify a user across more than one page request or
HttpSession
visit to a Web site and to store information about that user.

Objects that are bound to a session may listen to container events


HttpSessionActivationListener notifying them that sessions will be passivated and that session will be
activated.

This listener interface can be implemented in order to get notifications


HttpSessionAttributeListener
of changes to the attribute lists of sessions within this web application.

Causes an object to be notified when it is bound to or unbound from a


HttpSessionBindingListener
session.

Deprecated. As of Java(tm) Servlet API 2.1 for security reasons, with no


HttpSessionContext
replacement.
Unit – 2 CS-25 - Advance Java Programming (J2ee)

Implementations of this interface are notified of changes to the list of


HttpSessionListener
active sessions in a web application.

Classes in javax.servlet.http package

There are many classes in javax.servlet.http package. They are as follows:

Class Summary
Creates a cookie, a small amount of information sent by a servlet to a
Cookie
Web browser, saved by the browser, and later sent back to the server.

Provides an abstract class to be subclassed to create an HTTP servlet


HttpServlet
suitable for a Web site.

Provides a convenient implementation of the HttpServletRequest


HttpServletRequestWrapper interface that can be subclassed by developers wishing to adapt the
request to a Servlet.

Provides a convenient implementation of the HttpServletResponse


HttpServletResponseWrapper interface that can be subclassed by developers wishing to adapt the
response from a Servlet.

Events of this type are either sent to an object that implements


HttpSessionBindingListener when it is bound or unbound from a
HttpSessionBindingEvent session, or to a HttpSessionAttributeListener that has been
configured in the deployment descriptor when any attribute is bound,
unbound or replaced in a session.

This is the class representing event notifications for changes to sessions


HttpSessionEvent
within a web application.

HttpUtils Deprecated. As of Java(tm) Servlet API 2.3.


Unit – 2 CS-25 - Advance Java Programming (J2ee)

 Servlet Life Cycle

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is
in new state if servlet instance is created. After invoking the init() method, Servlet comes in the ready
state. In the ready state, servlet performs all the tasks. When the web container invokes the destroy()
method, it shifts to the end state.

 Finally, servlet is garbage collected by the garbage collector of the JVM.


Now let us discuss the life cycle methods in detail
Unit – 2 CS-25 - Advance Java Programming (J2ee)

1) Servlet class is loaded

The class loader is responsible to load the servlet class. The servlet class is loaded when the first
request for the servlet is received by the web container.

2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.

3) The init() Method


The init method is called only once. It is called only when the servlet is created, and not
called for any user requests afterwards. So, it is used for one-time initializations, just as
with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet,
but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user
request resulting in a new thread that is handed off to doGet or doPost as appropriate. The
init() method simply creates or loads some data that will be used throughout the life of the
servlet.
The init method definition looks like this:
public void init() throws ServletException {
// Initialization code...
}
4) The service() Method
The service() method is the main method to perform the actual task. The servlet container
(i.e. web server) calls the service() method to handle requests coming from the client(
browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and
calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE,
etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method:


public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{
}
The service () method is called by the container and service method invokes doGet, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service()
method but you override either doGet() or doPost() depending on what type of request you
receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request.
Unit – 2 CS-25 - Advance Java Programming (J2ee)
Here is the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
5)The destroy() Method
The destroy() method is called only once at the end of the life cycle of a servlet. This
method gives your servlet a chance to close database connections, halt background threads,
write cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The
destroy method definition looks like this:
public void destroy() {
// Finalization code...
}

Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.
First the HTTP requests coming to the server are delegated to the servlet container.

The servlet container loads the servlet before invoking the service() method.

Then the servlet container handles multiple requests by spawning multiple threads,
each thread executing the service() method of a single instance of the servlet.
Unit – 2 CS-25 - Advance Java Programming (J2ee)

 Developing and Deploying Servlets

There are given 6 steps to create a servlet example. These steps are required for all the servers.

The servlet example can be created by three ways:

1. By implementing Servlet interface,


2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost(), doHead() etc.

Here, we are going to use apache tomcat server in this example. The steps are as follows:

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet
Unit – 2 CS-25 - Advance Java Programming (J2ee)
)Create a directory structures

The directory structure defines that where to put the different types of files so that web
container may get the information and respond to the client.

The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's
see the directory structure that must be followed to create the servlet.

As you can see that the servlet class file must be in the classes folder. The web.xml file must be
under the WEB-INF folder.

2)Create a Servlet
There are three ways to create the servlet.

1. By implementing the Servlet interface


2. By inheriting the GenericServlet class
3. By inheriting the HttpServlet class

The HttpServlet class is widely used to create the servlet because it provides methods to handle http
requests such as doGet(), doPost, doHead() etc.

In this example we are going to create a servlet that extends the HttpServlet class. In this example, we
Unit – 2 CS-25 - Advance Java Programming (J2ee)

are inheriting the HttpServlet class and providing the implementation of the doGet() method. Notice
that get request is the default request.

DemoServlet.java

1. import javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class DemoServlet extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException,IOException
7. {
8. res.setContentType("text/html");//setting the content type
9. PrintWriter pw=res.getWriter();//get the stream to write the data
10.
11. //writing html in the stream
12. pw.println("<html><body>");
13. pw.println("Welcome to servlet");
14. pw.println("</body></html>");
15.
16. pw.close();//closing the stream
17. }}

3)Compile the servlet

For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar
files:

Jar file Server

1) servlet-api.jar Apache Tomcat

2) weblogic.jar Weblogic

3) javaee.jar Glassfish

4) javaee.jar JBoss

Two ways to load the jar file

1. set classpath
Unit – 2 CS-25 - Advance Java Programming (J2ee)
2. paste the jar file in JRE/lib/ext folder

Put the java file in any folder. After compiling the java file, paste the class file of servlet in
WEB-INF/classes directory.

4)Create the deployment descriptor (web.xml file)

The deployment descriptor is an xml file, from which Web Container gets the information
about the servet to be invoked.

The web container uses the Parser to get the information from the web.xml file. There are many
xml parsers such as SAX, DOM and Pull.

There are many elements in the web.xml file. Here is given some necessary elements to run the
simple servlet program.

web.xml file

1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>sonoojaiswal</servlet-name>
10. <url-pattern>/welcome</url-pattern>
11. </servlet-mapping>
12.
13. </web-app>

Description of the elements of web.xml file

There are too many elements in the web.xml file. Here is the illustration of some elements that is
used in the above web.xml file. The elements are as follows:

<web-app> represents the whole application.

<servlet> is sub element of <web-app> and represents the servlet.

<servlet-name> is sub element of <servlet> represents the name of the servlet.


Unit – 2 CS-25 - Advance Java Programming (J2ee)

<servlet-class> is sub element of <servlet> represents the class of the servlet.

<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.

<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the
servlet.

5)Start the Server and deploy the project

To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin
directory.

One Time Configuration for Apache Tomcat Server

You need to perform 2 tasks:

1. set JAVA_HOME or JRE_HOME in environment variable (It is required to start server).


2. Change the port number of tomcat (optional). It is required if another server is running on same
port (8080).

1) How to set JAVA_HOME in environment variable?

To start Apache Tomcat server JAVA_HOME and JRE_HOME must be set in Environment
variables.

Go to My Computer properties -> Click on advanced tab then environment variables -> Click on
the new tab of user variable -> Write JAVA_HOME in variable name and paste the path of jdk
folder in variable value -> ok -> ok -> ok.

Go to My Computer properties:
Unit – 2 CS-25 - Advance Java Programming (J2ee)

Click on advanced system settings tab then environment variables:


Unit – 2 CS-25 - Advance Java Programming (J2ee)
Unit – 2 CS-25 - Advance Java Programming (J2ee)

Click on the new tab of user variable or system variable:


Unit – 2 CS-25 - Advance Java Programming (J2ee)

Write JAVA_HOME in variable name and paste the path of jdk folder in variable value:
Unit – 2 CS-25 - Advance Java Programming (J2ee)

There must not be semicolon (;) at the end of the path.

After setting the JAVA_HOME double click on the startup.bat file in apache tomcat/bin.

Note: There are two types of tomcat available:

1. Apache tomcat that needs to extract only (no need to install)


2. Apache tomcat that needs to install

It is the example of apache tomcat that needs to extract only.


Unit – 2 CS-25 - Advance Java Programming (J2ee)
Unit – 2 CS-25 - Advance Java Programming (J2ee)

Now server is started successfully.

2) How to change port number of apache tomcat

Changing the port number is required if there is another server running on the same system with
same port number.Suppose you have installed oracle, you need to change the port number of
apache tomcat because both have the default port number 8080.

Open server.xml file in notepad. It is located inside the apache-tomcat/conf directory . Change
the Connector port = 8080 and replace 8080 by any four digit number instead of 8080. Let us
replace it by 9999 and save this file.

5) How to deploy the servlet project

Copy the project and paste it in the webapps folder under apache tomcat.
Unit – 2 CS-25 - Advance Java Programming (J2ee)

But there are several ways to deploy the project. They are as follows:

 By copying the context(project) folder into the webapps directory


 By copying the war folder into the webapps directory
 By selecting the folder path from the server
 By selecting the war file from the server

Here, we are using the first approach.

You can also create war file, and paste it inside the webapps directory. To do so, you need to use
jar tool to create the war file. Go inside the project directory (before the WEB-INF), then write:

1. projectfolder> jar cvf myproject.war *

Creating war file has an advantage that moving the project from one location to another takes
less time.

6) How to access the servlet

Open broser and write http://hostname:portno/contextroot/urlpatternofservlet. For example:

1. http://localhost:9999/demo/welcome
Unit – 2 CS-25 - Advance Java Programming (J2ee)

 Handling Servlet Requests and Responses

Following is a summary of the most useful HTTP 1.1 response headers which go back to the
browser from web server side and you would use them very frequently in web programming −

Sr.No. Header & Description

Allow
1
This header specifies the request methods (GET, POST, etc.) that the server supports.
Cache-Control

2 This header specifies the circumstances in which the response document can safely be
cached. It can have values public, private or no-cache etc. Public means document is
cacheable, Private means document is for a single user and can only be stored in private
(non-shared) caches and nocache means document should never be cached.
Connection
3
This header instructs the browser whether to use persistent in HTTP connections or not. A
value of close instructs the browser not to use persistent HTTP connections and keepalive
means using persistent connections.
Unit – 2 CS-25 - Advance Java Programming (J2ee)

Content-Disposition
4
This header lets you request that the browser ask the user to save the response to disk in a
file of the given name.
Content-Encoding
5
This header specifies the way in which the page was encoded during transmission.
Content-Language
6
This header signifies the language in which the document is written. For example en, en-
us, ru, etc
Content-Length
7
This header indicates the number of bytes in the response. This information is needed only
if the browser is using a persistent (keep-alive) HTTP connection.
Content-Type
8
This header gives the MIME (Multipurpose Internet Mail Extension) type of the response
document.
Expires
9
This header specifies the time at which the content should be considered out-of-date and
thus no longer be cached.
Last-Modified
10
This header indicates when the document was last changed. The client can then cache the
document and supply a date by an If-Modified-Since request header in later requests.
Location
11
This header should be included with all responses that have a status code in the 300s. This
notifies the browser of the document address. The browser automatically reconnects to
this location and retrieves the new document.
Refresh
12
This header specifies how soon the browser should ask for an updated page. You can
specify time in number of seconds after which a page would be refreshed.
Retry-After
13
This header can be used in conjunction with a 503 (Service Unavailable) response to tell
the client how soon it can repeat its request.
Set-Cookie
14
This header specifies a cookie associated with the page.
Unit – 2 CS-25 - Advance Java Programming (J2ee)

Methods to Set HTTP Response Header


There are following methods which can be used to set HTTP response header in your servlet
program. These methods are available with HttpServletResponse object.

Sr.No. Method & Description

boolean containsHeader(String name)


3
Returns a Boolean indicating whether the named response header has already been set.
void addCookie(Cookie cookie)
5
Adds the specified cookie to the response.
void addDateHeader(String name, long date)
6
Adds a response header with the given name and date-value.
void addHeader(String name, String value)
7
Adds a response header with the given name and value.
void addIntHeader(String name, int value)
8
Adds a response header with the given name and integer value.
void flushBuffer()
9
Forces any content in the buffer to be written to the client.
void reset()
10
Clears any data that exists in the buffer as well as the status code and headers.
void sendError(int sc)
12
Sends an error response to the client using the specified status code and clearing the
buffer.
void sendError(int sc, String msg)
13
Sends an error response to the client using the specified status.
void sendRedirect(String location)
14
Sends a temporary redirect response to the client using the specified redirect location
URL.
void setBufferSize(int size)
15
Sets the preferred buffer size for the body of the response.
Unit – 2 CS-25 - Advance Java Programming (J2ee)

void setCharacterEncoding(String charset)


16
Sets the character encoding (MIME charset) of the response being sent to the client, for
example, to UTF-8.
void setContentLength(int len)
17
Sets the length of the content body in the response In HTTP servlets, this method sets the
HTTP Content-Length header.
void setContentType(String type)
18
Sets the content type of the response being sent to the client, if the response has not been
committed yet.
void setDateHeader(String name, long date)
19
Sets a response header with the given name and date-value.
void setHeader(String name, String value)
20
Sets a response header with the given name and value.
void setIntHeader(String name, int value)
21
Sets a response header with the given name and integer value
void setLocale(Locale loc)
22
Sets the locale of the response, if the response has not been committed yet.
void setStatus(int sc)
23
Sets the status code for this response
Unit – 2 CS-25 - Advance Java Programming (J2ee)

HTTP Header Response Example


You already have seen setContentType() method working in previous examples and following
example would also use same method, additionally we would use setIntHeader() method to set
Refresh header.

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class


public class Refresh extends HttpServlet {

// Method to handle GET method request.


public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

// Set refresh, autoload time as 5 seconds


response.setIntHeader("Refresh", 5);

// Set response content type


response.setContentType("text/html");

// Get current time


Calendar c = new GregorianCalendar();
int am_pm=c.get(Calendar.AM_PM);
int hour = c.get(Calendar.HOUR);
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);

String a_p;
if(am_pm==0)
a_p="AM";
else
a_p="PM";

String all_time="Hour :" + hour + " Minute :" + minute + "


Second :" + second + a_p;

PrintWriter out = response.getWriter();


String title = "Auto Refresh Header Setting";
out.println(title + "<br/>");
out.println("<span style='color:red'>"+ "Current Time is :" +
all_time + "</span>");
}
Now calling the above servlet would display current system time after
every 5 seconds as follows. Just run the servlet and wait to see the result –
OUTPUT:---- Auto Refresh Header Setting

Current Time is: 9:44:50 PM


Unit – 2 CS-25 - Advance Java Programming (J2ee)
 REQUEST

Following is the important header information which comes from browser side and you would
use very frequently in web programming −

Sr.No. Header & Description

Accept
1
This header specifies the MIME types that the browser or other clients can handle. Values
of image/png or image/jpeg are the two most common possibilities.
Accept-Charset
2
This header specifies the character sets the browser can use to display the information. For
example ISO-8859-1.
Accept-Encoding
3
This header specifies the types of encodings that the browser knows how to handle.
Values of gzip or compress are the two most common possibilities.
Accept-Language
4
This header specifies the client's preferred languages in case the servlet can produce
results in more than one language. For example en, en-us, ru, etc
Authorization
5
This header is used by clients to identify themselves when accessing password-protected
Web pages.
Connection
6
This header indicates whether the client can handle persistent HTTP connections.
Persistent connections permit the client or other browser to retrieve multiple files with a
single request. A value of Keep-Alive means that persistent connections should be used.
Content-Length
7
This header is applicable only to POST requests and gives the size of the POST data in
bytes.
Cookie
8
This header returns cookies to servers that previously sent them to the browser.
Host
9
This header specifies the host and port as given in the original URL.
Unit – 2 CS-25 - Advance Java Programming (J2ee)

Referer
10
This header indicates the URL of the referring Web page. For example, if you are at Web
page 1 and click on a link to Web page 2, the URL of Web page 1 is included in the
Referrer header when the browser requests Web page 2.
User-Agent
11
This header identifies the browser or other client making the request and can be used to
return different content to different types of browsers.

Exapmle
Header Name Header Value(s)
Host localhost:8084
user-agent Mozilla/5.0 (Windows NT 6.1; rv:47.0) Gecko/20100101 Firefox/47.0
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
accept-language en-US,en;q=0.5
accept-encoding gzip, deflate
Referrer http://localhost:8084/ServletLifeCycle/
connection keep-alive
content-type application/x-www-form-urlencoded
content-length 8

Methods to read HTTP Header


There are following methods which can be used to read HTTP header in your servlet program.
These methods are available with HttpServletRequest object

Sr.No. Method & Description

Cookie[] getCookies()
1
Returns an array containing all of the Cookie objects the client sent with this request.
2 Enumeration getAttributeNames()
Unit – 2 CS-25 - Advance Java Programming (J2ee)

Returns an Enumeration containing the names of the attributes available to this request.
Enumeration getHeaderNames()
3
Returns an enumeration of all the header names this request contains.
Enumeration getParameterNames()
4
Returns an Enumeration of String objects containing the names of the parameters
contained in this request
HttpSession getSession()
5
Returns the current session associated with this request, or if the request does not have a
session, creates one.

String getAuthType()
6
Returns the name of the authentication scheme used to protect the servlet, for example,
"BASIC" or "SSL," or null if the JSP was not protected.
String getCharacterEncoding()
7
Returns the name of the character encoding used in the body of this request.
String getContentType()
8
Returns the MIME type of the body of the request, or null if the type is not known.
String getHeader(String name)
9
Returns the value of the specified request header as a String.
String getMethod()
10
Returns the name of the HTTP method with which this request was made, for example,
GET, POST, or PUT.
String getParameter(String name)
11
Returns the value of a request parameter as a String, or null if the parameter does not
exist.
String getPathInfo()
12
Returns any extra path information associated with the URL the client sent when it made
this request
String getProtocol()
13
Returns the name and version of the protocol the request.
Unit – 2 CS-25 - Advance Java Programming (J2ee)

String getQueryString()
14
Returns the query string that is contained in the request URL after the path.

String getServletPath()
15
Returns the part of this request's URL that calls the JSP.
String[] getParameterValues(String name)
16
Returns an array of String objects containing all of the values the given request parameter
has, or null if the parameter does not exist.
boolean isSecure()
17
Returns a Boolean indicating whether this request was made using a secure channel, such
as HTTPS.
int getContentLength()
18
Returns the length, in bytes, of the request body and made available by the input stream,
or -1 if the length is not known.
int getServerPort()
19
Returns the port number on which this request was received.
Unit – 2 CS-25 - Advance Java Programming (J2ee)

HTTP Header Request Example


Following is the example which uses getHeaderNames() method of HttpServletRequest to read
the HTTP header information. This method returns an Enumeration that contains the header
information associated with the current HTTP request.

Once we have an Enumeration, we can loop down the Enumeration in the standard manner,
using hasMoreElements() method to determine when to stop and using nextElement() method to
get each parameter name

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class


public class DisplayHeader extends HttpServlet {

// Method to handle GET method request.


public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "HTTP Header Request Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";

out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Header Name</th><th>Header Value(s)</th>\n"+
"</tr>\n"
);

Enumeration headerNames = request.getHeaderNames();

while(headerNames.hasMoreElements()) {
String paramName = (String)headerNames.nextElement();
Unit – 2 CS-25 - Advance Java Programming (J2ee)
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
out.println("</table>\n</body></html>");
}

 Reading Initialization Parameters

The servlet container provides the initialization parameters for a servlet or filter within the
configuration object the container passes to the init method. The configuration object provides
a getInitParameter() function that takes a std::string name and returns the contents of
the initialization parameter by that name. A filter uses the configuration object to access
initialization parameters

Syntax to provide the initialization parameter for a servlet


The init-param sub-element of servlet is used to specify the initialization parameter for a
servlet.

1. <web-app>
2. <servlet>
3. ......
4.
5. <init-param>
6. <param-name>parametername</param-name>
7. <param-value>parametervalue</param-value>
8. </init-param>
9. ......
10. </servlet>
11. </web-app>

ServletConfig to get initialization parameter


In this example, we are getting the one initialization parameter from the web.xml file and
printing this information in the servlet.

DemoServletInit.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class DemoServletInit extends HttpServlet {
6. public void doGet(HttpServletRequest request, HttpServletResponse response)
7. throws ServletException, IOException {
Unit – 2 CS-25 - Advance Java Programming (J2ee)
8.
9. response.setContentType("text/html");
10. PrintWriter PW = response.getWriter();
11.
12. ServletConfig config=getServletConfig();
13. String name=config.getInitParameter("name");
14. pw.print("Name is: "+name);
15.
16. pw.close();
17. }
18. }
19. Here web.xml is updated as following

<servlet>

<servlet-name>D</servlet-name>

<servlet-class>DemoServletInit</servlet-class>

<init-param>

<param-name>name</param-name>

<param-value>KSCPAC</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>D</servlet-name>

<url-pattern>/Demo</url-pattern>

</servlet-mapping>

1. after executing output displays like following:


Unit – 2 CS-25 - Advance Java Programming (J2ee)

 Session Tracking Approaches (URL Rewriting, Hidden


Form Fields, Cookies, Session API)

HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client
opens a separate connection to the Web server and the server automatically does not keep any
record of previous client request.

Still there are following three ways to maintain session between web client and web server −

Cookies
A webserver can assign a unique session ID as a cookie to each web client and for subsequent
requests from the client they can be recognized using the recieved cookie.

This may not be an effective way because many time browser does not support a cookie, so I
would not recommend to use this procedure to maintain the sessions.

 Public void setDomain(String domain)

It is used to set the domain to which the cookie applies

 Public String getDomain()

It is used to get the domain to which cookie applies

 Public void setMaxAge(int expiry)

It sets the maximum time which should apply till the cookie expires

 Public int getMaxAge()

It returns the maximum age of cookie

 Public String getName()

It returns the name of the cookie

 Public void setValue(String value)

Sets the value associated with the cookie


Unit – 2 CS-25 - Advance Java Programming (J2ee)
 Public String getValue()

Get the value associated with the cookie

 Public void setPath(String path)

It sets the path to which cookie applies

 Public String getPath()

It gets the path to which the cookie applies

 Public void setSecure(Boolean flag)

It should be sent over encrypted connections or not.

 Public void setComment(String cmt)

It describes the cookie purpose

 Public String getComment()

It the returns the cookie comments which has been described.

Hidden Form Fields


A web server can send a hidden HTML form field along with a unique session ID as follows −

<input type = "hidden" name = "sessionid" value = "12345">

This entry means that, when the form is submitted, the specified name and value are
automatically included in the GET or POST data. Each time when web browser sends request
back, then session_id value can be used to keep the track of different web browsers.

This could be an effective way of keeping track of the session but clicking on a regular (<A
HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot
support general session tracking.

URL Rewriting
Unit – 2 CS-25 - Advance Java Programming (J2ee)
In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next
resource. We can send parameter name/value pairs using the following format:

url?name1=value1&name2=value2&??

A name and a value is separated using an equal = sign, a parameter name/value pair is
separated from another parameter using the ampersand(&). When the user clicks the
hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we
can use getParameter() method to obtain a parameter value.

Example of using URL Rewriting


In this example, we are maintaning the state of the user using link. For this purpose, we are
appending the name of the user in the query string and getting the value from the query
string in another page.

index.html
1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. //appending the username in the query string
18. out.print("<a href='servlet2?uname="+n+"'>visit</a>");
19.
20. out.close();
Unit – 2 CS-25 - Advance Java Programming (J2ee)

21.
22. }catch(Exception e){System.out.println(e);}
23. }
24.
25. }

SecondServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse response)
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. //getting value from the query string
14. String n=request.getParameter("uname");
15. out.print("Hello "+n);
16.
17. out.close();
18.
19. }catch(Exception e){System.out.println(e);}
20. }
21.
22.
23. }

web.xml
1. <web-app>
1. <servlet>
1. <servlet-name>s1</servlet-name>
2. <servlet-class>FirstServlet</servlet-class>
2. </servlet>
2. <servlet-mapping>
1. <servlet-name>s1</servlet-name>
2. <url-pattern>/servlet1</url-pattern>
2. </servlet-mapping>
Unit – 2 CS-25 - Advance Java Programming (J2ee)

3. <servlet>
1. <servlet-name>s2</servlet-name>
2. <servlet-class>SecondServlet</servlet-class>
4. </servlet>
5. <servlet-mapping>
1. <servlet-name>s2</servlet-name>
2. <url-pattern>/servlet2</url-pattern>
6. </servlet-mapping>
7. </web-app>

The HttpSession Object


Apart from the above mentioned three ways, servlet provides HttpSession Interface which
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.

You would get HttpSession object by calling the public method getSession() of
HttpServletRequest, as below −

HttpSession session = request.getSession();

You need to call request.getSession() before you send any document content to the client. Here is
a summary of the important methods available through HttpSession object −

Sr.No. Method & Description

public Object getAttribute(String name)


1
This method returns the object bound with the specified name in this session, or null if no
object is bound under the name.
public Enumeration getAttributeNames()
2
This method returns an Enumeration of String objects containing the names of all the
objects bound to this session.
public long getCreationTime()
3
This method returns the time when this session was created, measured in milliseconds
since midnight January 1, 1970 GMT.
Unit – 2 CS-25 - Advance Java Programming (J2ee)

public String getId()


4
This method returns a string containing the unique identifier assigned to this session.
public long getLastAccessedTime()
5
This method returns the last accessed time of the session, in the format of milliseconds
since midnight January 1, 1970 GMT
public int getMaxInactiveInterval()
6
This method returns the maximum time interval (seconds), that the servlet container will
keep the session open between client accesses.
public void invalidate()
7
This method invalidates this session and unbinds any objects bound to it.
public boolean isNew( )
8
This method returns true if the client does not yet know about the session or if the client
chooses not to join the session.
public void removeAttribute(String name)
9
This method removes the object bound with the specified name from this session.
public void setAttribute(String name, Object value)
10
$_SESSON[“username”]=”abcd”; $_POST[“txt_uname”]

This method binds an object to this session, using the name specified.
public void setMaxInactiveInterval(int interval)
11
This method specifies the time, in seconds, between client requests before the servlet
container will invalidate this session.
getSession(boolean create)
12 Returns the current HttpSession associated with this request or, if there is no
current session and create is true, returns a new session.
getSession()
13 Returns the current session associated with this request, or if the request does not
have a session, creates one.

Session Example
index.html

<form action="login">
User Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPassword"/><br/>
Unit – 2 CS-25 - Advance Java Programming (J2ee)
<input type="submit" value="submit"/>
</form>

MyServlet1.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();

String name = request.getParameter("userName");


String password = request.getParameter("userPassword");
pwriter.print("Hello "+name);
pwriter.print("Your Password is: "+password);
HttpSession session=request.getSession();
session.setAttribute("uname",name);
session.setAttribute("upass",password);
pwriter.print("<a href='welcome'>view details</a>");
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}
}

MyServlet2.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
HttpSession session=request.getSession(false);
String myName=(String)session.getAttribute("uname");
String myPass=(String)session.getAttribute("upass");
pwriter.print("Name: "+myName+" Pass: "+myPass);
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}
}

web.xml

<web-app>
Unit – 2 CS-25 - Advance Java Programming (J2ee)
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping> </web-app>

First Screen:

After clicking Submit:

After clicking view details:

Deleting Session Data


When you are done with a user's session data, you have several options −

 Remove a particular attribute − You can call public void removeAttribute(String name)
method to delete the value associated with a particular key.
 Delete the whole session − You can call public void invalidate() method to discard an
entire session.
 Setting Session timeout − You can call public void setMaxInactiveInterval(int interval)
method to set the timeout for a session individually.
 Log the user out − The servers that support servlets 2.4, you can call logout to log the
client out of the Web server and invalidate all sessions belonging to all the users.
Unit – 2 CS-25 - Advance Java Programming (J2ee)
 web.xml Configuration − If you are using Tomcat, apart from the above mentioned
methods, you can configure session time out in web.xml file as follows.

<session-config>
<session-timeout>15</session-timeout>
</session-config>

The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in
Tomcat.

The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in
seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( )
returns 900.

 Servlet Collaboration

The Servlet collaboration is all about sharing information among the servlets. Collaborating
servlets is to pass the common information that is to be shared directly by one servlet to another
through various invocations of the methods. To perform these operations, each servlet need to
know the other servlet with which it is collaborated. Here are several ways to communicate with
one another:

 Using RequestDispatchers include() and forward() method;


 Using HttpServletResponse sendRedirect() method;
 Using ServletContext setAttribute() and getAttribute() methods;
 Using Java's system-wide Properties list;
 Using singleton class object.

- The collaboration can be done by redirecting a servlet from another or loading the servlets from the
ServletContext access methods.

- This can also be achieved by the methods forward() and include() of RequestDispatcher or by
sendRedirect() method.

1. ServletContext : In an application, there must be one Servlet context which is shared by all the
servlets in this application. It works as a global map .each servlet put necessary information , which
needs to be shared
and other can get that info
<servlet>
<servlet-name>ServletName</servlet-name>
Unit – 2 CS-25 - Advance Java Programming (J2ee)
<servlet-class>com.example.ServletTest</servlet-class>
</servlet>

<context-param>
<param-name>name</param-name>
<param-value>Shamik Mitra</param-value>
</context-param>

To get this
getServletContext().getInitParameter("email");

Request Dispatcher:
request.setAttribute("name", "Shamik Mitra")
request.getRequestDispatcher("destination_name").forward(req,res);
request.getRequestDispatcher("destination_name").include(req,res);

Java Singleton class :

public class Javacontext


{
private static Javacontext ctx = new Javacontext();
private String name ="Shamik";
private Javacontext()
{
}
public static Javacontext getInstance()
{
return ctx;
}
public String getname()
{
return name;
}
}

Java Properties: Using java properties you can share information

import java.util.*;
Unit – 2 CS-25 - Advance Java Programming (J2ee)

public class PropDemo {

public static void main(String args[]) {


Properties prop= new Properties();
Set<String> key;

prop.put("name", "Shamik Mitra");

// Show all states and capitals in hashtable.


key= prop.keySet(); // get set-view of keys
Iterator itr = key.iterator();
while(itr.hasNext()) {
str = (String) itr.next();
System.out.println("The key is" +
str + " name is " + prop.getProperty(str) + ".");
}

}
}

 Servlet with JDBC


Here, you will learn that how to create simple registration form in servlet. We are using oracle10g
database. So you need to create a table first as given below:

 CREATE TABLE "REGISTERUSER"


 ( "NAME" VARCHAR2(4000),
 "PASS" VARCHAR2(4000),
 "EMAIL" VARCHAR2(4000),
 "COUNTRY" VARCHAR2(4000)
 )

To create the registration page in servlet, we can separate the database logic from the servlet. But
here, we are mixing the database logic in the servlet only for simplicity of the program. We will
develop this page in JSP following DAO, DTO and Singleton design pattern later.
Unit – 2 CS-25 - Advance Java Programming (J2ee)
Example of Registration form in servlet

In this example, we have created the three pages.

 register.html
 Register.java
 web.xml

register.html

 In this page, we have getting input from the user using text fields and combobox. The
information entered by the user is forwarded to Register servlet, which is responsible to
store the data into the database.

<html>
<body>
<form action="servlet/Register" method="post">
Name:<input type="text" name="userName"/><br/><br/>
Password:<input type="password" name="userPass"/><br/><br/>
Email Id:<input type="text" name="userEmail"/><br/><br/>
Country:
<select name="userCountry">
<option>India</option>
<option>Pakistan</option>
<option>other</option>
</select>
<br/><br/>
<input type="submit" value="register"/> </form> </body> </html>
Register.java

This servlet class receives all the data entered by user and stores it into the database. Here, we
are performing the database logic. But you may separate it, which will be better for the web
application.

import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class Register extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
Unit – 2 CS-25 - Advance Java Programming (J2ee)
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
String e=request.getParameter("userEmail");
String c=request.getParameter("userCountry");

try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

PreparedStatement ps=con.prepareStatement(
"insert into registeruser values(?,?,?,?)");

ps.setString(1,n);
ps.setString(2,p);
ps.setString(3,e);
ps.setString(4,c);

int i=ps.executeUpdate();
if(i>0)
out.print("You are successfully registered...");

}catch (Exception e2) {System.out.println(e2);}

out.close();
}

}
web.xml file

The is the configuration file, providing information about the servlet.

<web-app>

<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/servlet/Register</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>register.html</welcome-file>
Unit – 2 CS-25 - Advance Java Programming (J2ee)
</welcome-file-list>

</web-app>

First create a employee table in Oracle and insert some data as below.

create table employee(empid varchar(10),empname varchar(10),sal int)

insert into employee values('e001','raj',10000)


insert into employee values('e002','harry',20000)
insert into employee values('e003','sunil',30000)
insert into employee values('e004','pollock',40000)
insert into employee values('e005','jonty',50000)
insert into employee values('e006','kallis',60000)
insert into employee values('e007','richard',70000)

Creation of dsn(database source name)

Start-Control panel- Administrative Tools- Data Sources (ODBC)-go to system dsn tab-click
add button-select a driver for which you want to set up data source (for Oracle- Oracle in
XE)-select it and click finish-give any name in data source name textbox-then click ok
button.

Program to display data from database through servlet and JDBC

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class display extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws


IOException, ServletException {
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("<html><body>");
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:mydsn", "system",
"pintu");
// Here dsnname- mydsn,user id- system(for oracle 10g),password is pintu.
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from employee");
out.println("<table border=1 width=50% height=50%>");
out.println("<tr><th>EmpId</th><th>EmpName</th><th>Salary</th><tr>");
while (rs.next()) {
String n = rs.getString("empid");
String nm = rs.getString("empname");
int s = rs.getInt("sal");
out.println("<tr><td>" + n + "</td><td>" + nm + "</td><td>" + s +
Unit – 2 CS-25 - Advance Java Programming (J2ee)
"</td></tr>");
}
out.println("</table>");
out.println("</html></body>");
con.close();
}
catch (Exception e) {
out.println("error");
}
}
}

web.xml setting:-

<?xml version="1.0" encoding="ISO-8859-1"?>


<!--
Licensed to the Apache Software Foundation (ASF) under one or more contributor license
agreements. See the NOTICE file distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file to You under the Apache License,
Version 2.0 (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
ANY KIND, either express or implied. See the License for the specific language governing
permissions and limitations under the License.
-->

<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>display</servlet-name>
<servlet-class>display</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>display</servlet-name>
<url-pattern>/display</url-pattern>
</servlet-mapping>
</web-app>

Compile

javac -cp servlet-api.jar display.java (for tomcat 6.0)


Unit – 2 CS-25 - Advance Java Programming (J2ee)

Running the servlet in web browser

First run the tomcat 6.0

http://localhost:8081/javaservlet/display
Unit – 2 CS-25 - Advance Java Programming (J2ee)

You might also like