0% found this document useful (0 votes)
113 views17 pages

Java Unit7 Ashok Kumar K

The document provides information about Java Server Pages (JSP) notes prepared by Mr. Ashok Kumar K for the 7th semester of B.E in Computer Science/Information Science Engineering at VTU. It discusses the basics of JSP including defining a JSP, the difference between JSP and servlets, advantages of JSP over servlets, JSP architecture, and JSP tags. It is intended to teach students about JSP and provide study materials for their course.

Uploaded by

NikhilGupta
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)
113 views17 pages

Java Unit7 Ashok Kumar K

The document provides information about Java Server Pages (JSP) notes prepared by Mr. Ashok Kumar K for the 7th semester of B.E in Computer Science/Information Science Engineering at VTU. It discusses the basics of JSP including defining a JSP, the difference between JSP and servlets, advantages of JSP over servlets, JSP architecture, and JSP tags. It is intended to teach students about JSP and provide study materials for their course.

Uploaded by

NikhilGupta
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/ 17

VTU

7th sem B.E (CSE/ISE)

JAVA/ J2EE

Notes prepared by
Mr. Ashok Kumar K
9742024066 | [email protected]
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

Unit 7:

Java Server Pages,


Remote Method Invocation

Mr. Ashok Kumar K


9742024066 | [email protected]

Mr. Ashok Kumar K | 9742024066 | [email protected]


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

15 reasons to choose VTUPROJECTS.COM for your final year project work

1. Training from the scratch


We train our students on all the languages and technologies required for developing the projects from the
scratch. No prerequisites required.
2. Line by Line code explanation
Students will be trained to such an extent where they can explain the entire project line by line code to their
respective colleges.
3. Study Materials
We provide the most efficient study material for each and every module during the project development
4. Trainers
Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter
expert in strengthening student's skillset for cracking any interviews. He will be having a thorough experience
in working on both product and service driven industries.
5. Reports and PPTs
Project report as per the university standards and the final presentation slides will be provided and each
student will be trained on the same.
6. Video manuals
Video manuals will be provided which will be useful in installing and configuring various softwares during
project development
7. Strict SDLC
Project development will be carried out as per the strict Software Development model
8. Technical Seminar topics
We help students by providing current year's IEEE papers and topics of their wish for their final semester
Technical seminars
9. Our Availability
We will be available at our centers even after the class hours to help our students in case they have any
doubts or concerns.
10. Weightage to your Resume
Our students will be adding more weightage to their resumes since they will be well trained on various
technologies which helps them crack any technical interviews
11. Skype/ Team viewer support
In case the student needs an emergency help when he/she is in their colleges, we will be helping out them
through Skype/ Team viewer screen sharing
12. Practical Understanding
Each and module in the project will be implemented and taught to the students giving practical real world
applications and their use.
13. Mock demo and presentations
Each student will have to prepare for mock demo and presentations every week so that he/she will be
confident enough to demonstrate the project in their respective colleges
14. Communication & Soft skills Training
We provide communication and soft skills training to each students to help improve their presentation and
demonstration skills.
15. Weekly monitoring
Each student will be monitored and evaluated on the status of the project work done which helps the students
to obtain thorough understanding on how the entire project will be developed

Mr. Ashok Kumar K | 9742024066 | [email protected]


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

JAVA SERVER PAGES

7.1 Basics

Servlets are powerful and sometimes they are a bit cumbersome when it comes to generating complex HTML. Most servlets contain a
little code that handles application logic and a lot more code that handles output formatting (presentation logic). This can make it difficult
to separate and reuse portions of the code when a different output format is needed. For these reasons, web application developers
turn towards JSP as their preferred servlet environment.

Below is the snap shot of the servlet program that we have seen in previous chapter. Notice the application logic and presentation logic
are coupled together which is not recommended. In later sections we see how JSP helps in separating the application logic from the
presentation logic.

Defining a JSP

A JSP page is a text based document containing static HTML and dynamic actions which describe how to process a response to the
client in a more powerful and flexible manner. Most of a JSP file is a plain HTML but it also will be interspersed with special JSP tags.

Java Server Pages (JSP) is a server side program that is similar in design and functionality to a java Servlet. A JSP is called by client to
provide a web service, the nature of which depends on the J2EE Application.

Mr. Ashok Kumar K | 9742024066 | [email protected]


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

Difference between JSP and Servlet

Servlet is written using Java programming language and JSP is written in HTML, XML, or in the client’s
responses are encoded as an output string object that is format that is interspersed with the scripting
passed to the println() method. The output string object is elements, directives, and actions comprised of
formatted in HTML, XML, or whatever format are required by Java programming language and JSP syntax
the client

Advantages of JSPs over Servlet

 Servlets use println statements for printing an HTML document which is usually very difficult to use. JSP has no such
