0% found this document useful (0 votes)
3 views35 pages

Advanced Java Programming (J2Ee) : Bca/Bscit Sem 5

Uploaded by

dhyeysavaliya28
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views35 pages

Advanced Java Programming (J2Ee) : Bca/Bscit Sem 5

Uploaded by

dhyeysavaliya28
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

31-07-2024

ADVANCED JAVA PROGRAMMING (J2EE)


BCA/BSCIT SEM 5

UNIT 2

SERVLET, RMI

1 1
31-07-2024

UNIT 2 SERVLET, RMI

SERVLET INTRODUCTION

• Servlet architecture comes under a java programming language to create dynamic


web applications.
• Mainly servlets are used to develop server-side applications.
• Servlets are very robust and scalable.
• Before introducing servlets, CGI (common gateway interface) was used.
• Servlet is an API that provides many interfaces and classes including
documentation.
• Servlet is an interface that must be implemented for creating any Servlet.
• Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
• Servlet is a web component that is deployed on the server to create a dynamic web
page.

UNIT 2 SERVLET, RMI

ARCHITECTURE OF A SERVLET

Servlets are grouped under the Advanced Java tree that is used to create dynamic
web applications. Servlets are used in developing server-side applications.

Servlet execute various functions, such as:


• Control the flow of the application.
• Generate dynamic web content.
• Server-side load balancing.
• Implement business logic.

There are two types of Servlets-


1. Generic Servlets
2. HTTPServlets.servlets

1 2
31-07-2024

UNIT 2 SERVLET, RMI

Components of Servlet Architecture

Servlet Architecture contains the business logic to process all the requests made by
client. Below is the high-level architecture diagram of servlet.

UNIT 2 SERVLET, RMI

1. Client
The client shown in the architecture above is the web browser and it primarily works
as a medium that sends out HTTP requests over to the web server and the web
server generates a response based on some processing in the servlet and the client
further processes the response.

2. Web Server
Primary job of a web server is to process the requests and responses that a user
sends over time and maintain how a web user would be able to access the files that
has been hosted over the server.

3. Web Container
Web container is another typical component in servlet architecture which is
responsible for communicating with the servlets. Two prime tasks of a web container
are: Managing the servlet lifecycle and URL mapping.

1 3
31-07-2024

UNIT 2 SERVLET, RMI

Servlet Request Flow


The steps to processing a servlet request:
• The client sends a request.
• The web server accepts the request and forwards it to the web container.
• Web container searches web.xml file for request URL pattern and gets the address
of the servlet.

Advantages
• Servlets are server independent, as they are compatible with any web server.
Compared to server-side web technologies like ASP and JavaScript, these are
server-specific.
• Servlets are protocol-independent, i.e., it supports FTP, SMTP, etc. Mainly it
provides extended support to HTTP protocol functionality.
• Servlets are portable; since they are written in java, they are portable and support
any web server.

UNIT 2 SERVLET, RMI

SERVLET API (JAVAX.SERVLET AND JAVAX.SERVLET.HTTP)

Servlets are the Java programs that run on the Java-enabled web server or
application server. They are used to handle the request obtained from the webserver,
process the request, produce the response, then send a response back to the
webserver.
A package in servlets contains numerous classes and interfaces.

Types of Packages
There are two types of packages in Java Servlet that are providing various functioning
features to servlet Applications. The two packages are as follows:

javax.servlet package
javax.servlet.http package

1 4
31-07-2024

UNIT 2 SERVLET, RMI

1: javax.servlet package: This package of Servlet contains many servlet interfaces


and classes which are capacity of handling any types of protocols that are invoked by
the servlet or web server container.

Interfaces in javax.servlet package:


Servlet : This interface describes and connects all the methods that a Servlet must
implement.
ServletRequest : ServletRequest interface is used to retrieve the information data
from the user.
ServletResponse : ServletResponse interface is used to send the information data to
the user.
ServletContext : ServletContext interface is used to featuring the info. data to the web
applications.
ServletConfig : ServletConfig object is used for providing the information data to the
servlet classes.

UNIT 2 SERVLET, RMI

Classes in javax.servlet package:


GenericServlet : If you want to write the Servlet’s protocols other than the HTTP, then
the easy way of doing this is to extend GenericServlet.
ServletInputStream : This class ServletInputStream is used to reading the binary data
from end user request.
ServletOutputStream : This class ServletOutputStream is useful to send the
transferring binary data to the user.

2: javax.servlet.http package:
This package of servlet contains more interfaces and classes which can handle any
specified http types of protocols on the servlet.
The javax.servlet.http packages have provided these feature classes that are unique
to handling these HTTP requests allowing from it.

