Anda di halaman 1dari 21

JAVA & J2EE

10IS753

Unit-7 JSP JSP stands for Java Server Page, it is the server side program. JSP is written in HTML, XML, or in client format.

JSP AND SERVLET Java servlet written using java programming language and responses are encoded as an output string object that is passed to the println() method. The output string object is formatted in html, xml or whatever format required by the client. JSP is written in html, xml or in client format. That is, interspersed with scripting elements, directives and actions comprised of java programming language and JSP syntax. Purpose of JSP JSP program is a combination of HTML tags and JSP tags. JSP is simple to create than a java servlet because JSP is written in html. There are three methods that are automatically called when a JSP is requested and when the JSP terminates normally. These are jspInt() jspDestroy() service() jspInt():This method identical to init() in a java servlet and in an applet. The jspInt() method is called when the JSP is requested. jspInt() method is used to initialize the objects and variables that are used throught out the life of jsp. It is called first. jspDestroy():this method is identical to the destroy method in a java servlet.This method is called automatically when the JSP terminates normally. It is used for clean up where as where resources used during execution are released. ex: disconnecting from data base. service() : this method is called automatically and retrieves a connection to http.

Dept. of ISE, MIT-Mysore

Page 1

JAVA & J2EE

10IS753

JSP TAGS: JSP tags are embedded into the HTML component of a JSP program. These tags are processed by a JSP virtual engine such as tomcat. There are 5 types of tags. These are as follows: Comment tag Declaration statement tag Directive tags Expression tag Scriptlet tag A comment tag opens with <%-- and closes with --%> and is followed by a comment line that usually describes the functionality of statements that follow the comment tag. Ex:<%- - this is simple jsp program - - %> Declaration Statement Tag opens with <%! and it is followed by java declaration statements that define variables, objects, and methods that are available to other components of the program. This tag closes with %>. Ex:- <%! int x=100; %> Directive tags : A directive tag opens with <%@ and closes with %>. There are three commonly used directive tags, they are import, include and taglib. The import tag is used to import java tags packages into the JSP program. The include tag inserts a new file into the JSP program. The taglib tag specifies the a file that contains a tag library. Ex:- <%@ page import="java.util.* " %> An Expression tag opens with <%= and is used for an expression statement . An expression tag closes with %>. Ex:- <%= "this is expression tag %> <%= (a+b) %> <%= a %> A scriptlet tag opens with <% and contains commonly used java control statements and loops. A scriptlet tag closes with %>. Ex:- <% for(int i=0;i<3;i++) { %> <p>your grade is:<%=grade[i]%></p> <%}%>

Dept. of ISE, MIT-Mysore

Page 2

JAVA & J2EE

10IS753

Variables and objects:Declaring and using a variable:<html> <head> <title>welcome to JSP programming</title> </head> <body> <%! int age=29; %> <h1>your age is: <%=age %></h1> </body> </html> Declaring multiple variables within a single JSP tag <html> <head> <title>welcome to JSP programming</title> </head> <body> <%! int age=29; float salary=2000; int empnumber=100; %> <h1>your age=<%=age%></h1> <h1>your salary=<%=salary%></h1> <h1>your empnumber=<%=empnumber%></h1> </body> </html> Declaring objects and arrays within a single JSP tag <html> <head> <title>welcome to JSP programming</title> </head> <body> <%! String name; String [ ] Telephone = { 201-555-1212, 201-555-4433 }; String Company = new String(); Vector Assignments = new Vector(); int [ ] grade={100, 82, 93}; %> </body> </html>

Dept. of ISE, MIT-Mysore

Page 3

JAVA & J2EE

10IS753

Methods:Defining and calling a method <html> <head> <title>JSp Programming</title> </head> <body> <%! double area(double r) { return 3.14*r*r; } %> <h1>area of a circle=<%=area(4) %></h1> </body> </html> Method overloading /*Q. Write a JSP program to demonstrate method overloading. */ <html> <head> <title>JSp Programming</title> </head> <body> <%! double area(double r) { return 3.14*r*r; } double area(double l, double b) { return l*b; } %> <h1>Area of a circle=<%=area(4) %></h1> <h1>Area of a rectangle=<%=area(4,2) %></h1> </body> </html>

Control statements:Using an if stament information are to be sent to the browser <html> <head> <title>JSp Programming</title> </head> <body> <%! int grade = 85; %> <% if(grade>=69){%> <p>you passed!</p> Dept. of ISE, MIT-Mysore Page 4

JAVA & J2EE

10IS753

<%} else { %> <p>Better luck next time.</p> <%} %> </body> </html> Using switch stament information are to be sent to the browser <html> <head> <title>JSp Programming</title> </head> <body> <%! int grade = 85; %> <% 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> </body> </html> <% break; } %>

