Unit-7 JSP, RMI (Compatibility Mode)
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 clients format that is interspersed with scripting elements, directives and actions comprised of Java Programming language and JSP syntax.
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
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 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
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 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
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: 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
Example: <HTML> <HEAD> <TITLE> JSP Programming </TITLE> </HEAD> <BODY> <%! int age = 29; %> <P> Your age is : <%= age %> </P> </BODY> </HTML>
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> 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.
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> <%! int age = 29; float salary; int empnumber; %> </BODY> </HTML>
10
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.
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) { return 10 + grade; } %> <P> Your curved grade is: <%= curve (80) %> </P> </BODY> </HTML>
Shreenath Acharya St. Joseph Engg. College, Mangalore 12
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 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.
13
15
<% 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> <% { break; %> case 60: } %> <P> Your final grade is F </P> <% { break; } %> </BODY> </HTML>
Shreenath Acharya St. Joseph Engg. College, Mangalore 16
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 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
<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>
18
<TABLE> <TR> <TD> First </TD> <TD> Second </TD> <TD> Third </TD> </TR> <TR> <% while(x<3) { %> <TD> <%= Grade[x] %> </TD> <% x++; } %> </TR> </TABLE>
19
<TABLE> <TR> <TD> First </TD> <TD> Second </TD> <TD> Third </TD> </TR> <TR> <% x = 0; do { %> <TD> <%= Grade[x] %> </TD> <% x++; } while (x<3); %> </TR> </TABLE> </BODY> </HTML>
20
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. 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.
21
22
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
23
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. 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
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).
26
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 the program sends the dynamic HTML page to the browser.
27
Cookies
A cookie is a small piece of information created by a JSP program that is stored on the clients 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.
29
30
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 the name of the cookie that needs to be retrieved from the clients 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
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 clients 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 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.
33
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. 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.
34
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.
35
38
39
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 facility to load the objects bytecode known as dynamic code loading. ie, the behaviour of an application can be dynamically extended by the remote JVM.
40
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 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 objects methods. The remote stub in turn invokes the actual remote objects 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
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 objects 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 fields are not passed by default. Any changes made to an objects state by the client are not reflected in the original object.
42
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 clients 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.
44
45
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 ( ) ); } } }
46
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 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 objects name is //host/myApplication where host is the name or IP address of the server.
47
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 objects 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 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.
48
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 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
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: 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