Download - Unit-7 JSP, RMI [Compatibility Mode]

Transcript
Page 1: Unit-7 JSP, RMI [Compatibility Mode]

Java Server Pages

1Shreenath Acharya St. Joseph Engg.

College, Mangalore

Page 2: Unit-7 JSP, RMI [Compatibility Mode]

• Java Server pages(JSP) is a server side program that is similar in design and

functionality to a Java servlet.

• JSP is called by a client to provide a Web Service whose nature depends upon the

J2EE application.

• A JSP processes the request by using logic built into the JSP or by calling other web

components built using Java Servlet technology or Enterprise Java Bean (EJB)

technology.

• Once a request is processed, the JSP responds by sending the results to the client.

• JSP is written in HTML, XML or in the client’s format that is interspersed with

scripting elements, directives and actions comprised of Java Programming language

and JSP syntax.

2Shreenath Acharya St. Joseph Engg.

College, Mangalore

Page 3: Unit-7 JSP, RMI [Compatibility Mode]

JSP

• JSP is simpler to create than a Java servlet since it is written in HTML rather than Java

programming language.

• JSP offers the same features like Servlets, because a JSP is converted to a Java Servlet

the first time that a client requests the JSP.

• The three methods that are automatically called when a JSP is requested and when a JSP is

terminated are:

i). jspInit( ):

It is identical to init( ) method in Java Servlet and an applet.

It is called first when the JSP is requested and is used to initialize objects and

variables that are used throughout the life cycle of the JSP.

ii). jspDestroy( ):

It is identical to the destroy( ) method in Java Servlet and an applet.

It is called automatically when the JSP terminates.

It is not called when the JSP abruptly terminates such as server crash.

It is used for cleanup to release the resources used during the execution of the

JSP such as disconnecting from a database.

iii). service( ): It is automatically called and retrieves a connection to HTTP.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

3

Page 4: Unit-7 JSP, RMI [Compatibility Mode]

Installation• Once a JSP is created it should be placed in the same directory as HTML

pages(unlike servlet which requires to be placed in a separate directory).

• Referencing a JSP does not require to set the CLASSPATH.

• The three factors to be considered while installing JSP are:

1). Web services called by a JSP must be installed properly.

For ex: A Java servlet called by a JSP must be placed in the designated

directory for Java servlets and referenced on the CLASSPATH. The

development environment used to create the J2EE application development environment used to create the J2EE application

determines the designated directory.

2). Avoid placing the JSP in the WEB-INF or META-INF directories. The

development environment prohibits it.

3). The directory name used to store a JSP must not have the same name as the

prefix of the URL of the web application.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

4

Page 5: Unit-7 JSP, RMI [Compatibility Mode]

JSP Tags• A JSP program consists of a combination of HTML tags and JSP tags.

• JSP tags define Java code to be executed before the output of the JSP program is sent to

the browser.

• A JSP tag begins with a <% , which is followed by Java code, and ends with %>.

• Another version of JSP tags known as Extendable Markup Language(XML) are formatted

as <jsp:TagID> </jsp:TagID>.

• JSP tags are embedded into the HTML component of a JSP program and are processed by a • JSP tags are embedded into the HTML component of a JSP program and are processed by a

JSP virtual engine such as Tomcat.

• Tomcat reads the JSP program whenever the program is called by a browser and resolves

JSP tags, then sends the HTML tags and related information to the browser.

• The Java code associated with JSP tags in the JSP program is executed when encountered

by Tomcat, and the result of that process is sent to the browser.

• The browser knows how to display the result since the JSP tag is enclosed within an open

and closed HTML tag.Shreenath Acharya St. Joseph Engg.

College, Mangalore

5

Page 6: Unit-7 JSP, RMI [Compatibility Mode]

Five Types of JSP tags1. Comment tag:

It opens with <%-- and closes with --%>

It is followed by a comment that describes the functionality of statements that

follow the comment tag.

2. Declaration statement tags:

It opens with <%!

It is followed by a Java declaration statement(s) that define variables, objects and

methods that are available to other components of the JSP program.

It closes with %>It closes with %>

3. Directive tags:

It opens with <%@

It commands the JSP virtual engine to perform a specific task such as, importing

a Java package required by objects and methods used in a declaration statement.

This tag closes with %>

Shreenath Acharya St. Joseph Engg.

College, Mangalore

6

Page 7: Unit-7 JSP, RMI [Compatibility Mode]