Looping Statements:Using for loop <html> <head> <title>welcome to JSP programming</title> </head> <body> <%! int [ ] grade={100, 82, 93}; %> <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> </body> </html> Dept. of ISE, MIT-Mysore Page 5

JAVA & J2EE

10IS753

Using while loop <html> <head> <title>welcome to JSP programming</title> </head> <body> <%! int [ ] grade={100, 82, 93}; int x=0; %> <table> <tr> <td>First</td> <td>second</td> <td>third</td> </tr> <tr> <% while(x<3) { %> <td><%=grade[x]%></td> <% x++; }%> </tr> </table> </body> </html> Using do..while loop <html> <head> <title>welcome to JSP programming</title> </head> <body> <%! int [ ] grade={100, 82, 93}; int x=0; %> <table> <tr> <td>First</td> <td>second</td> <td>third</td> </tr> <tr> <% do { %> <td><%=grade[x]%></td> <% x++; } while(x<3);%> </tr> </table> </body> </html> Dept. of ISE, MIT-Mysore Page 6

JAVA & J2EE

10IS753

Q. Write a JSP program for simple calculator. <html> <head> <title>JSP program for simple calculator</title> </head> <body> <%! double add(double a, double b) { return a+b; } double sub(double a, double b) { return a-b; } double mul(double a, double b) { return a*b; } double div(double a, double b) { return a/b; } %> <p>Addition of two numbers:<%=add(6,3)%></p> <p>Substraction of two numbers:<%=sub(6,3)%></p> <p>Multiplication of two numbers:<%=mul(6,3)%></p> <p>Division of two numbers:<%=div(8,7)%></p> </body> </html> Q. Write a JSP program print current date and time on the web page and refresh the page for every 10 seconds. <html> <head> <title>Page refreshing example</title> <meta http-equiv = "refresh" content = "10" /> <title>A Simple JSP Example</title> </head> <body> </body> </html>

<p>Simple JSP Example</p> <%= new java.util.Date() %>

Dept. of ISE, MIT-Mysore

Page 7

JAVA & J2EE

10IS753

Q. Department has set the grade for the subject Java as follows: Above 90: A, 80 - 89: B, 70 -79: C, Below 70 = fail. Sham enters his marks for the subject Java in the interface provided. Write a JSP program to accept the marks entered and display his grade to the browser. Grade1.jsp <html> <head> <title>JSP Programming</title> </head> <body> <h3>Enter your grade</h3> <form method="post" action="/root/jsp1/Grade2.jsp"> <input type="text" name="grade" size="3" /> <input type="submit" value="Send" /> </form> </body> </html> Grade2.jsp <html> <body> <%! int grade = Integer.parseInt(request.getParameter(grade)); %> <% if(grade>=90){%> <p>Grade is A</p> <%} else if(grade>=80 && grade<=89){ %> <p>Grade is B</p> <%} else if(grade>=70) { %> <p>Grade is C</p> <%} else { %> <p>fail</p> <%} %> </body> </html>

Dept. of ISE, MIT-Mysore

Page 8

JAVA & J2EE

10IS753

TOMCAT: JSP programs are executed by a JSP virtual machine that runs on a web server. Tomcat is JSP virtual machine. To down load and install tomcat: Connect to jakarta.apache.org Select download Select binaries to display the binary down load page Create a folder from the root directory called tomcat. Download jakarta-tomcat.zip to the tomcat folder. Unzip jakarta-tomcat.zip. Extract the zip file in tomcat directory, bin, conf, doc, lib, src and webapps. Use text editor such as notepad and edit the java_ome variable in the tomcat.bat file which is located in the \tomcat\bin folder. Java_home is assigned the path where jdk is installed on the system. Open the window and type \tomcat\bin\tomcat to start tomcat. Open the browser. Type it as follows. Http:\\localhost:8080 .tomcat home page is displayed on the screen. REQUEST STRING: The browser generates a user request string whenever the submit button is clicked. User request string consists of the URL and the query string. It is as follows. http://localhost:8090/abc/one.jsp The server page (program) has to parse the query string to extract values of fields that are to be processed by the program. The query string can be parsed by using methods of the JSP request object. The getParameterName (Name) is the method used to parse a value of a specific field. The request object is an instance of HttpServletRequest The response object is an instance of HttpServletResponse The session object is an instance of HttpSession

Dept. of ISE, MIT-Mysore

Page 9

JAVA & J2EE

10IS753

<% %> <html> <body>

String x=request.getParameter("t1"); out.println(x);