1 5
31-07-2024

UNIT 2 SERVLET, RMI

Interfaces in javax.servlet.http
HttpServletRequest : The HttpServletRequest interface enables a servlet to obtain
information about a client request.
HttpServletResponse : The HttpServletResponse interface enables a servlet to
formulate an HTTP response to a client.
HttpSession : The HttpSession interface enables a servlet to read and write the state
information that is associated with an HTTP session.

Classes in javax.servlet.http package


HttpServlet : In this HttpServlet purely abstracted class having features as
functionality to extending and applying on the HTTP requests.
Cookie : This Class provides the feature Servlet an interface for the storage of small
portions of data information on the end-user computer or system.

UNIT 2 SERVLET, RMI

SERVLET LIFE CYCLE


The entire life cycle of a Servlet is managed by the
Servlet container which uses the javax.servlet.Servlet
interface.
Stages of the Servlet Life Cycle:
- Loading a Servlet.
- Initializing the Servlet.
- Request handling.
- Destroying the Servlet.

1. Loading a Servlet: The first stage of the Servlet


lifecycle involves loading and initializing the Servlet by
the Servlet container. The Servlet container performs
two operations in this stage :
Loads the Servlet class and Creates an instance of the
Servlet.

1 6
31-07-2024

UNIT 2 SERVLET, RMI

2. Initializing a Servlet: After the Servlet is loading successfully, the Servlet container
initializes the Servlet object. The container initializes the Servlet object by invoking
the Servlet.init(ServletConfig) method which accepts ServletConfig object reference
as parameter. If the Servlet fails to initialize, then it informs the Servlet container by
throwing the ServletException or UnavailableException.

3. Handling request: After initialization, the Servlet instance is ready to serve the
client requests. It creates the ServletRequest and ServletResponse objects.
In this case, if this is a HTTP request, then the Web container creates
HttpServletRequest and HttpServletResponse objects.

4. Destroying a Servlet: When a Servlet container decides to destroy the Servlet, it


performs the following operations, It allows all the threads currently running in the
service method of the Servlet instance to complete their jobs and get released.
After completed their jobs, the the destroy() method run.

UNIT 2 SERVLET, RMI

Servlet Life Cycle Methods


There are three life cycle methods of a Servlet :
init() : A servlet’s life begins here . This method
is called only once to load the
servlet.
service() : The service() method is the most
important method to perform that provides the
connection between client and server.
The web server calls the service() method to
handle requests coming from the client( web
browsers) and to send response back to the
client.
destroy() : The destroy() method is called only
once. It is called at the end of the life cycle of
the servlet.

1 7
31-07-2024

UNIT 2 SERVLET, RMI

Example of Servlet Life Cycle


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AdvanceJavaConcepts extends HttpServlet {
private String output;
public void init() throws ServletException {
output = "Advance Java Concepts"; }
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println(output); }
public void destroy() {
System.out.println("Over"); }
}

UNIT 2 SERVLET, RMI

SERVLET CONFIGURATION WITH DEPLOYMENT DESCRIPTOR


Web applications are configured using elements contained in the web application
deployment descriptor. The deployment descriptor for a JavaServer Faces application must
specify certain configurations, which include the following:

The servlet used to process JavaServer Faces requests


The servlet mapping for the processing servlet
The path to the configuration resource file if it is not located in a default location

The deployment descriptor can also specify other, optional configurations, including:
• Specifying where component state is saved
• Encrypting state saved on the client
• Compressing state saved on the client
• Restricting access to pages containing JavaServer Faces tags
• Turning on XML validation
• Verifying custom objects

1 8
31-07-2024

UNIT 2 SERVLET, RMI

A web application's deployment descriptor maps the http request with the servlets.

When the web server receives a request for the application, it uses the deployment
descriptor to map the URL of the request to the code that ought to handle the request.
The deployment descriptor should be named as web.xml.

It resides in the application's WAR file under the WEB-INF/ directory.

Root element of web.xml should be <web-app>. <servlet> element map a URL to a servlet
using <servlet-mapping> element.

To map a URL to a servlet, you declare the servlet with the <servlet> element, then define
a mapping from a URL path to a servlet declaration with the <servlet-mapping> element.
The <servlet> element declares the servlet class and a logical name used to refer to the
servlet by other elements in the file.

UNIT 2 SERVLET, RMI

1 9
31-07-2024

UNIT 2 SERVLET, RMI

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:

By implementing Servlet interface,


By inheriting GenericServlet class, (or)
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:

UNIT 2 SERVLET, RMI

Create a directory structure:


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 servlet class file must be in the src folder. The web.xml file must be under the
WEB-INF folder.

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