• The three commonly used directive tags are: import, include and taglib.

1. import tag is used to import Java packages into the JSP program.

2. include tag inserts a specified file into the JSP program replacing the include

tag.

3. taglib tag specifies a file that contains a tag library.

Example:

<%@ page import = “ import java.sql.*; %> // import tag – imports the package

<%@ include file = “keogh\books.html” %> //include tag – includes the file

<%@ taglib uri = “myTags.tld” %> //taglib tag - loads myTags.tld library

4. Expression tags:4. Expression tags:

It opens with <% =

It is used for an expression statement whose result replaces the expression tag

when the JSP virtual engine resolves JSP tags.

It closes with %>

5. Scriptlet tags:

It opens with <%

It contains commonly used Java control statements and loops.

It closes with %>

Shreenath Acharya St. Joseph Engg.

College, Mangalore

7

Page 8: Unit-7 JSP, RMI [Compatibility Mode]

Variables and Objects• In a JSP program the declaration statement must appear as a JSP tag within the

JSP program before the variable or object is used in the program.

Example:

<HTML>

<HEAD>

<TITLE> JSP Programming </TITLE>

</HEAD>

<BODY><BODY>

<%! int age = 29; %>

<P> Your age is : <%= age %> </P>

</BODY>

</HTML>

Shreenath Acharya St. Joseph Engg.

College, Mangalore

8

Page 9: Unit-7 JSP, RMI [Compatibility Mode]

Example – Explanation:

• The declaration <%! int age = 29; %> tells the JSP virtual engine to make

statements contained in the tag variable available to other JSP tags in the program.

It needs to be done every time when we declare variables or objects in our program

unless they are only to be used within the JSP tag where they are declared.

• The variable age is used in the expression tag inside a HTML paragraph as,

<P> Your age is : <%= age %> </P><P> Your age is : <%= age %> </P>

The JSP virtual engine resolves the JSP expression before sending the output of the

JSP program to the browser. ie, the JSP tag <%= age %> is replaced with its value

29 before sending the information to the browser.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

9

Page 10: Unit-7 JSP, RMI [Compatibility Mode]

• Multiple statements could be placed within a JSP tag by extending the close JSP

tag to another line in the JSP program.

Example:

<HTML>

<HEAD>

<TITLE> JSP Programming </TITLE>

</HEAD>

<BODY><BODY>

<%! int age = 29;

float salary;

int empnumber;

%>

</BODY>

</HTML>

Shreenath Acharya St. Joseph Engg.

College, Mangalore

10

Page 11: Unit-7 JSP, RMI [Compatibility Mode]

• Apart from variables, we will also be able to declare objects, arrays and Java

collections within a JSP tag using similar techniques as in a Java program.

Example - to show how to declare an object and an array:

<HTML>

<HEAD>

<TITLE> JSP Programming </TITLE>

</HEAD>

<BODY>

<%! String Name;

String [ ] Telephone = { “201-555-1212”, “201-555-4433” };String [ ] Telephone = { “201-555-1212”, “201-555-4433” };

String Company = new String( );

Vector Assignments = new Vector( );

int [ ] Grade = {100,82,93};

%>

</BODY>

</HTML>

• Here the JSP program creates three String objects, the first two declarations implicitly

allocate memory and the third, explicitly allocates memory. In addition, it creates

arrays and a Vector.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

11

Page 12: Unit-7 JSP, RMI [Compatibility Mode]

Methods• In a JSP program a method is defined similar to a method definition in a Java

program except that the method definition must be placed within a JSP tag.

• The methods could be called from within the JSP tag once it is defined.

Example:

<HTML>

<HEAD>

<TITLE> JSP Programming </TITLE>

</HEAD>

<BODY>

<%! boolean curve (int grade)<%! boolean curve (int grade)

{

return 10 + grade;

}

%>

<P> Your curved grade is: <%= curve (80) %> </P>

</BODY>

</HTML>

Shreenath Acharya St. Joseph Engg.

College, Mangalore

12

Page 13: Unit-7 JSP, RMI [Compatibility Mode]

• In the previous example the method is called from within an HTML paragraph.

• Although any appropriate tag can be used to call the method, technically the method

is called from within the JSP tag that is enclosed within the HTML paragraph

tag.

• The JSP tag that calls the method must be a JSP expression tag, which begins with

<%=.