<form name=form1 method=post action="http://localhost:8070/mit/four.jsp"> username <input type=textbox name="t1"> <input type=submit value="go"> </form></body></html> getParameterValues() method is used to return multiple values from the field specified as the argument to the getParameterValues(). EX: <% String [] email = request.getParameterValues("EMAILADDRESS"); %> <P> <%= email [0] %> </p> <p><%= email[1]%> </p> <html> <body> <form name=form1 method=post action="http://localhost:8070/harsha/five.jsp"> ENAME:<input type=text name="EMAILADDRESS"><br> EMAILID:<input type=text name="EMAILADDRESS"><br> <input type=submit value="go"> </form> </body> </html> USER SESSIONS: JSP program must be able to track a session as a client moves from between html pages and JSP programs. These commonly used methods are hidden field, Dept. of ISE, MIT-Mysore Page 10

JAVA & J2EE

10IS753

cookie java bean. A hidden field is one whose value is not displayed on the html page. hidden.html <html> <body> <form action="http://localhost:8070/harsha/hidden.jsp"> <input type="hidden" value="xyz" name="t1"> <input type=submit value="go"> </form> </body> </html> hidden.jsp <%@ page import="java.lang.*"%> <% String x=request.getParameter("t1");%> <%= "ur name is"+x%> COOKIE: It is a small piece of information created by a JSP program that is stored on the clients hard disk by the browser. These are used to store various kinds of information. Such as user preferences and an id that tracks a session with a JSP database system.
/* Write a JSP program to create and read cookie named userid that stores the value JB007 */

CreateCookie.jsp <% String uid="userid"; String uvalue="JB007"; response.addCookie(new Cookie(uid,uvalue)); %> Readcookie.jsp <html> <body> <%! String uid="userid"; String uvalue;

Dept. of ISE, MIT-Mysore

Page 11

JAVA & J2EE

10IS753

String cname,cvalue; int found=0; Cookie[] c = request.getCookies(); for(int i=0; i<c.length;i++) { cname=c[i].getName(); cvalue=c[i].getValue(); if(uid.equals(cookieNames[i])) { found=1; uvalue=cvalue; } } if(found==1) { %> <p><cookie name= <%=uid %> </p> <p>cookie value=<%= uvalue %></p> <% } %> </body> </html> SESSION OBJECTS: A JSP database system is to share information among JSP program with in a session by using a session object. Each time the session is created; a unique id is assigned to the session and stored as a cookie. A unique id enables JSP programs to track multiple sessions simultaneously while maintaining data integrity of each session. Session id is to prevent the mingling of information from clients. In addition to session id, it contains other information such as attribute. Attribute can be login information. // uvalue =cookieValue;

Dept. of ISE, MIT-Mysore

Page 12

JAVA & J2EE

10IS753

Below exapmle illustrates how to assign information to a session attribute. <html> <body> <%@ page session="true" %> <% String AtName="product"; String AtValue=1234; session.setAttribute(AtName, AtValue); %> <body> </html> Below program shows how to read session attributes. <html> <body> <%! Enumeration check = session.getAttributeNames(); while(check.hasMoreElements()) { String atname=(String)attributeNames.nextElement(); String atvalue=(String)session.getAttribute(atname); %> <p> Attribute Name <%= atname %> </p> <p> Attribute value <%= atvalue %> </p> <% } %> </body> </html>

Dept. of ISE, MIT-Mysore

Page 13

JAVA & J2EE

10IS753

REMOTE METHOD INVOCATION (RMI) or Purpose of RMI: Java object runs within a java virtual machine. A J2EE application runs with in a JVM. However objects used by a J2EE application do not need to run on the same JVM. A J2EE application and its components can invoke objects located on a different JVM by using the remote method invocation. RMI is used for remote communication between java applications and components. Both of which must 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. 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 reference the remote object. In either case, RMI returns a reference to the remote object which is then invoked by the client as if the object was on the local JVM. RMI handles transmission of requests and provides the facility to load the objects bytecode, which is referred to as dynamic code loading. REMOTE INTERFACE: 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. The 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 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 set of remote interfaces that are implemented by the remote object. Dept. of ISE, MIT-Mysore Page 14

JAVA & J2EE

10IS753

PASSING OBJECTS: 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. RMI PROCESS: There are three steps necessary to make an object available to remote clients. These are To design an object To compile an object To make the object accessible to remote clients over the network. Defining the business logic of an object, the remote interface for the object is to be defined. It identifies the methods that are available to remote clients. In addition to the methods that can be invoked by remote clients, the other methods that support the processing of client invoked methods to be defined. These are referred to as server methods. While methods invoked by client are called client methods. Compilation of the object is a two step process. the remote interface, server and client methods. Once the object is compiled, a stub has to be created for the object. This is done by calling the RMI compiler called rmic. The compiled object is then made accessible over the network by loading the object to a server. RMI remote object registry is to be started. Otherwise, a remote client will be unable to access the object. It begins by compiling the object using the javac compiler. The object must contain the implementation of

Dept. of ISE, MIT-Mysore

Page 15

JAVA & J2EE

10IS753