tedious task to maintain.
 JSP needs no compilation, CLASSPATH setting and packaging.
 In a JSP page visual content and logic are separated, which is not possible in a servlet.
 There is automatic deployment of a JSP; recompilation is done automatically when changes are made to JSP pages.
 Usually with JSP, Java Beans and custom tags web application is simplified
 Reduces Development time

7.2 JSP Architecture

A JSP page is executed in a JSP container (or JSP engine), which is installed in a web server (or an application server). When a client
requests for a JSP page the engine wraps up the request and delivers it to the JSP page along with a response object. The JSP page
processes the request and modifies the response object to incorporate the communication with the client. The container or the engine,
on getting the response, wraps up the responses from the JSP page and delivers it to the client. The underlying layer for a JSP is
actually a servlet implementation. The abstraction of the request and response are the same as the ServletRequest and
ServletResponse respectively. If the protocol used is HTTP, then the corresponding objects are HttpServletRequest and
HttpServletResponse.

The first time when the engine intercepts a request for a JSP, it compiles this translation unit (the JSP page and other dependent files)
into a class file that implements the servlet protocol. If the dependent files are other JSPs they are compiled into their own classes.

Since most JSP pages use HTTP, their implementation classes must actually implement the javax.servlet.jsp.HttpJspPage
interface, which is a sub interface of javax.servlet.jsp.JspPage.

The javax.servlet.jsp.JspPage interface contains two methods:

public void jspInit()

This method is invoked when the JSP is initialized and the page authors are free to provide
initialization of the JSP by implementing this method in their JSPs.

public void jspDestroy()

This method is invoked when the JSP is about to be destroyed by the container. Similar to above,
page authors can provide their own implementation.

The javax.servlet.jsp.HttpJspPage interface contains one method:

Mr. Ashok Kumar K | 9742024066 | [email protected]


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
public void _jspService (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException

This method generated by the JSP container, is invoked, every time a request comes to the JSP. The
request is processed and the JSP generates appropriate response. This response is taken by the
container and passed back to the client.

7.3 JSP Tags

JSP tags define java code that is to be executed before the output of a JSP program is sent to the browser.
There are five types of JSP tags:
1. Comment Tag
2. Declaration statement Tag
3. Directive Tag
4. Expression Tag
5. Scriptlet Tag

Comment Tag

A comment tag opens with <%-- and closes with --%>, and is followed by a comment that usually describes the functionality of
statements that follow the comment tag.
Ex:
<%--
This is a JSP Comment
--%>

Declaration Statement Tag

A Declaration statement tag opens with <%! and is followed by a Java declaration statements that define variables, objects, and
methods.
Ex:
<%!
int a; String s;
Employee e = new Employee();
%>

Directive Tag

A Directive tag opens with <%@ and closes with %>. There are three commonly used directives.
 Import
Used to import java packages into JSP program
Ex: <%@ page import = “java.sql.*” %>
 Include
It inserts a specified file into the JSP program replacing the include tag
Ex: <%@ include file = ”Keogh\book.html” %>

Mr. Ashok Kumar K | 9742024066 | [email protected]


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

 Taglib
It specifies a file that contains a tag library
Ex: <%@ taglib uri = “myTags.tld” %>

Expression Tag

An expression tag opens with <%= and is used for an expression statement whose result replaces the expression tag. It closes with %>
Ex:
<%! int a = 5, b = 10; %>
<%= a+b %>

Scriptlet Tag

A scriptlet tag opens with <% and contains commonly used java control statements and loops. It closes with %>

7.4 Implicit Objects in JSP

JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call
them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.
JSP supports nine Implicit Objects which are listed below:

Object Description
request This is the HttpServletRequest object associated with the
request.
response This is the HttpServletResponse object associated with the
response to the client.
out This is the PrintWriter object used to send output to the
client.
session This is the HttpSession object associated with the request.
application This is the ServletContext object associated with application
context.
config This is the ServletConfig object associated with the page.
pageContext This encapsulates use of server-specific features like higher
performance JspWriters.
page This is simply a synonym for this, and is used to call the
methods defined by the translated servlet class.
Exception The Exception object allows the exception data to be
accessed by designated JSP.

7.5 Example JSP Programs

1. JSP to illustrate variables declarations and usage

<html>
<body>
<%!
Mr. Ashok Kumar K | 9742024066 | [email protected]
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
int a = 10;
String s = "TEST";
%>
<p>
int value is <%= a %>
String value is <%= s %>
</p>
</body>
</html>

2. JSP that defines a method and illustrates its usage.

<html>
<body>
<%!
int findSum(int a, int b) {
return a+b;
}
%>
<p>
sum of 2 and 5 is <%=findSum(2,5) %>
</p>
</body>
</html>

3. JSP to illustrate control statements

<html>
<body>
<%!
int grade = 70;
%>

<% if (grade >= 70 ) {%>


FCD
<% } else if (grade<70 && grade>=60) { %>
FC
<% } else if (grade<60 && grade>=50) { %>
SC
<% } else if (grade<50 && grade>=35) { %>
Just pass
<% } else { %>
FAIL
<% } %>
</body>
</html>

4. JSP to illustrate looping statements

<html>
<body>

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


HELLO WORLD
<% } %>
</body>
</html>