• The JSP virtual engine resolves the JSP tag that calls the method by replacing the • The JSP virtual engine resolves the JSP tag that calls the method by replacing the

JSP tag with the results returned by the method, which is then passed along to the

browser that called the JSP program.

• A JSP program is capable of handling any kind of method that are normally used in

a Java program.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

13

Page 14: Unit-7 JSP, RMI [Compatibility Mode]

Example – Method overloading in JSP<HTML>

<HEAD>

<TITLE> JSP Programming </TITLE>

</HEAD>

<BODY>

<%! boolean curve (int grade)

{

return 10 + grade;

}

boolean curve (int grade, int curveValue)boolean curve (int grade, int curveValue)

{

return curveValue + grade;

}

%>

<P> Your curved grade is: <%= curve (80, 10) %> </P>

<P> Your curved grade is: <%= curve (70) %> </P>

</BODY>

</HTML>Shreenath Acharya St. Joseph Engg.

College, Mangalore

14

Page 15: Unit-7 JSP, RMI [Compatibility Mode]

Control Statements - Example

<HTML>

<HEAD>

<TITLE> JSP Programming </TITLE>

</HEAD>

<BODY>

<%! int grade=70; %>

<% if (grade > 69) { %>

<P> You passed! </P>

<% } else { %><% } else { %>

<P> Better luck next time. </P>

<% } %>

Shreenath Acharya St. Joseph Engg.

College, Mangalore

15

Page 16: Unit-7 JSP, RMI [Compatibility Mode]

<% switch (grade)

{

case 90: } %>

<P> Your final grade is A </P>

<% { break; %>

case 80: } %>

<P> Your final grade is B </P>

<% { break; %>

case 70: } %>

<P> Your final grade is C </P><P> Your final grade is C </P>

<% { break; %>

case 60: } %>

<P> Your final grade is F </P>

<% { break;

}

%>

</BODY>

</HTML>

Shreenath Acharya St. Joseph Engg.

College, Mangalore

16

Page 17: Unit-7 JSP, RMI [Compatibility Mode]

Loops - Example• JSP loops are identical to loops that we use in our Java program except that, we can

repeat HTML tags and related information multiple times within our JSP program

without having to enter the additional HTML tags.

• The three kinds of loops used are: for loop, while loop and do …… while loop.

• The following example creates the same table using the above three kinds of looping

constructs.

Here the JSP program initially declares and initializes an array and an integer, and then

begins to create the first table.

There are two rows in each table.

The first row contains three column headings that are hard coded into the JSP program.

The second row also contains three columns each of which is a value of an element of theThe second row also contains three columns each of which is a value of an element of the

array.

<HTML>

<HEAD>

<TITLE> JSP Programming </TITLE>

</HEAD>

<BODY>

<%! int [ ] Grade = {100,82,93};

int x = 0;

%>

Shreenath Acharya St. Joseph Engg.

College, Mangalore

17

Page 18: Unit-7 JSP, RMI [Compatibility Mode]

<TABLE>

<TR>

<TD> First </TD>

<TD> Second </TD>

<TD> Third </TD>

</TR>

<TR>

<% for (int i = 0; i<3;i++) { %>

<TD> <%= Grade[i] %> </TD>

<% } %><% } %>

</TR>

</TABLE>

Shreenath Acharya St. Joseph Engg.

College, Mangalore

18

Page 19: Unit-7 JSP, RMI [Compatibility Mode]

<TABLE>

<TR>

<TD> First </TD>

<TD> Second </TD>

<TD> Third </TD>

</TR>

<TR>

<% while(x<3) { %>

<TD> <%= Grade[x] %> </TD>

<% x++;<% x++;

} %>

</TR>

</TABLE>

Shreenath Acharya St. Joseph Engg.

College, Mangalore

19

Page 20: Unit-7 JSP, RMI [Compatibility Mode]

<TABLE>

<TR>

<TD> First </TD>

<TD> Second </TD>

<TD> Third </TD>

</TR>

<TR>

<% x = 0;

do { %>

<TD> <%= Grade[x] %> </TD><TD> <%= Grade[x] %> </TD>

<% x++;

} while (x<3); %>

</TR>

</TABLE>

</BODY>

</HTML>

Shreenath Acharya St. Joseph Engg.

College, Mangalore

20

Page 21: Unit-7 JSP, RMI [Compatibility Mode]

Tomcat• The JSP programs are executed by a JSP Virtual Machine that runs on a web