SERVER SIDE: The server side of a remote object invocation consists of a remote interface and methods. 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.
REMOTE INTERFACE DEFINITION:

import import import import

java.util.*; java.io.*; java.rmi.*; java.rmi.server.*;

public interface rmic1 extends Remote { String mymethod()throws RemoteException; } The following program is server-side program that contains the remote objects definition. import java.rmi.*; import java.rmi.server.*; import java.io.*; public class rmic2 extends UnicastRemoteObject implements rmic1 { public rmic2()throws RemoteException { } public String mymethod() { return "I am here to serve"; } public static void main(String v[]) { try { rmic2 obj = new rmic2(); Naming.rebind("xxx",obj); } catch(Exception error) { } } }

Dept. of ISE, MIT-Mysore

Page 16

JAVA & J2EE

10IS753

The implementation class uses UnicastRemoteObject to link into the RMI system. This is not a requirement. A class that does not extend UnicastRemoteObject may use its exportObject() method to be linked into RMI. When a class extends UnicastRemoteObject, it must provide a constructor that declares that it may throw a RemoteException object. When this constructor calls super(), it activates code in UnicastRemoteObject that performs the RMI linking and remote object initialization Client Side:The client side program calls the remote object, which returns a String object that client side program displays. Below program illustrates the client side program. This program begins by creating security manager. import java.rmi.*; import java.rmi.server.*; import java.net.*; import java.io.*; public class rmic4 { public static void main(String v[]) { try { rmic1 x = (rmic1)Naming.lookup("rmi://mukund-64c65018./xxx"); System.out.println(x.mymethod()); } catch(Exception e) { System.out.println(e); } } }

The lookup() method is used to locate the remote object. Before running the client, you need to Compile the source code. Compile the server class using rmic compiler, which produces the skeleton and stub classes. Dept. of ISE, MIT-Mysore Page 17

JAVA & J2EE

10IS753

Start the rmiregistry. Start the server. Run the client.

Advantages of RMI:Since RMI is a Java native, integration of its remote object facilities into a Java application is seamless. You can use RMI-enabled objects as if they live in the local Java environment. RMI extends the internal garbage-collection mechanisms of the standard JVM to provide distributed garbage collection of remotely exported objects. RMI is platform-independent (though not language-independent). RMI is easy to learn. You can migrate entire objects (i.e. class byte codes are portable) to a remote host via object serialization in RMI. This is not possible in CORBA.

Dept. of ISE, MIT-Mysore

Page 18

JAVA & J2EE

10IS753

More examples:RMI calculator program Server Side:Remote Interface The Calculator interface defines all of the remote features offered by the service: import java.rmi.*; public interface Calculator extends Remote { public long add(long a, long b) throws RemoteException; public long sub(long a, long b) throws RemoteException; public long mul(long a, long b) throws RemoteException; public long div(long a, long b) throws RemoteException; } RMI Calculator: Implementation import java.rmi.*; import java.rmi.server.*; public class CalculatorImpl extends UnicastRemoteObject implements Calculator { public CalculatorImpl() throws java.rmi.RemoteException { super(); } public long add(long a, long b) throws RemoteException { return a + b; } public long sub(long a, long b) throws RemoteException { return a - b; } public long mul(long a, long b) throws RemoteException { return a * b; } public long div(long a, long b) throws RemoteException { return a / b; } }

Dept. of ISE, MIT-Mysore

Page 19

JAVA & J2EE

10IS753

The implementation class uses UnicastRemoteObject to link into the RMI system. This is not a requirement. A class that does not extend UnicastRemoteObject may use its exportObject() method to be linked into RMI. When a class extends UnicastRemoteObject, it must provide a constructor that declares that it may throw a RemoteException object. When this constructor calls super(), it activates code in UnicastRemoteObject that performs the RMI linking and remote object initialization

RMI Calculator: Server program


Remote RMI services must be hosted in a server process. The class CalculatorServer is a very simple server that provides the bare essentials for hosting. import java.rmi.Naming; public class CalculatorServer { public CalculatorServer() { try { Calculator c = new CalculatorImpl(); Naming.rebind(" rmi://localhost:1099/CalculatorService", c); } catch (Exception e) { System.out.println("Trouble: " + e); } } public static void main(String args[]) { new CalculatorServer(); } }

RMI Calculator: Client program


public class CalculatorClient { public static void main(String[] args) { try {
Calculator c = (Calculator) Naming.lookup( "rmi://remotehost/CalculatorServer");

Dept. of ISE, MIT-Mysore

Page 20

JAVA & J2EE

10IS753

} catch (MalformedURLException e) { } } } .

System.out.println( System.out.println( System.out.println( System.out.println(

c.sub(4, 3) ); c.add(4, 5) ); c.mul(3, 6) ); c.div(9, 3) );

Dept. of ISE, MIT-Mysore

Page 21

Anda mungkin juga menyukai