Mr. Ashok Kumar K | 9742024066 | [email protected]


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
7.6 Request String

The browser generates a user request string whenever the submit button is selected.
The user request string consists of:
1. URL
2. Query String

Example

Query String

JSP program should parse the query string to extract the values of fields that are to be processed by a JSP. A JSP can parse the query
string in two ways:

a) Using request.getParameter()
getParameter() method requires an argument, which is the name of the field whose value you want to retrieve.
Ex:
<%!
String uname = request.getParameter(“username”);
String pword = request.getParameter(“password”);
%>

b) Using request.getParameterValues()
Multi valued fields (such as checkboxes and select menus) can be read using getParameterValues() method.
It returns multiple values from the field specified as an argument to this method.
Ex:
<%!
String[] games = request.getParameterValues(“favgames”);
%>

Example Program

Here we will develop a sample JSP to read the parameters from the client request.

You would require writing these three files


 param.html
 readParam.jsp

Mr. Ashok Kumar K | 9742024066 | [email protected]


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
And, here is the structure of your dynamic web project created in Eclipse. Notice the placement of the above files in the project.

Step 1: Create param.html

<html>
<body>
<form action='readParam.jsp'>
Enter your name: <input type='text' name='username' /> <br />
<br /> Select your favourite games : <br/>
<select name='games' multiple=multiple>
<option value='Cricket'>Cricket</option>
<option value='Football'>Football</option>
<option value='Hockey'>Hockey</option>
<option value='Tennis'>Tennis</option>
</select> <br />
<br /> <input type='submit' value='Click me' />
</form>
</body>
</html>

Step 2: Create readParam.jsp

<html>
<body>
<%
String name = request.getParameter("username");
String games[] = request.getParameterValues("games");
%>

Welcome, <%= name %> <br/><br/>


Your favourite games are : <br/>
<%

Mr. Ashok Kumar K | 9742024066 | [email protected]


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
for (int i=0;i<games.length;i++) {
%>
<%= games[i] %> <br/>
<%
}
%>
</body>
</html>

Step 3:
Run param.html by entering the direct URL in the browser.

URL

A URL is divided into four parts:

 Protocol
It defines the rules that are used to transfer the request string from the browser to JSP program. Three commonly used
protocols are HTTP, HTTPS, and FTP
 Host
It is the internet protocol address (IP) or name of the server that contains the JSP program.
 Port
It is the port that the host monitors. If the port is not specified, it is defaulted to 80.
Whenever HTTP is used, the host will be monitoring the port 80
 Virtual path to JSP program
The server maps this virtual path to the physical path

Example for URL:

Mr. Ashok Kumar K | 9742024066 | [email protected]


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

7.7 User Sessions in JSP

As mentioned earlier, HTTP is a "stateless" protocol which means each time when a client retrieves a web page, the client opens a
separate connection to the web server and the server does not keep any record of previous client request. The question here is how
can we maintain the session between the client and a server?

As explained in the previous chapter, there are four possible ways to maintain the session between client and a server
 Cookies
 Hidden fields
 URL Rewriting
 HttpSession interface (session object)

7.7.1 Hidden Fields

A hidden field is a field in HTML form whose value isn’t displayed on the HTML page. You can assign a value to the hidden field in a
JSP program before the program sends the HTML page to the browser.
Consider a login screen which asks for username and password.
Here is how the session is tracked using hidden field:

 Upon submitting the form, the browser sends the username and password to the JSP program.
 The JSP program then validates the username and password and generates another dynamic HTML page. This newly
generated HTML page has a form that contains hidden field which is assigned a userID along with other fields as well.
 When the user submits the form in the new HTML page, the userID stored in the hidden field and other information on the form
are sent to the JSP program.
 This cycle continues where the JSP program processing the request string receives the userID as a parameter and then
passes the userID to the next dynamically built HTML page as a hidden field.
In this way, each HTML page and subsequent JSP program has access to userID and therefore can track the session.

7.7.2 Cookies

A cookie is a small piece of information created by a JSP program that is stored in the client’s hard disk by the browser. Cookies are
used to store various kind of information such as username, password, and user preferences, etc.

Sample JSP program to create a Cookie