server. So, we need to have access to a JSP Virtual Machine to run our JSP

program.

• Alternatively, we can use an integrated development environment (IDE) such as

JBuilder that has a built-in JSP Virtual Machine or we can download and install

a JSP Virtual Machine.

• Tomcat is one of the most popular JSP Virtual Machine which is downloadable

from the Apache web site.from the Apache web site.

• Apache is a popular web server that can also be downloaded.

• JDK must be installed in our system (to work with JSP) which ca be downloaded

from the www.sun.com web site.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

21

Page 22: Unit-7 JSP, RMI [Compatibility Mode]

Steps to download and install Tomcat1. Connect to jakarta.apache.org.

2. Select download.

3. Select Binaries to display the Binary Download page.

4. Create a folder from the root directory called Tomcat.

5. Download the latest release of jakarta-tomcat.zip to the tomcat folder.

6. Unzip jakarta-tomcat.zip. We can download a demo copy of WinZip from

www.winzip.com if we don’t have a zip/unzip program installed on our computer.

7. The extraction process should create the following folders in the tomcat directory:

bin, conf, doc, lib src and webapps.

8. Use a text editor such as Notepad and edit the JAVA_HOME variable in the 8. Use a text editor such as Notepad and edit the JAVA_HOME variable in the

tomcat.bat file, which is located in the \tomcat \bin folder. The JAVA_HOME

variable should be assigned with the path, where the JDK is installed in our

computer.

9. Open a DOS window and type \tomcat\bin\tomcat to start the Tomcat.

10. Open the browser. Enter the url http://localhost:8080. The Tomcat home page is

displayed on the screen verifying that it is running.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

22

Page 23: Unit-7 JSP, RMI [Compatibility Mode]

Request String• The browser generates a user request string whenever the Submit button is selected.

• The user request string consists of the URL and the query string .

Ex:

http://www.jimkeogh.com/jsp/myprogram.jsp?fname = “Bob” & lname = “Smith”

• Our program needs to parse the query string to extract values of fields that should

be processed by our program.

• We can parse the query string by using methods of the JSP request object. The

method getParameter(Name) is used to parse a value of a specified field. The

argument passed is the name of the field whose value is to be retrieved.

Example: To retrieve the value of the fname field and the lname field:

<%! String Firstname = request.getParameter(fname);

String Lastname = request.getParameter(lname);

%>

• We can use request string values throughout our program once the values are

assigned to variables in our JSP program

Shreenath Acharya St. Joseph Engg.

College, Mangalore

23

Page 24: Unit-7 JSP, RMI [Compatibility Mode]

• There are four predefined implicit objects in every JSP program.

They are: request, response, session and out.

The request object is an instance of HttpServletRequest.

The response object is an instance of HttpServletResponse.

The session object is an instance of HttpSession.

The out object is an instance of the JspWriter that is used to send a response to

the client.

• Copying a value from a multivalued field such as selection field can be easily

handled by using the getParameterValues( ) method. This method is designed to

return multiple values of the field specified as the argument.return multiple values of the field specified as the argument.

Ex: To retrieve the EMAILADDRESS as an array of String objects called

EMAIL.

<%! String [ ] EMAIL = request.getParameterValues(“EMAILADDRESS”); %>

<P> <%= EMAIL [0] %> </P>

<P> <%= EMAIL [1] %> </P>

We can parse the field names by using the getParameterNames( ) method. This

method returns an enumeration of String objects that contains the field names in

the request string.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

24

Page 25: Unit-7 JSP, RMI [Compatibility Mode]

Passing Other Information• The request string sent to the JSP by the browser is divided into two general components

that are separated by the question mark.

The URL component appears to the left of the question mark and,

The query string appears to the right of the question mark.

• The URL is divided into four parts: protocol, host, port and virtual path

• Protocol:

The protocol defines the rules that are used to transfer the request string from the browser

to the JSP program.

The commonly used protocols are HTTP, HTTPS (the secured version of HTTP) and FTP

(file transfer protocol).(file transfer protocol).

• Host and port combination:

The host is the Internet Protocol (IP) address or name of the server that contains the

JSP program.

The port number is the port that the host monitors.

The port is usually excluded from the request string whenever HTTP is used

because the assumption is the host monitoring port 80.

• Virtual path of the JSP program:

The server maps the virtual path to the physical path.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

25

Page 26: Unit-7 JSP, RMI [Compatibility Mode]

Example: A Typical URL