Example:
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;

1 10
31-07-2024

UNIT 2 SERVLET, RMI

public class DemoServlet extends HttpServlet{


public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException {

res.setContentType("text/html");
PrintWriter pw=res.getWriter();

pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");

pw.close();
}
}

UNIT 2 SERVLET, RMI

Compile the Servlet:


For compiling the Servlet, jar file is required to be loaded. Different Servers provide
different jar files:
For Apache Tomcat server servlet-api.jar file is used.
To load the jar file
set classpath

Put the java file in any folder. After compiling the java file, paste the class file of servlet
in src directory.

Create a deployment descriptor:


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.

1 11
31-07-2024

UNIT 2 SERVLET, RMI

Example: web.xml

<web-app>
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

UNIT 2 SERVLET, RMI

Start the server and deploy the project:


To start Apache Tomcat server, double click on the startup.bat file under Apache-
tomcat/bin directory.
Copy the project and paste it in the webapps folder under Apache tomcat.
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.

Access the servlet:


Open browser and write
http://hostname:portno/root/urlpatternofservlet.

For example:
http://localhost:9999/demo/welcome

1 12
31-07-2024

UNIT 2 SERVLET, RMI

HANDLING SERVLET REQUESTS AND RESPONSES


The HttpServlet class provides specialized methods that handle the various types of HTTP
requests. A servlet developer typically overrides one of these methods. These methods are
doGet( ), doPost( ) etc.
The GET and POST requests are commonly used when handling form input.

Handling HTTP GET Requests


Here we will develop a servlet that handles an HTTP GET request. The servlet is invoked
when a form on a web page is submitted. The example contains two files. A web page is
defined in index.html, and a servlet is defined in ColorGetServlet.java.

The HTML source code for index.html defines a form that contains a select element and a
submit button. Notice that the action parameter of the form tag specifies a URL. The URL
identifies a servlet to process the HTTP GET request.

UNIT 2 SERVLET, RMI

index.html

<html>
<body>
<center>
<form name="Form1" action="http://localhost:8080/ColorGetDemo/ColorGetServlet">
<B>Color:</B>
<select name="color" size="1"> <option value="Red">Red</option> <option
value="Green">Green</option>
<option value="Blue">Blue</option> </select>
<br><br>
<input type=submit value="Submit"> </form>
</body>
</html>

1 13
31-07-2024

UNIT 2 SERVLET, RMI

ColorGetServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}

UNIT 2 SERVLET, RMI

Handling HTTP POST Requests


Here we will develop a servlet that handles an HTTP POST request. The servlet is invoked
when a form on a web page is submitted. The example contains two files. A web page is
defined in index.html, and a servlet is defined in ColorPostServlet.java.
The HTML source code for index.html specifies that the POST method should be used, and
the action parameter for the form tag specifies a different servlet.

index.html

<html>
<body>
<center>
<form name="Form1" method="post"
action="http://localhost:8080/ColorPostDemo/ColorPostServlet">
<B>Color:</B>

1 14
31-07-2024

UNIT 2 SERVLET, RMI

<select name="color" size="1">

<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>

</select>
<br><br>

<input type=submit value="Submit"> </form>


</body>
</html>

UNIT 2 SERVLET, RMI

ColorPostServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}

1 15
31-07-2024

UNIT 2 SERVLET, RMI

READING INITIALIZATION PARAMETERS

Most of the time, data (Ex: admin email, database username and password etc.) need to
be provided in the production mode (client choice). Initialization parameters can reduce
the complexity and maintenance.
Initialization parameters are specified in the web.xml file as follows:

<servlet>
<servlet-name>Name of servlet</servlet-name>
<servlet-class>Servlet class</servlet-class>
<init-param>
<param-name>admin</param-name>
<param-value>[email protected]</param-value>
</init-param>
</servlet>

UNIT 2 SERVLET, RMI

Initialization parameters are stored as key value pairs. They are included in web.xml file
inside init-param tags. The key is specified using the param-name tags and value is
specified using the param-value tags.
Servlet initialization parameters are retrieved by using the ServletConfig object. Following
methods in ServletConfig interface can be used to retrieve the initialization parameters:

String getInitParameter(String parameter_name)


Enumeration getInitParameterNames()

Example: index.html
<form action="welcome" method="post">
Username: <input type="text" name="user" /><br/>
Password: <input type="password" name="pass" /><br/>
<input type="submit" value="Submit" />
</form>

1 16
31-07-2024

UNIT 2 SERVLET, RMI

web.xml