<html>
<body>
<%!
String cName = "userID";
String cValue = "1VK06IS009";
Cookie myCookie = new Cookie (cName, cValue);

Mr. Ashok Kumar K | 9742024066 | [email protected]


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
%>
<%
response.addCookie(myCookie);
%>
</body>
</html>

Sample JSP program to read the Cookie

<html>
<body>
<%!
String cName = "userID";
String name;
String value;
int found = 0;
%>
<%
Cookie[] myCookies = request.getCookies();
for (int i=0;i<myCookies.length;i++) {
name = myCookies[i].getName();
if (name.equals(cName)) {
value = myCookies[i].getValue();
found = 1;
}
}
if (found==1) { %>
<p> Cookie Name: <%= cName %> </p>
<p> Cookie Value: <%= value %> </p>
<% } else { %>
<p> Cookie NOT FOUND </p>
<%>} %>
</body>
</html>

7.7.3 session object

A JSP database system is able to share information among JSP programs within a session 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. In addition to session ID, a session object is also
used to store other types of information called attributes.

Sample JSP program to create a session attribute

<html>
<body>
<%!
String attName = "userID";
String attValue = "1VK06IS009";
%>
<%
session.setAttribute(attName, attValue);
%>
</body>
</html>

Sample JSP program to read session attribute

Mr. Ashok Kumar K | 9742024066 | [email protected]


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

<html>
<body>
<%!
Enumeration<String> e;
%>
<%
e = session.getAttributeNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
String value = (String) session.getAttribute(name);
%>
<p> Attribute name : <%= name %></p>
<p> Attribute value : <%= value %></p>
<%
}
%>
</body>
</html>

Mr. Ashok Kumar K | 9742024066 | [email protected]


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

REMOTE METHOD INVOCATION


7.8 Basics

Definition and concepts

A Java object runs within a JVM. Likewise, a J2EE application runs within 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 different JVM by using Java RMI system.

RMI is used for remote communication between Java applications and components, both of which must be written in 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 the clients

RMI handles transmission of requests and provides the facility to load the object’s bytecode, which is referred to as dynamic code
loading

Following fig visualizes the RMI process

When 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 object’s methods.

7.9 The RMI Process

There are three steps necessary to make an object available to remote clients
1. Design an object
2. Compile the object

Mr. Ashok Kumar K | 9742024066 | [email protected]


www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
3. Make the object accessible to remote clients over the network

Designing an object

Besides defining 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.
In addition to methods that can be invoked by remote clients, the developer must also define other methods that support the processing
of client invoked methods. There are referred as server methods, while methods invoked by a client are called client methods.

Compile the object

Compilation of the object is a two-step process


 Compile the object using the javac compiler
This will create the byte codes for the objects.
 Compile the object using rmic compiler
This will create a stub for the object

Make the object available to remote client

It is done by loading the object into a server. Make sure the RMI remote object registry is running. If not, type the following at the
command line:
C:\> start rmiregistry

7.10 Server Side

Server side of RMI consists of a remote interfaces and methods. Remote interfaces provide the API for clients to access the methods.
Methods provide the business logic that fulfills a client’s request whenever the client remotely invokes them.

Example for Remote interface is shown below:

HelloInterface.java

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

Remote Object that implements the remote interface is shown below:

Hello.java

import java.rmi.*;
import java.rmi.server.*;

public class Hello extends UnicastRemoteObject


implements HelloInterface {
public String say() throws RemoteException {
System.out.println(“Hello World”);
}
}
Mr. Ashok Kumar K | 9742024066 | [email protected]
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.

Below program in the server side makes the Remote object available to the clients by binding it to the naming registry.

HelloServer.java

import java.rmi.Naming;

public class HelloServer {


public static void main (String[] argv) {
if (System.getSecurityManager() == null)
System.setSecurityManager(new RMISecurityManager());
try {
Naming.rebind("MyObj", new Hello ());
System.out.println ("Server is connected");
}
catch (Exception e) {
System.out.println ("Server not connected: " + e);
}
}
}

Clients can access the remote object by looking up the naming registry for the appropriate entry.

7.11 Client Side

Below example shows how a client can lookup the naming registry to get an instance of the remote object. It also illustrates how a client
can use the remote object to call its methods.

HelloClient.java

import java.rmi.Naming;

public class HelloClient {


public static void main(String[] argv) {
if (System.getSecurityManager() == null)
System.setSecurityManager(new RMISecurityManager());
try {
HelloInterface hello = (HelloInterface) Naming
.lookup("//192.168.10.201/MyObj");
System.out.println(hello.say());
} catch (Exception e) {
System.out.println("HelloClient exception: " + e);
}
}
}

Mr. Ashok Kumar K | 9742024066 | [email protected]

You might also like