http://www.jimkeogh.com/jsp/myprogram.jsp

Here,

protocol is http.

host is www.jimkeogh.com.

port is not specified since the browser assumes that the server is monitoring port

80.

virtual path is /jsp/myprogram.jsp

Shreenath Acharya St. Joseph Engg.

College, Mangalore

26

Page 27: Unit-7 JSP, RMI [Compatibility Mode]

User Sessions• A JSP program must be able to track a session as a client moves between HTML

pages and JSP programs.

• The three commonly used methods to track a session are:

1). By using a hidden field

2). By using a Cookie

3). By using a Java Bean.

• A hidden field is an HTML form whose value is not displayed on the HTML

page. We can assign a value to a hidden field in a JSP program before thepage. We can assign a value to a hidden field in a JSP program before the

program sends the dynamic HTML page to the browser.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

27

Page 28: Unit-7 JSP, RMI [Compatibility Mode]

Example – Hidden field workingEx:

If our JSP database system displays a dynamic logic screen, the browser sends the

user ID and password to the JSP program when the submit button is selected,

where these parameters are parsed and stored into two memory variable .

The JSP program then validates the login information and generates another

dynamic HTML page once the user ID and password are approved. The

dynamically built HTML page contains a form that contains a hidden field, among

other fields. And the user ID is assigned as the value to the hidden field.

When the person selects the Submit button on the new HTML page , the user ID

stored in the hidden field and information in other fields on the form are sent by

the browser to another JSP program for processing.

The above cycle continues where the JSP program processing the request string

receives the user ID as a parameter and then passes the user ID to the next

dynamically built HTML page as a hidden field. In this way, each HTML page

and subsequent JSP program has access to the user ID and therefore can track the

session.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

28

Page 29: Unit-7 JSP, RMI [Compatibility Mode]

Cookies• A cookie is a small piece of information created by a JSP program that is stored

on the client’s hard disk by the browser.

• Cookies are used to store various kinds of information such as, user preferences

and an ID that tracks a session with a JSP database system.

• We can create and read a cookie by using methods of the Cookie class and the

response object.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

29

Page 30: Unit-7 JSP, RMI [Compatibility Mode]

Example – Creating and Writing a Cookie<HTML>

<HEAD>

<TITLE> JSP Programming </TITLE>

</HEAD>

<BODY>

<%! String MyCookieName = “userID”;

String MyCookieValue = “JK1234”;

response.addCookie(new Cookie(MyCookieName, MyCookieValue));

%>

</BODY></BODY>

</HTML>

The above example begins by initializing the cookie name and cookie value and then

passes these String objects as arguments to the constructor of a new cookie. This cookie

is then passed to the addCookie( ) method, which causes the cookie to be written to the

client’s hard disk.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

30

Page 31: Unit-7 JSP, RMI [Compatibility Mode]

Example – Cookie retrieval and sending information to the Browser

<HTML>

<HEAD>

<TITLE> JSP Programming </TITLE>

</HEAD>

<BODY>

<%! String MyCookieName = “userID”;

String MyCookieValue;

String CName, CValue;

int found = 0;

Cookie [ ] = request.getCookies( ); Cookie [ ] = request.getCookies( );

for(int i =0; i<cookies.length; i++) {

CName = cookies[ i].getName( );

CValue = cookies [i ].getValue( );

if(MyCookieName.equals(CName)){

found = 1;

MyCookieValue = CValue;

}

} Shreenath Acharya St. Joseph Engg.

College, Mangalore

31

Page 32: Unit-7 JSP, RMI [Compatibility Mode]

if(found = = 1) { %>

<P> Cookie name = <%= MyCookieName %> </P>

<P> Cookie value= <%= MyCookieValue %> </P>

<% } %>

</BODY>

</HTML>

Explanation:

In the above example, a String object named MyCookieName is initialized to theIn the above example, a String object named MyCookieName is initialized to the

name of the cookie that needs to be retrieved from the client’s hard disk.(here it is

userID).

Two other String objects are created to hold the name and value of the cookie read from

the client namely, CName and CValue.

An integer variable named found is used as a flag (initialized to zero).

Shreenath Acharya St. Joseph Engg.

College, Mangalore

32

Page 33: Unit-7 JSP, RMI [Compatibility Mode]

An array of Cookie objects called cookies is created and assigned the results of the

request.getCookies ( ) method, which reads all the cookies from the client’s hard disk