<web-app>
<servlet>
<servlet-name>ValidAdmin</servlet-name>
<servlet-class>ValidAdmin</servlet-class>
<init-param>
<param-name>admin</param-name>
<param-value>sarvodya college</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ValidAdmin</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

UNIT 2 SERVLET, RMI

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

public class ValidAdmin extends HttpServlet {


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

PrintWriter out = response.getWriter();


ServletConfig config=getServletConfig();
String name=config.getInitParameter("admin");
out.println("Welcome "+name);
out.close();
}
}

1 17
31-07-2024

UNIT 2 SERVLET, RMI

SESSION TRACKING APPROACHES

Session simply means a particular interval of time.


Session Tracking is a way to maintain state (data) of a user. It is also known as session
management in servlet.
Http protocol is a stateless, so we need to maintain state using session tracking
techniques. Each time user requests to the server, server treats the request as the new
request. So, we need to maintain the state of a user to recognize to user.

There are four techniques used in Session tracking:

Cookies
Hidden Form Field
URL Rewriting
HttpSession

UNIT 2 SERVLET, RMI

1. Cookies in Servlet
A cookie is a small piece of information that can be a name, a single value, and a version
number etc.
There are 2 types of cookies in servlets.

Non-persistent cookie
Persistent cookie

Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It
is removed only if user logout or sign-out.

1 18
31-07-2024

UNIT 2 SERVLET, RMI

Cookie class

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot


of useful methods for cookies.

For adding cookie or getting the value from the cookie, we need some methods provided
by other interfaces. They are:

public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add


cookie in response object.

public Cookie[] getCookies():method of HttpServletRequest interface is used to return all


the cookies from the browser.

UNIT 2 SERVLET, RMI

Example:
In this example, we are storing the name of the user in the cookie object and accessing it
in another servlet.

index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

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

public class FirstServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response){

1 19
31-07-2024

UNIT 2 SERVLET, RMI

try{
response.setContentType("text/html");
PrintWriter out;
out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print("<form action='servlet2' method='post'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(IOException e){System.out.println(e);}
}
}

UNIT 2 SERVLET, RMI

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

public class SecondServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out;
out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(IOException e){System.out.println(e);}
}
}

1 20
31-07-2024

UNIT 2 SERVLET, RMI

web.xml

<web-app>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>SecondServlet</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

UNIT 2 SERVLET, RMI

<servlet-mapping>
<servlet-name>SecondServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

1 21
31-07-2024

UNIT 2 SERVLET, RMI

Hidden Form Field


In case of Hidden Form Field, a hidden (invisible) textfield is used for maintaining the state
of a user.
In such case, we store the information in the hidden field and get it from another servlet.
This approach is better if we must submit form in all the pages and we don't want to
depend on the browser.
Let's see the code to store value in hidden field.

<input type="hidden" name="uname" value="Vimal">


Here, uname is the hidden field name and VimaL is the hidden field value.

Advantage of Hidden Form Field


It will always work whether cookie is disabled or not.
Disadvantage of Hidden Form Field:
It is maintained at server side.
Only textual information can be used.

UNIT 2 SERVLET, RMI

Example:
In this example, we are storing the name of the user in a hidden textfield and getting that
value from another servlet.

index.html

<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

1 22
31-07-2024

UNIT 2 SERVLET, RMI

FirstServlet.java

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

public class FirstServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response){

try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

UNIT 2 SERVLET, RMI

//creating form that have invisible textfield


out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}

SecondServlet.java

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

1 23
31-07-2024

UNIT 2 SERVLET, RMI

public class SecondServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

//Getting the value from the hidden field


String n=request.getParameter("uname");
out.print("Hello "+n);

out.close();
}catch(Exception e){System.out.println(e);}
}
}

UNIT 2 SERVLET, RMI

web.xml

<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

1 24
31-07-2024

UNIT 2 SERVLET, RMI

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>

UNIT 2 SERVLET, RMI

URL Rewriting
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.

Advantage of URL Rewriting


• It will always work whether cookie is disabled or not (browser independent).
• Extra form submission is not required on each pages.
Disadvantage of URL Rewriting
• It will work only with links.
• It can send Only textual information.

1 25
31-07-2024

UNIT 2 SERVLET, RMI

Example:

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

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

public class FirstServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response){

UNIT 2 SERVLET, RMI

try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);
//appending the username in the query string
out.print("<a href='servlet2?uname="+n+"'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}

1 26
31-07-2024

UNIT 2 SERVLET, RMI

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

public class SecondServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//getting value from the query string
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
} }

UNIT 2 SERVLET, RMI

HttpSession interface
In such case, container creates a session id for each user.
The container uses this id to identify the user.
An object of HttpSession can be used to perform two tasks:

1. bind objects
2. view and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.

The HttpServletRequest interface provide a method to get the object of HttpSession:

public HttpSession getSession():Returns the current session associated with this request,
or if the request does not have a session, creates one.

1 27
31-07-2024

UNIT 2 SERVLET, RMI

Commonly used methods of HttpSession interface

public String getId():Returns a string containing the unique identifier value.

public long getCreationTime():Returns the time when this session was created, measured
in milliseconds since midnight January 1, 1970, GMT.

public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1,
1970, GMT.

public void invalidate():Invalidates this session then unbinds any objects bound to it.

UNIT 2 SERVLET, RMI

Example:

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

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

public class FirstServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response){

1 28
31-07-2024

UNIT 2 SERVLET, RMI

try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}

UNIT 2 SERVLET, RMI

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

public class SecondServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
} }

1 29
31-07-2024

UNIT 2 SERVLET, RMI

RMI OVERVIEW

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.

ARCHITECTURE OF AN RMI APPLICATION


In an RMI application, there are 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.

UNIT 2 SERVLET, RMI

The following diagram shows the architecture of an RMI application.


Transport Layer − This layer connects the
client and the server. It manages the existing
connection and sets up new connections.
Stub − A stub is a representation (proxy) of
the remote object at client. It resides in the
client system; it acts as a gateway for the
client program.
Skeleton − This is the object which resides
on the server side. stub communicates with
this skeleton to pass request to the remote
object.
RRL(Remote Reference Layer) − It is the
layer which manages the references made
by the client to the remote object.

1 30
31-07-2024

UNIT 2 SERVLET, RMI

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:

• It initiates a connection with remote Virtual Machine (JVM),


• It writes and transmits the parameters to the remote Virtual Machine (JVM),
• It waits for the result
• It reads the return value or exception, and
• It finally, returns the value to the caller.

UNIT 2 SERVLET, RMI

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:

• It reads the parameter for the remote method


• It invokes the method on the actual remote object, and
• It writes and transmits the result to the caller.

1 31
31-07-2024

UNIT 2 SERVLET, RMI

RMI Example

These are the steps to be followed sequentially to implement Interface as defined


below as follows:

• Define a remote interface.


• Implementing remote interface.
• create and start remote application
• create and start client application

1) create the remote interface


For creating the remote interface, extend the Remote interface and declare the
RemoteException with all the methods of the remote interface.

UNIT 2 SERVLET, RMI

HelloInterface.java

import java.rmi.*;
public interface HelloInterface extends Remote {
public String say() throws RemoteException;
}

2) Provide the implementation of the remote interface


For providing the implementation of the Remote interface, we need to extend the
UnicastRemoteObject class.

1 32
31-07-2024

UNIT 2 SERVLET, RMI

Hello.java

import java.rmi.*;
import java.rmi.server.*;
public class Hello extends UnicastRemoteObject
implements HelloInterface {
private String message;
public Hello(String msg) throws RemoteException {
message = msg;
}
public String say() throws RemoteException {
return message;
}
}

UNIT 2 SERVLET, RMI

3) Create the server application


Now rmi services need to be hosted in a server process. The Naming class provides
methods to get and store the remote object.

HelloServer.java

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
public class HelloServer {
public static void main(String[] args) {
try {
Registry r = java.rmi.registry.LocateRegistry.createRegistry(1099);
//1099 is the port number

1 33
31-07-2024

UNIT 2 SERVLET, RMI

r.rebind("Hello", new Hello("Welcome to Sarvodaya College."));


System.out.println("Server is connected and ready for operation.");
} catch (RemoteException e) {
System.out.println("Server not connected: " + e);
}
}
}

4) Create the client application


At the client we are getting the stub object by the lookup() method of the Naming class
and invoking the method on this object.

UNIT 2 SERVLET, RMI

HelloClient.java
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
public class HelloClient {
public static void main(String[] argv) {
try {
HelloInterface hello = (HelloInterface) Naming.lookup("//localhost/Hello");
System.out.println(hello.say());
} catch (MalformedURLException | NotBoundException | RemoteException e) {
System.out.println("HelloClient exception: " + e);
}
}
}

1 34
31-07-2024

UNIT 2 SERVLET, RMI

Steps to run this RMI application


Save all the above java files into a directory and name it as "rmi"

1. compile all the java files


javac *.java

2. Start RMI registry


start rmiregistry

3. Run Server file


java HelloServer

4. Run Client file in another command prompt


java HelloClient

UNIT 2 SERVLET, RMI

END OF UNIT 2

1 35

You might also like