and assigns them to the array of Cookie objects.

The methods getName( ) and getValue( ) methods to retrieve the name and value from

each object of the array of Cookie objects. Each time a cookie is read, the program

compares the name of the cookie to the value of the MyCookieName string object, which

is userID.

When a match is found, the program assigns the value of the current Cookie object to theWhen a match is found, the program assigns the value of the current Cookie object to the

MyCookieValue String object and changes the value of the found variable from 0 to 1.

After reading all the Cookie objects, the program evaluates the value of the found

variable. If the value is 1, the program sends the value of the MyCookieName and

MyCookieValue to the browser, which displays these values on the screen.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

33

Page 34: Unit-7 JSP, RMI [Compatibility Mode]

Session Objects• Sharing of the information among JSP programs within a session is by using a

session object.

• Each time a session is created, a unique ID is assigned to the session and stored as

a cookie.

• The unique ID enables JSP programs to track multiple sessions simultaneously

while maintaining data integrity of each session.

• The session ID is used to prevent the intermingling of information from clients.• The session ID is used to prevent the intermingling of information from clients.

• A session object is also used to store other types of information called attributes.

• An attribute can be login information, preferences or even purchase placed in an

electronic shopping cart.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

34

Page 35: Unit-7 JSP, RMI [Compatibility Mode]

Example• Suppose we have built a Java database system that enables customers to purchase

goods online. A JSP program dynamically generates catalogue pages of available

merchandise. A new catalogue page is generated each time the JSP program

executes.

• The customer selects merchandise from a catalogue page, then jumps to another

catalogue page where additional merchandise is available for purchase. Our JSP

database system must be able to temporarily store purchases made from each

catalogue page, otherwise, the system is unable to execute the checkout process.

ie, the purchases must be accessible each time the JSP program executes.

The different ways of sharing the purchases are:

1). Storing merchandises temporally in a table which needs to access the DBMS

several times during the session, this might cause performance degradation.

2). Using a session object and storing the information about the purchases as

session attributes. Session attributes can be retrieved and modified each time the

JSP program runs.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

35

Page 36: Unit-7 JSP, RMI [Compatibility Mode]

Example- Assigning information to session attribute<HTML>

<HEAD>

<TITLE> JSP Programming </TITLE>

</HEAD>

<BODY>

<%! String AtName = “Product”;

String AtValue = “1234”;

Session.setAttribute(AtName, AtValue);

%>

</BODY>

<HTML>

The above example program creates and initializes two String objects.

The first String object is assigned the name of the attribute.

The second String object is assigned a value for the attribute.

The programs calls the setAttribute( ) method with the above two string objects as the

parameters.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

36

Page 37: Unit-7 JSP, RMI [Compatibility Mode]

Example – Reading Attributes<HTML>

<HEAD>

<TITLE> JSP Programming </TITLE>

</HEAD>

<BODY>

<%! Enumeration purchases = session.getAttributeNames();

While(purchases.hasMoreElements( ) ) {

String AtName = (String ) purchases.nextElement ( );

String AtValue = (String ) session.getAttribute (AtName);

<P> Attribute Name = <%= AtName %> </P>

<P> Attribute Value = <%= AtValue %> </P>

<% } %>

</BODY>

<HTML>

The above example program begins by calling the getAttributeNames( ) method that returns names of

all the attributes as an Enumeration. The program tests whether or not the getAttributeNames( )

method returned any attributes. If it is true, the while loop is executed assigning the attribute name of

the current element to the AtName String object.

The AtName String object is passed as an argument to the getAttribute( ) method which returns the

value of the attribute. The program sends the attribute name and value to the browser.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

37

Page 38: Unit-7 JSP, RMI [Compatibility Mode]

Remote Method Invocation (RMI)Remote Method Invocation (RMI)

Shreenath Acharya St. Joseph Engg.

College, Mangalore

38

Page 39: Unit-7 JSP, RMI [Compatibility Mode]

Remote Method Invocation Concept• A Java object runs within a Java Virtual Machine(JVM).

• A J2EE application runs within a JVM, however, objects used by a J2EE application

do not need to run on the same JVM as the J2EE application. This is because a J2EE

application and its components can invoke objects located on a different JVM by

using the Java Remote Method Invocation (RMI) system.

• RMI is used for remote communication between Java applications and

components, both of which must be written in the Java programming language.

• RMI is used to connect together a client and a server.

• A client is an application or component that requires the services of an object to

fulfill a request.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

39

Page 40: Unit-7 JSP, RMI [Compatibility Mode]

• A server creates an object and makes the object available to clients.

• A client contacts the server to reference and invoke the object by using RMI.

• A client locates a remote object by either using the RMI naming registry or by

passing a string that references the remote object. In either case, the RMI returns

a reference to the remote object, which is then invoked by the client as if the object

was on the local JVM.

• Dynamic code loading: The RMI handles transmission of requests and provides the• Dynamic code loading: The RMI handles transmission of requests and provides the

facility to load the object’s bytecode known as dynamic code loading.

ie, the behaviour of an application can be dynamically extended by the remote JVM.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

40

Page 41: Unit-7 JSP, RMI [Compatibility Mode]

Remote Interface• The server-side objects that are invoked by remote clients must implement a remote

interface and associated method definitions.

• The remote interface is used by clients to interact with the object using RMI

communications.

• A remote interface extends java.rmi.Remote and each method must throw a

RemoteException.

• When a client references a remote object, the RMI passes a remote stub for the • When a client references a remote object, the RMI passes a remote stub for the

remote object.

• The remote stub is the local proxy for the remote object. The client calls the

remote method on the local stub whenever the client wants to invoke one of the

remote object’s methods. The remote stub in turn invokes the actual remote

object’s method.

• A remote stub implements the sets of remote interfaces that are implemented by

the remote object.Shreenath Acharya St. Joseph Engg.

College, Mangalore

41

Page 42: Unit-7 JSP, RMI [Compatibility Mode]

Passing Objects• The RMI passes objects as arguments and returns a value by reference.

• The reference is the stub of the remote object.

• Any changes made to an object’s state by an invocation of a remote call affect

the original remote object.

• Object serialization is used to pass a local object by value.

• Serialization can override how static and transient fields are passed. These • Serialization can override how static and transient fields are passed. These

fields are not passed by default.

• Any changes made to an object’s state by the client are not reflected in the

original object.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

42

Page 43: Unit-7 JSP, RMI [Compatibility Mode]

The RMI ProcessThe three steps to make an object available to remote clients are:

1). To design an object

2). To compile the object

3). To make the object accessible to remote clients over the network.

1). Besides developing (designing) the business logic of an object, the developer must define a

remote interface for the object which identifies methods that are available to remote

clients. These methods must be defined in the object.

The developer must also define the methods that support the processing of client – invoked

methods known as server methods.

The methods invoked by a client are known as client methods.

2). Compilation of the object is a two – step process:2). Compilation of the object is a two – step process:

1). Compiling the object using the javac compiler. The object must contain

implementation of the remote interface and server and client methods.

2). Once the object is compiled we must create a stub for the object by calling the RMI

compiler called rmic.

3). The compiled object is made accessible over the network by loading the object to a server.

The RMI remote object registry must be running, otherwise, a remote client will be unable to

access the object.

To start the RMI registry on Windows NT, we need to type the following in the command

line:

C:\> start rmiregistryShreenath Acharya St. Joseph Engg.

College, Mangalore

43

Page 44: Unit-7 JSP, RMI [Compatibility Mode]

Server Side• The server side of a remote object invocation consists of a remote interface and

methods.

• The remote interface is at the center of every remote object because the remote

interface defines how the client views the object.

• Methods provide the business logic that fulfills a client’s request whenever the

client remotely invokes the method.

• Example – Remote interface definition :

import java.rmi.Remote;

import java.rmi.RemoteException;

public interface myApplication extends Remote

{

String myMethod( ) throws RemoteException;

}

In the above example the method myMethod( ) is available to clients. It does not

require any arguments and returns a String object.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

44

Page 45: Unit-7 JSP, RMI [Compatibility Mode]

Example – Server Side Program containing Remote Objects Definition

import java.rmi.*;

import java.rmi.server.*;

public class myApplicationServer extends UnicastRemoteObject implements

myApplication

{

public myApplicationServer ( ) throws RemoteException

{

super( );

}}

public String myMethod ( )

{

return “I’m here to serve. \n”;

}

Shreenath Acharya St. Joseph Engg.

College, Mangalore

45

Page 46: Unit-7 JSP, RMI [Compatibility Mode]

public static void main(String args [ ])

{

if (System.getSecurityManager ( ) = = null)

{

System.setSecurityManager (new RMISecurityManager( ) );

}

String app = “// localhost/myApplication”;

try {

myApplicationServer server = new myApplicationServer ( );

Naming. rebind(app, server);

} catch (Exception error)

{

System.err.println (“myApplicationServer exception: “ + error.getMessage ( ) );

}

}

}

Shreenath Acharya St. Joseph Engg.

College, Mangalore

46

Page 47: Unit-7 JSP, RMI [Compatibility Mode]

• The above program implements the previously defined interface myApplication.

• The program creates and installs a security manager.

• A security manager serves as a firewall and grants or rejects downloaded code

access to the local file system and similar privileged operations. RMI requires that

server-side applications install a security manager.

• The getSecurityManager( ) method creates a SecurityManager object.

The setSecurityManager( ) method associates the server – side program with the

SecurityManager object.

• The server - side program creates an instance of myApplication and makes the • The server - side program creates an instance of myApplication and makes the

remote object myMethod available to remote clients by calling the rebind( )

method.

The rebind( ) method registers the remote object with the RMI remote object

registry or with another naming service.

The object’s name is “//host/myApplication” where host is the name or IP address

of the server.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

47

Page 48: Unit-7 JSP, RMI [Compatibility Mode]

• The argument to the rebind ( ) method is the URL that contains the location and

name of the remote object and the server.

• The RMI returns to a remote client reference to the remote object’s stub and not

to the object itself.

• The port number on the server must be specified if the port number 1099(default

port) is not used.

• Reference to a remote object can be bound, unbound, or rebound to the registry • Reference to a remote object can be bound, unbound, or rebound to the registry

only if the object and registry are on the same host. It is a security restriction that

prevents the registry from being deleted or modified by a remote client.

NOTE : Refer Quick Reference Guide in text book for more informations

about the Interfaces, Methods and Classes on JSP and RMI.

Shreenath Acharya St. Joseph Engg.

College, Mangalore

48

Page 49: Unit-7 JSP, RMI [Compatibility Mode]

Client Side• The client side program calls the remote object defined in the server - side

example which returns a String object that the client – side program displays.

• A real - world application requires the remote object to perform complicated

operations that simply return a String object.

The following example illustrates the client - side program.

• It begins by creating a security manager(same as in the server - side program).

• The lookup ( ) method is used to locate the remote object known as• The lookup ( ) method is used to locate the remote object known as

myApplication. It returns a reference to the object called mApp.

• The program calls the myMethod ( ) method to invoke the myMethod( ) of the

println( ) method which displays the contents of the String object on the screen.

• Any exceptions that are thrown while the client - side program runs are trapped by

the catch( ) block. The catch( ) block calls the getMessage ( ) method to retrieve

the error message that is associated with the exception which will be displayed on

the screen.Shreenath Acharya St. Joseph Engg.

College, Mangalore

49

Page 50: Unit-7 JSP, RMI [Compatibility Mode]

Client – Side Programimport java.rmi.*;

public class myApplicationClient {

public static void main(String args[ ]) {

if(System.getSecurityManager( ) == null)

{

System.setSecurityManager( new RMISecurityManager( ) );

}

try {

String app = “//localhost/myApplication”;String app = “//localhost/myApplication”;

myApplication mApp = (myApplication) Naming.lookup(app);

System.out.println(mApp.myMethod ( ) );

} catch (Exception error)

{

System.err.println(“myApplicationClient exception: “ + error.getMessage( ) );

}

}

}Shreenath Acharya St. Joseph Engg.

College, Mangalore

50

Page 51: Unit-7 JSP, RMI [Compatibility Mode]

Before running the client we need to,

1. Compile the source code.

2. Compile the server class using the rmic compiler, which produces the skeleton

and stub classes.

3. Start the rmiregistry.

4. Start the server.

5. Start the client.

Command line necessary to run the client program:

java -Djava.security.policy = c:/javacode/src/policy myApplicationClient

Command line necessary to run the server program:Command line necessary to run the server program:

java -Djava.rmi.server.codebase= file:///c:/javacode/classes/ -

Djava.security.policy = c:/javacode/src/policy myApplicationServer

The Djava.rmi.server.codebase argument identifies the location of the class files.

One or three forward slashes must precede the path depending on the operating environment.

The Djava.security.policy argument identifies the location of the policy file.

Example – policy file :

grant {

permission java.security.AllPermission;

};

Shreenath Acharya St. Joseph Engg.

College, Mangalore

51