Java Server Pages 416
Java Server Pages 416
That is to say, anything that can be done using JSPs can also be accomplished using Java servlets.
However, it is important to note that servlets and JSPs are complementary technologies, NOT
replacement of each other. Servlet can be viewed as "HTML inside Java", which is better for
implementing business logic - as it is Java dominant. JSP, on the other hand, is "Java inside HTML",
which is superior for creating presentation - as it is HTML dominant. In a typical Model-View-
Control (MVC) application, servlets are often used for the Controller (C), which involves complex
programming logic. JSPs are often used for the View (V), which mainly deals with presentation. The
Model (M) is usually implemented using JavaBean or EJB.
JSPs, like servlets, are server-side programs run inside a HTTP server. To support JSP/servlet, a
Java-capable HTTP server is required. Tomcat Server (@ http://tomcat.apache.org) is the official
reference implementation (RI) for Java servlet and JSP, provided free by Apache (@
http://www.apache.org) - an open-source software foundation.
JSP life cycle is also managed by container. Usually every web container that contains servlet
container also contains JSP container for managing JSP pages. JSP pages life cycle phases are:
Translation - JSP pages doesn’t look like normal java classes, actually JSP container parse
the JSP pages and translate them to generate corresponding servlet source code. If JSP file
name is home.jsp, usually its named as home_jsp.java.
Compilation - If the translation is successful, then container compiles the generated servlet
source file to generate class file.
Class Loading - Once JSP is compiled as servlet class, its lifecycle is similar to servlet and it
gets loaded into memory.
1
Instance Creation - After JSP class is loaded into memory, its object is instantiated by the
container.
Initialization - The JSP class is then initialized and it transforms from a normal class to
servlet. After initialization, ServletConfig and ServletContext objects become accessible to
JSP class.
Request Processing - For every client request, a new thread is spawned with ServletRequest
and ServletResponse to process and generate the HTML response.
Destroy - Last phase of JSP life cycle where it’s unloaded into memory.
1. jspInit() declared in JspPage interface. This method is called only once in JSP lifecycle to
initialize config params.
2. _jspService(HttpServletRequest request, HttpServletResponse response) declared in
HttpJspPage interface and response for handling client requests.
3. jspDestroy() declared in JspPage interface to unload the JSP from memory.
Let's begin with a simple JSP example. We shall use the webapp called "hello" that we have created
in our earlier exercise. Use a programming text editor to enter the following HTML/JSP codes and
save as "first.jsp" (the file type of ".jsp" is mandatory) in your webapp (web context) home
directory (i.e., "webapps\hello".
1 <html>
2 <head><title>First JSP</title></head>
3 <body>
4 <%
5 double num = Math.random();
6 if (num > 0.95) {
7 %>
8 <h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
9 <%
10 } else {
11 %>
12 <h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
13 <%
14 }
15 %>
16 <a href="<%= request.getRequestURI() %>"><h3>Try Again</h3></a>
17 </body>
18 </html>
To execute the JSP script: Simply start your Tomcat server and use a browser to issue an URL to
browse the JSP page (i.e., http://localhost:8080/hello/first.jsp).
From your browser, choose the "View Source" option to check the response message. It should be
either of the followings depending on the random number generated.
<html>
<h2>You'll have a luck day!</h2>
2
<p>(0.987)</p>
<a href="first.jsp"><h3>Try Again</h3></a>
</html>
<html>
<h2> Well, life goes on ... </h2>
<p>(0.501)</p>
<a href="first.jsp"><h3>Try Again</h3></a>
</html>
It is important to note that the client is not able to "view" the original JSP script (otherwise, you may
have security exposure), but merely the result generated by the script.
Explanations
1. A JSP script is a regular HTML page containing Java programs. Recall that JSP is "Java
inside HTML" (whereas servlet is "HTML inside Java"). The Java statements are enclosed by
<% ... %> (called JSP scriptlet) or <%= ... %> (called JSP expression).
2. JSP Scriptlet <% ... %> is used to include Java statements.
3. JSP Expression <%= ... %> is used to evaluate a single Java expression and display its result.
4. The method request.getRequestURI() is used to retrieve the URL of the current page.
This is used in the anchor tag <a> for refreshing the page to obtain another random number.
When a JSP is first accessed, Tomcat converts the JSP into a servlet; compile the servlet, and execute
the servlet. Check out the generated servlet for "first.jsp", and study the JSP-to-servlet
conversion. Look under Tomcat's "work\Catalina\localhost\hello" for "first_jsp.java".
The relevant part of the generated servlet is extracted as follows (with some simplifications):
1 out.write("<html>\r\n ");
2 double num = Math.random();
3 if (num > 0.95) {
4 out.write("<h2>You will have a luck day!");
5 out.write("</h2><p>(");
6 out.print( num );
7 out.write(")</p>\r\n");
8 } else {
9 out.write("\r\n ");
10 out.write("<h2>Well, life goes on ... ");
11 out.write("</h2><p>(");
12 out.print( num );
13 out.write(")</p>\r\n ");
14 }
15 out.write("<a href=\"");
16 out.print( request.getRequestURI() );
17 out.write("\">");
18 out.write("<h3>Try Again</h3></a>\r\n");
19 out.write("</html>\r\n");
Explanation
1. The HTML statements are written out as part of the response via out.write(), as "it is".
2. The JSP scriptlets <% ... %> are kept, as "it is", in the converted servlet as the program logic.
3
3. The JSP expressions <%= ... %> are placed inside a out.print(). Hence, the expression
will be evaluated, and the result of the evaluation written out as part of the response message.
Compare the JSP script and the internally generated servlet, you shall understand that servlet is
"HTML inside Java", whereas JSP is "Java inside HTML".
Subsequent accesses to the same JSP will be much faster, because they will be re-directed to the
converted and compiled servlet directly (no JSP-to-servlet conversion and servlet compilation
needed again), unless the JSP has been modified.
That is to say, anything that can be done using JSPs can also be accomplished using Java servlets.
However, it is important to note that servlets and JSPs are complementary technologies, NOT
replacement of each other. Servlet can be viewed as "HTML inside Java", which is better for
implementing business logic - as it is Java dominant. JSP, on the other hand, is "Java inside HTML",
which is superior for creating presentation - as it is HTML dominant. In a typical Model-View-
Control (MVC) application, servlets are often used for the Controller (C), which involves complex
programming logic. JSPs are often used for the View (V), which mainly deals with presentation. The
Model (M) is usually implemented using JavaBean or EJB.
JSPs, like servlets, are server-side programs run inside a HTTP server. To support JSP/servlet, a
Java-capable HTTP server is required. Tomcat Server (@ http://tomcat.apache.org) is the official
reference implementation (RI) for Java servlet and JSP, provided free by Apache (@
http://www.apache.org) - an open-source software foundation.
JSP life cycle is also managed by container. Usually every web container that contains servlet
container also contains JSP container for managing JSP pages. JSP pages life cycle phases are:
Translation - JSP pages doesn’t look like normal java classes, actually JSP container parse
the JSP pages and translate them to generate corresponding servlet source code. If JSP file
name is home.jsp, usually its named as home_jsp.java.
Compilation - If the translation is successful, then container compiles the generated servlet
source file to generate class file.
Class Loading - Once JSP is compiled as servlet class, its lifecycle is similar to servlet and it
gets loaded into memory.
Instance Creation - After JSP class is loaded into memory, its object is instantiated by the
container.
Initialization - The JSP class is then initialized and it transforms from a normal class to
servlet. After initialization, ServletConfig and ServletContext objects become accessible to
JSP class.
Request Processing - For every client request, a new thread is spawned with ServletRequest
and ServletResponse to process and generate the HTML response.
Destroy - Last phase of JSP life cycle where it’s unloaded into memory.
4
JSP lifecycle methods are:
4. jspInit() declared in JspPage interface. This method is called only once in JSP lifecycle to
initialize config params.
5. _jspService(HttpServletRequest request, HttpServletResponse response) declared in
HttpJspPage interface and response for handling client requests.
6. jspDestroy() declared in JspPage interface to unload the JSP from memory.
Let's begin with a simple JSP example. We shall use the webapp called "hello" that we have created
in our earlier exercise. Use a programming text editor to enter the following HTML/JSP codes and
save as "first.jsp" (the file type of ".jsp" is mandatory) in your webapp (web context) home
directory (i.e., "webapps\hello".
1 <html>
2 <head><title>First JSP</title></head>
3 <body>
4 <%
5 double num = Math.random();
6 if (num > 0.95) {
7 %>
8 <h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
9 <%
10 } else {
11 %>
12 <h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
13 <%
14 }
15 %>
16 <a href="<%= request.getRequestURI() %>"><h3>Try Again</h3></a>
17 </body>
18 </html>
To execute the JSP script: Simply start your Tomcat server and use a browser to issue an URL to
browse the JSP page (i.e., http://localhost:8080/hello/first.jsp).
From your browser, choose the "View Source" option to check the response message. It should be
either of the followings depending on the random number generated.
<html>
<h2>You'll have a luck day!</h2>
<p>(0.987)</p>
<a href="first.jsp"><h3>Try Again</h3></a>
</html>
<html>
<h2> Well, life goes on ... </h2>
<p>(0.501)</p>
<a href="first.jsp"><h3>Try Again</h3></a>
</html>
It is important to note that the client is not able to "view" the original JSP script (otherwise, you may
have security exposure), but merely the result generated by the script.
5
Explanations
5. A JSP script is a regular HTML page containing Java programs. Recall that JSP is "Java
inside HTML" (whereas servlet is "HTML inside Java"). The Java statements are enclosed by
<% ... %> (called JSP scriptlet) or <%= ... %> (called JSP expression).
6. JSP Scriptlet <% ... %> is used to include Java statements.
7. JSP Expression <%= ... %> is used to evaluate a single Java expression and display its result.
8. The method request.getRequestURI() is used to retrieve the URL of the current page.
This is used in the anchor tag <a> for refreshing the page to obtain another random number.
When a JSP is first accessed, Tomcat converts the JSP into a servlet; compile the servlet, and execute
the servlet. Check out the generated servlet for "first.jsp", and study the JSP-to-servlet
conversion. Look under Tomcat's "work\Catalina\localhost\hello" for "first_jsp.java".
The relevant part of the generated servlet is extracted as follows (with some simplifications):
1 out.write("<html>\r\n ");
2 double num = Math.random();
3 if (num > 0.95) {
4 out.write("<h2>You will have a luck day!");
5 out.write("</h2><p>(");
6 out.print( num );
7 out.write(")</p>\r\n");
8 } else {
9 out.write("\r\n ");
10 out.write("<h2>Well, life goes on ... ");
11 out.write("</h2><p>(");
12 out.print( num );
13 out.write(")</p>\r\n ");
14 }
15 out.write("<a href=\"");
16 out.print( request.getRequestURI() );
17 out.write("\">");
18 out.write("<h3>Try Again</h3></a>\r\n");
19 out.write("</html>\r\n");
Explanation
4. The HTML statements are written out as part of the response via out.write(), as "it is".
5. The JSP scriptlets <% ... %> are kept, as "it is", in the converted servlet as the program logic.
6. The JSP expressions <%= ... %> are placed inside a out.print(). Hence, the expression
will be evaluated, and the result of the evaluation written out as part of the response message.
Compare the JSP script and the internally generated servlet, you shall understand that servlet is
"HTML inside Java", whereas JSP is "Java inside HTML".
Subsequent accesses to the same JSP will be much faster, because they will be re-directed to the
converted and compiled servlet directly (no JSP-to-servlet conversion and servlet compilation
needed again), unless the JSP has been modified.
6
Facts About JSP
Here are some facts about JSP (JavaServer Pages):
JSP stands for Java Server Pages.
JSP is a technology to build dynamic web applications.
JSP is a part of Java Enterprise Edition (Java EE).
JSP is similar to HTML pages, but they also contain Java code executed on the server side.
Server-side scripting means the JSP code is processed on the web server rather than the client
machine.
A JSP page is a file with a ".jsp" extension that can contain a combination of HTML
Tags and JSP codes.
To create a web page, JSP uses a combination of HTML or XML markup, JSP tags,
expressions, and Java code.
JSP tags begin with <% and end with %>.
JSP expressions are used to insert dynamic content into the page and begin with <%= and end
with %>.
JSP can use JavaBeans to store and retrieve data.
JSP requires a Java development environment and a Java Servlet Container such as Apache
Tomcat or Jetty.
JSP is widely used in the industry for creating enterprise web applications.
JSP is an improved extended version of Servlet technology.
Advantages of JSP
Some advantages of JSP (JavaServer Pages) include the following:
JSP offers an efficient and more straightforward approach to coding dynamic web pages.
JSP provides a wide variety of pre-built tags and custom tags, which can be used to add
functionality to web pages
JSP allows developers to separate the presentation of the web page from the logic and
processing, making it easier to maintain the web application.
Web Container (or application server like tomcat) handles changes when changes are done in
the JSP code and does not need recompilation.
JSP allows developers to follow the Model-View-Controller (MVC) design pattern, which
separates a web application's presentation, logic, and data. This makes it easier to create
scalable and maintainable web applications.
JSP is commonly used with other Java technologies, such as JavaServer Faces (JSF), which
provides a framework for building web applications, making the development process more
streamlined.
Provides good security features like session tracking, user authentication, and access
restriction.
JSP can use standard Java code and libraries, which increases the potential for code reuse.
Advantages of JSP than Servlet
JSP is considered to be better than servlet; there are many reasons why JSP is more beneficial than
servlet:
JSP pages allow web designers to work with HTML or XML markup, while Servlets require
a deeper understanding of Java.
JSP doesn't need additional files such as java class files, web.xml, etc.
JSPs are compiled into servlets by the JSP engine, which improves performance compared to
interpreting servlets at runtime.
Many IDEs and tools are available for developing JSPs, which can make development
quicker and easier compared to servlets.
JSPs are more accessible to debug and troubleshoot than servlets because they have better
error reporting and debugging facilities.
7
Revisit Java Servlets
A typical Java servlet (as shown below) contains three kinds of methods: init(), destroy(), and
one or more service() methods such as doGet() and doPost(). init() runs when the servlet is
loaded. destroy() runs when the servlet is unloaded. service() runs once per HTTP request. The
service() methods takes two arguments: request and response, corresponding to the HTTP
request and response messages respectively. A PrintWriter called out is created for writing out the
response to the network.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications. This
means that JSP can play a part in the simplest applications to the most complex and demanding.
JSP Processing
The following steps explain how the web server creates the Webpage using JSP −
i. As with a normal page, your browser sends an HTTP request to the web server.
8
ii. The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP
engine. This is done by using the URL or JSP page which ends with .jsp instead of .html.
iii. The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements and all
JSP elements are converted to Java code. This code implements the corresponding dynamic
behavior of the page.
iv. The JSP engine compiles the servlet into an executable class and forwards the original request to
a servlet engine.
v. A part of the web server called the servlet engine loads the Servlet class and executes it. During
execution, the servlet produces an output in HTML format. The output is furthur passed on to
the web server by the servlet engine inside an HTTP respons
vi. The web server forwards the HTTP response to your browser in terms of static HTML content.
vii. Finally, the web browser handles the dynamically-generated HTML page inside the HTTP
response exactly as if it were a static page.
All the above mentioned steps can be seen in the following diagram −
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and whether
the modification date on the JSP is older than the servlet. If the JSP is older than its generated servlet,
the JSP container assumes that the JSP hasn't changed and that the generated servlet still matches the
JSP's contents. This makes the process more efficient than with the other scripting languages (such
as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having to be a Java
programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular
servlet.
In this chapter, we will discuss the lifecycle of JSP. The key to understanding the low-level
functionality of JSP is to understand the simple life cycle they follow.
A JSP life cycle is defined as the process from its creation till the destruction. This is similar to a
servlet life cycle with an additional step which is required to compile a JSP into servlet.
JSP and servlets typically work together, especially in older Java web applications. From a coding
perspective, the most obvious difference between JSP and servlets is that with servlets you write Java
9
code and then embed client-side markup (like HTML) into that code. With JSP, you start with the
client-side script or markup, then embed JSP tags to connect your page to the Java back end.
Think of JSP as a way to write markup with ability to interact with the back end. Usually, markup
like HTML is sent to the client where it interacts with the back-end server via JavaScript. JSP pre-
processes the HTML with special commands to access and use server capabilities, then sends that
compiled page to the client.
A simple JSP page consists of HTML markup embedded with JSP tags. JSP files have the .jsp
extension. The JSP server (also called a JSP container) is configured to direct an HTTP request to a
specific JSP page, which is then responsible for rendering an HTTP response.
When the request arrives, the file is processed on the server and the HTML is rendered as the
application view, a web page. The embedded JSP tags will be used to call server-side code and data.
The ultimate product of the JSP is vanilla HTML that the client browser can understand as-is. The
diagram in Figure 1 shows the interaction between HTML, JSP, and the web application server.
IDG
Figure 1. Overview of a Jakarta Server Pages (JSP) page in a web application.
Listing 1 shows a simple JSP page.
<html>
<body>
</body></html>
Here, you see a block of HTML that includes a JSP expression, which is an instruction to the Java
server written using Expression Language (EL). In the expression ${2 * 2}, the ${} is JSP syntax for
interpolating code into HTML. The dollar sign with curly braces tells the JSP processor: “Hold on
for a second, we’re about to start talking about something special you need to take care of." When
10
executed, the JSP page will output the results of executing whatever is inside the expression. In this
case, the output will be the number 4.
JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the
page. If the page has never been compiled, or if the JSP has been modified since it was last compiled,
the JSP engine compiles the page.
The compilation process involves three steps −
Parsing the JSP.
Turning the JSP into a servlet.
Compiling the servlet.
JSP Initialization
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you
need to perform JSP-specific initialization, override the jspInit() method −
public void jspInit(){
// Initialization code...}
Typically, initialization is performed only once and as with the servlet init method, you generally
initialize database connections, open files, and create lookup tables in the jspInit method.
JSP Execution
This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine
invokes the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its
parameters as follows −
void _jspService(HttpServletRequest request, HttpServletResponse response) {
11
// Service handling code...}
The _jspService() method of a JSP is invoked on request basis. This is responsible for generating the
response for that request and this method is also responsible for generating responses to all seven of
the HTTP methods, i.e, GET, POST, DELETE, etc.
JSP Cleanup
The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a
container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override
jspDestroy when you need to perform any cleanup, such as releasing database connections or closing
open files.
The jspDestroy() method has the following form −
public void jspDestroy() {
// Your cleanup code goes here.}
Elements of JSP
The elements of JSP have been described below −
To simplify the access of the HTTP request and response messages, JSP has pre-defined the
following variables:
JSP comments <%-- comments --%> are ignored by the JSP engine. For example,
<body>
12
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body> </html>
The above code will generate the following result −
A Test of Comments
There are a small number of special constructs you can use in various cases to insert comments or
characters that would otherwise be treated specially. Here's a summary −
S.No. Syntax & Purpose
<\%
3
Represents static <% literal.
%\>
4
Represents static %> literal.
\'
5
A single quote in an attribute that uses single quotes.
\"
6
A double quote in an attribute that uses double quotes.
Note that HTML comment is <!-- comments -->. JSP expression within the HTML comment will
be evaluated. For example,
<!-- HTML comments here <%= Math.random() %> more comments -->
JSP scriptlets allow you to do more complex operations than inserting a single Java expression (with
the JSP expression). JSP scriptlets let you insert an arbitrary sequence of valid Java statement(s) into
the service() method of the converted servlet. All the Java statements in a scriptlet are to be
terminated with a semi-colon. A scriptlet can contain any number of JAVA language statements,
variable or method declarations, or expressions that are valid in the page scripting language.
13
</jsp:scriptlet>
Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the
simple and first example for JSP −
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body></html>
NOTE − Assuming that Apache Tomcat is installed in C:\apache-tomcat-7.0.2 and your
environment is setup as per environment setup tutorial.
Let us keep the above code in JSP file hello.jsp and put this file in C:\apache-
tomcat7.0.2\webapps\ROOT directory. Browse through the same using
URL http://localhost:8080/hello.jsp. The above code will generate the following result −
Example2:
<%
String author = request.getParameter("author");
if (author != null && !author.equals(""))) {
%>
<p>You have choose author <%= author %></p>
<%
}
%>
In the converted servlet, the above will be inserted into the service() method as follows:
Notice that the Java codes inside a scriptlet are inserted exactly as they are written, and used as the
programming logic. The HTML codes are passed to an out.write() method and written out as part
of the response message.
14
3.JSP Declarations
A declaration declares one or more variables or methods that you can use in Java code later in the
JSP file. You must declare the variable or method before you use it in the JSP file.
Following is the syntax for JSP Declarations −
<%! declaration; [ declaration; ]+ ... %>
You can write the XML equivalent of the above syntax as follows −
<jsp:declaration>
code fragment
</jsp:declaration>
Following is an example for JSP Declarations −
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
A JSP expression element contains a scripting language expression that is evaluated, converted to a
String, and inserted where the expression appears in the JSP file.
Because the value of an expression is converted to a String, you can use an expression within a line
of text, whether or not it is tagged with HTML, in a JSP file.
The expression element can contain any expression that is valid according to the Java Language
Specification but you cannot use a semicolon to end an expression.
Following is the syntax of JSP Expression −
<%= expression %>
JSP Expression can be used to insert a single Java expression directly into the response
message. This expression will be placed inside a out.print() method. Hence, the expression will
be evaluated and printed out as part of the response message. Any valid Java expression can be
used. There is no semi-colon at the end of the expression. For examples:
You can use the pre-defined variables, such as request, in the expressions. For examples:
15
You can write the XML equivalent of the above syntax as follows −
<jsp:expression>
expression</jsp:expression>
Following example shows a JSP Expression −
<html>
<head><title>A Comment Test</title></head>
<body>
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
</body> </html>
The above code will generate the following result −
Today's date: 11-Sep-2010 21:24:25
Directives supply directions and messages to a JSP container. The directives provide global
information about the entire page of JSP. Hence, they are an essential part of the JSP code. These
special instructions are used for translating JSP to servlet code. In this chapter, you will learn about
the different components of directives in detail.In JSP's life cycle phase, the code must be converted
to a servlet that deals with the translation phase. They provide commands or directions to the
container on how to deal with and manage certain JSP processing portions. Directives can contain
several attributes that are separated by a comma and act as key-value pairs. In JSP, directives are
described with a pair of <%@ .... %> tags.
JSP directives provide instructions to the JSP engine. The syntax of the JSP directive is:
<%@ directive_name
attribute1="value1"
attribute2="value2"
......
attributeN="valueN" %>
The "page" directive lets you import classes and customize the page properties. For examples,
16
JSP include Directive
The "include" directive lets you include another file(s) at the time when the JSP page is compiled
into a servlet. You can include any JSP files, or static HTML files. You can use include directive to
include navigation bar, copyright statement, logo, etc. on every JSP pages. The syntax is:
For example:
A JSP directive affects the overall structure of the servlet class. It usually has the following form −
<%@ directive attribute="value" %>
There are three types of directive tag −
S.No. Directive & Description
jsp:include
1
Includes a file at the time the page is requested.
jsp:useBean
2
Finds or instantiates a JavaBean.
3 jsp:setProperty
17
Sets the property of a JavaBean.
jsp:getProperty
4
Inserts the property of a JavaBean into the output.
jsp:forward
5
Forwards the requester to a new page.
jsp:plugin
6 Generates browser-specific code that makes an OBJECT or EMBED tag for the Java
plugin.
jsp:element
7
Defines XML elements dynamically.
jsp:attribute
8
Defines dynamically-defined XML element's attribute.
jsp:body
9
Defines dynamically-defined XML element's body.
jsp:text
10
Used to write template text in JSP pages and documents.
We would explain JSP actions in a separate chapter JSP - Actions
JSP Implicit Objects
JSP supports nine automatically defined variables, which are also called implicit objects. These
variables are −
S.No. Object & Description
request
1
This is the HttpServletRequest object associated with the request.
response
2
This is the HttpServletResponse object associated with the response to the client.
out
3
This is the PrintWriter object used to send output to the client.
session
4
This is the HttpSession object associated with the request.
application
5
This is the ServletContext object associated with the application context.
config
6
This is the ServletConfig object associated with the page.
18
pageContext
7 This encapsulates use of server-specific features like higher
performance JspWriters.
page
8 This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.
Exception
9
The Exception object allows the exception data to be accessed by designated JSP.
We would explain JSP Implicit Objects in a separate chapter JSP - Implicit Objects.
Control-Flow Statements
You can use all the APIs and building blocks of Java in your JSP programming including decision-
making statements, loops, etc.
Decision-Making Statements
The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line with
HTML text included between the Scriptlet tags.
<%! int day = 3; %> <html>
<head><title>IF...ELSE Example</title></head>
<body>
<% if (day == 1 || day == 7) { %>
<p> Today is weekend</p>
<% } else { %>
<p> Today is not weekend</p>
<% } %>
</body> </html>
The above code will generate the following result −
Today is not weekend
Now look at the following switch...case block which has been written a bit differentlty
using out.println() and inside Scriptletas −
<%! int day = 3; %> <html>
<head><title>SWITCH...CASE Example</title></head>
<body>
<%
switch(day) {
case 0:
out.println("It\'s Sunday.");
break;
case 1:
out.println("It\'s Monday.");
break;
case 2:
out.println("It\'s Tuesday.");
break;
case 3:
out.println("It\'s Wednesday.");
19
break;
case 4:
out.println("It\'s Thursday.");
break;
case 5:
out.println("It\'s Friday.");
break;
default:
out.println("It's Saturday.");
}
%>
</body> </html>
The above code will generate the following result −
It's Wednesday.
Loop Statements
You can also use three basic types of looping blocks in Java: for, while, and do…while blocks in
your JSP programming.
Let us look at the following for loop example −
<%! int fontSize; %> <html>
<head><title>FOR LOOP Example</title></head>
<body>
<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>
<font color = "green" size = "<%= fontSize %>">
JSP Tutorial
</font><br />
<%}%>
</body> </html>
Above example can be written using the while loop as follows −
<%! int fontSize; %> <html>
<head><title>WHILE LOOP Example</title></head>
<body>
<%while ( fontSize <= 3){ %>
<font color = "green" size = "<%= fontSize %>">
JSP Tutorial
</font><br />
<%fontSize++;%>
<%}%>
</body> </html>
The above code will generate the following result −
JSP Operators
JSP supports all the logical and arithmetic operators supported by Java. Following table lists out all
the operators with the highest precedence appear at the top of the table, those with the lowest appear
at the bottom.
JSP ACTIONS
20
These actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate
HTML for the Java plugin.
There is only one syntax for the Action element, as it conforms to the XML standard −
<jsp:action_name attribute = "value" />
Action elements are basically predefined functions. The following table lists out the available JSP
actions −
S.No. Syntax & Purpose
jsp:include
1
Includes a file at the time the page is requested.
jsp:useBean
2
Finds or instantiates a JavaBean.
jsp:setProperty
3
Sets the property of a JavaBean.
jsp:getProperty
4
Inserts the property of a JavaBean into the output.
jsp:forward
5
Forwards the requester to a new page.
jsp:plugin
6 Generates browser-specific code that makes an OBJECT or EMBED tag for the Java
plugin.
jsp:element
7
Defines XML elements dynamically.
jsp:attribute
8
Defines dynamically-defined XML element's attribute.
jsp:body
9
Defines dynamically-defined XML element's body.
jsp:text
10
Used to write template text in JSP pages and documents.
Common Attributes
There are two attributes that are common to all Action elements: the id attribute and
the scope attribute.
Id attribute
The id attribute uniquely identifies the Action element, and allows the action to be referenced inside
the JSP page. If the Action creates an instance of an object, the id value can be used to reference it
through the implicit object PageContext.
Scope attribute
21
This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute
are directly related, as the scope attribute determines the lifespan of the object associated with the id.
The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application.
The <jsp:include> Action
This action lets you insert files into the page being generated. The syntax looks like this −
<jsp:include page = "relative URL" flush = "true" />
Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet,
this action inserts the file at the time the page is requested.
Following table lists out the attributes associated with the include action −
S.No. Attribute & Description
page
1
The relative URL of the page to be included.
flush
2 The boolean attribute determines whether the included resource has its buffer flushed
before it is included.
Example
Let us define the following two files (a)date.jsp and (b) main.jsp as follows −
Following is the content of the date.jsp file −
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
Following is the content of the main.jsp file −
<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:include page = "date.jsp" flush = "true" />
</center>
</body></html>
Let us now keep all these files in the root directory and try to access main.jsp. You will receive the
following output −
22
S.No. Attribute & Description
class
1
Designates the full package name of the bean.
type
2
Specifies the type of the variable that will refer to the object.
beanName
3 Gives the name of the bean as specified by the instantiate () method of the
java.beans.Beans class.
Let us now discuss the jsp:setProperty and the jsp:getProperty actions before giving a valid
example related to these actions.
The <jsp:setProperty> Action
The setProperty action sets the properties of a Bean. The Bean must have been previously defined
before this action. There are two basic ways to use the setProperty action −
You can use jsp:setProperty after, but outside of a jsp:useBean element, as given below −
<jsp:useBean id = "myName" ... />
...
<jsp:setProperty name = "myName" property = "someProperty" .../>
In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an
existing bean was found.
A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element,
as given below −
<jsp:useBean id = "myName" ... >
...
<jsp:setProperty name = "myName" property = "someProperty" .../></jsp:useBean>
Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was
found.
Following table lists out the attributes associated with the setProperty action −
S.No. Attribute & Description
name
1 Designates the bean the property of which will be set. The Bean must have been
previously defined.
property
Indicates the property you want to set. A value of "*" means that all request
2
parameters whose names match bean property names will be passed to the
appropriate setter methods.
value
3 The value that is to be assigned to the given property. The the parameter's value is
null, or the parameter does not exist, the setProperty action is ignored.
param
4
The param attribute is the name of the request parameter whose value the property is
23
to receive. You can't use both value and param, but it is permissible to use neither.
The <jsp:getProperty> Action
The getProperty action is used to retrieve the value of a given property and converts it to a string,
and finally inserts it into the output.
The getProperty action has only two attributes, both of which are required. The syntax of the
getProperty action is as follows −
<jsp:useBean id = "myName" ... />
...<jsp:getProperty name = "myName" property = "someProperty" .../>
Following table lists out the required attributes associated with the getProperty action −
S.No. Attribute & Description
name
1 The name of the Bean that has a property to be retrieved. The Bean must have been
previously defined.
property
2
The property attribute is the name of the Bean property to be retrieved.
Example
Let us define a test bean that will further be used in our example −
/* File: TestBean.java */package action;
public class TestBean {
private String message = "No message specified";
<head>
<title>Using JavaBeans in JSP</title>
</head>
<body>
<center>
<h2>Using JavaBeans in JSP</h2>
<jsp:useBean id = "test" class = "action.TestBean" />
<jsp:setProperty name = "test" property = "message"
value = "Hello JSP..." />
24
<p>Got message....</p>
<jsp:getProperty name = "test" property = "message" />
</center>
</body></html>
Let us now try to access main.jsp, it would display the following result −
Got message....
Hello JSP...
page
1 Should consist of a relative URL of another resource such as a static page, another
JSP page, or a Java Servlet.
Example
Let us reuse the following two files (a) date.jsp and (b) main.jsp as follows −
Following is the content of the date.jsp file −
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
Following is the content of the main.jsp file −
<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:forward page = "date.jsp" />
</center>
</body></html>
Let us now keep all these files in the root directory and try to access main.jsp. This would display
result something like as below.
Here it discarded the content from the main page and displayed the content from forwarded page
only.
25
If the needed plugin is not present, it downloads the plugin and then executes the Java component.
The Java component can be either an Applet or a JavaBean.
The plugin action has several attributes that correspond to common HTML tags used to format Java
components. The <param> element can also be used to send parameters to the Applet or Bean.
Following is the typical syntax of using the plugin action −
<jsp:plugin type = "applet" codebase = "dirname" code = "MyApplet.class"
width = "60" height = "80">
<jsp:param name = "fontcolor" value = "red" />
<jsp:param name = "background" value = "black" />
<jsp:fallback>
Unable to initialize Java Plugin
</jsp:fallback>
</jsp:plugin>
You can try this action using some applet if you are interested. A new element,
the <fallback> element, can be used to specify an error string to be sent to the user in case the
component fails.
The <jsp:element> Action
The <jsp:element>, <jsp:attribute> and <jsp:body> actions are used to define XML elements
dynamically. The word dynamically is important, because it means that the XML elements can be
generated at request time rather than statically at compile time.
Following is a simple example to define XML elements dynamically −
<%@page language = "java" contentType = "text/html"%><html xmlns =
"http://www.w3c.org/1999/xhtml"
xmlns:jsp = "http://java.sun.com/JSP/Page">
<body>
<jsp:element name = "xmlElement">
<jsp:attribute name = "xmlElementAttr">
Value for the attribute
</jsp:attribute>
<jsp:body>
Body for XML element
</jsp:body>
</jsp:element>
</body></html>
This would produce the following HTML code at run time −
<html xmlns = "http://www.w3c.org/1999/xhtml" xmlns:jsp = "http://java.sun.com/JSP/Page">
<head><title>Generate XML Element</title></head>
26
<body>
<xmlElement xmlElementAttr = "Value for the attribute">
Body for XML element
</xmlElement>
</body></html>
The <jsp:text> Action
The <jsp:text> action can be used to write the template text in JSP pages and documents. Following
is the simple syntax for this action −
<jsp:text>Template data</jsp:text>
The body of the template cannot contain other elements; it can only contain text and EL expressions
(Note − EL expressions are explained in a subsequent chapter). Note that in XML files, you cannot
use expressions such as ${whatever > 0}, because the greater than signs are illegal. Instead, use
the gt form, such as ${whatever gt 0} or an alternative is to embed the value in a CDATA section.
<jsp:text><![CDATA[<br>]]></jsp:text>
If you need to include a DOCTYPE declaration, for instance for XHTML, you must also use
the <jsp:text> element as follows −
<jsp:text><![CDATA[<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"DTD/xhtml1-strict.dtd">]]></jsp:text>
<head><title>jsp:text action</title></head>
<body>
<books><book><jsp:text>
Welcome to JSP Programming
</jsp:text></book></books>
</body></html>
Try the above example with and without <jsp:text> action
In this chapter, we will discuss Client Request in JSP. When a browser requests for a Webpage, it
sends a lot of information to the web server. This information cannot be read directly because this
information travels as a part of header of HTTP request. You can check HTTP Protocol for more
information on this.
Following table lists out the important header information which comes from the browser. This
information is frequently used in web programming −
S.No. Header & Description
Accept
1 This header specifies the MIME types that the browser or other clients can handle.
Values of image/png or image/jpeg are the two most common possibilities.
Accept-Charset
2 This header specifies the character sets that the browser can use to display the
information. For example, ISO-8859-1.
Accept-Encoding
3 This header specifies the types of encodings that the browser knows how to handle.
Values of gzip or compress are the two most common possibilities.
4 Accept-Language
27
This header specifies the client's preferred languages in case the servlet can produce
results in more than one language. For example en, en-us, ru, etc.
Authorization
5 This header is used by clients to identify themselves when accessing password-
protected webpages.
Connection
This header indicates whether the client can handle persistent HTTP connections.
6 Persistent connections permit the client or other browser to retrieve multiple files
with a single request. A value of Keep-Alive means that persistent connections
should be used.
Content-Length
7 This header is applicable only to POST requests and gives the size of the POST data
in bytes.
Cookie
8
This header returns cookies to servers that previously sent them to the browser.
Host
9
This header specifies the host and port as given in the original URL.
If-Modified-Since
This header indicates that the client wants the page only if it has been changed after
10
the specified date. The server sends a code, 304 which means Not Modified header
if no newer result is available.
If-Unmodified-Since
11 This header is the reverse of If-Modified-Since; it specifies that the operation should
succeed only if the document is older than the specified date.
Referer
This header indicates the URL of the referring webpages. For example, if you are at
12
Webpage 1 and click on a link to Webpage 2, the URL of Webpage 1 is included in
the Referer header when the browser requests Webpage 2.
User-Agent
13 This header identifies the browser or other client making the request and can be used
to return different content to different types of browsers.
The HttpServletRequest Object
The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a
client requests a page, the JSP engine creates a new object to represent that request.
The request object provides methods to get HTTP header information including form data, cookies,
HTTP methods, etc.
Following table lists out the important methods that can be used to read HTTP header in your JSP
program. These methods are available with HttpServletRequest object which represents client request
to webserver.
28
S.No. Method & Description
Cookie[] getCookies()
1
Returns an array containing all of the Cookie objects the client sent with this request.
Enumeration getAttributeNames()
2 Returns an Enumeration containing the names of the attributes available to this
request.
Enumeration getHeaderNames()
3
Returns an enumeration of all the header names this request contains.
Enumeration getParameterNames()
4 Returns an enumeration of String objects containing the names of the parameters
contained in this request.
HttpSession getSession()
5 Returns the current session associated with the this request, or if the request does not
have a session, creates one.
Locale getLocale()
7 Returns the preferred Locale that the client will accept content in, based on the
Accept-Language header.
ServletInputStream getInputStream()
9
Retrieves the body of the request as binary data using a ServletInputStream.
String getAuthType()
10 Returns the name of the authentication scheme used to protect the servlet, for
example, "BASIC" or "SSL," or null if the JSP was not protected.
String getCharacterEncoding()
11
Returns the name of the character encoding used in the body of this request.
String getContentType()
12
Returns the MIME type of the body of the request, or null if the type is not known.
String getContextPath()
13
Returns the portion of the request URI that indicates the context of the request.
29
String getHeader(String name)
14
Returns the value of the specified request header as a String.
String getMethod()
15 Returns the name of the HTTP method with which this request was made, for
example, GET, POST, or PUT.
String getPathInfo()
17 Returns any extra path information associated with the URL the client sent when it
made this request.
String getProtocol()
18
Returns the name and version of the protocol the request uses.
String getQueryString()
19
Returns the query string that is contained in the request URL after the path.
String getRemoteAddr()
20
Returns the Internet Protocol (IP) address of the client that sent the request.
String getRemoteHost()
21
Returns the fully qualified name of the client that sent the request.
String getRemoteUser()
22 Returns the login of the user making this request, if the user has been authenticated,
or null if the user has not been authenticated.
String getRequestURI()
23 Returns the part of this request's URL from the protocol name up to the query string
in the first line of the HTTP request.
String getRequestedSessionId()
24
Returns the session ID specified by the client.
String getServletPath()
25
Returns the part of this request's URL that calls the JSP.
boolean isSecure()
27 Returns a boolean indicating whether this request was made using a secure channel,
such as HTTPS.
30
int getContentLength()
28 Returns the length, in bytes, of the request body and made available by the input
stream, or -1 if the length is not known.
int getServerPort()
30
Returns the port number on which this request was received.
HTTP Header Request Example
Following is the example which uses getHeaderNames() method of HttpServletRequest to read the
HTTP header information. This method returns an Enumeration that contains the header information
associated with the current HTTP request.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner. We will
use the hasMoreElements() method to determine when to stop and the nextElement() method to get
the name of each parameter name.
<%@ page import = "java.io.*,java.util.*" %>
<html>
<head>
<title>HTTP Header Request Example</title>
</head>
<body>
<center>
<h2>HTTP Header Request Example</h2>
</body></html>
Let us now put the above code in main.jsp and try to access it.
JSP RESPONSE
n this chapter, we will discuss the Server Response in JSP. When a Web server responds to a HTTP
request, the response typically consists of a status line, some response headers, a blank line, and the
document. A typical response looks like this −
31
HTTP/1.1 200 OKContent-Type: text/htmlHeader2: ......HeaderN: ...
(Blank Line)<!doctype ...>
<html>
<head>...</head>
<body>
...
</body></html>
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the
example), and a very short message corresponding to the status code (OK in the example).
Following is a summary of the most useful HTTP 1.1 response headers which go back to the browser
from the web server. These headers are frequently used in web programming −
S.No. Header & Description
Allow
1 This header specifies the request methods (GET, POST, etc.) that the server
supports.
Cache-Control
This header specifies the circumstances in which the response document can safely
be cached. It can have values public, private or no-cache etc. Public means
2
document is cacheable, Private means document is for a single user and can only be
stored in private (nonshared) caches and no-cache means document should never be
cached.
Connection
This header instructs the browser whether to use persistent HTTP connections or not.
3
A value of close instructs the browser not to use persistent HTTP connections
and keep-alive means using persistent connections.
Content-Disposition
4 This header lets you request that the browser ask the user to save the response to disk
in a file of the given name.
Content-Encoding
5
This header specifies the way in which the page was encoded during transmission.
Content-Language
6 This header signifies the language in which the document is written. For
example, en, en-us, ru, etc.
Content-Length
7 This header indicates the number of bytes in the response. This information is
needed only if the browser is using a persistent (keep-alive) HTTP connection.
Content-Type
8 This header gives the MIME (Multipurpose Internet Mail Extension) type of the
response document.
32
Expires
9 This header specifies the time at which the content should be considered out-of-date
and thus no longer be cached.
Last-Modified
This header indicates when the document was last changed. The client can then
10
cache the document and supply a date by an If-Modified-Since request header in
later requests.
Location
This header should be included with all responses that have a status code in the 300s.
11
This notifies the browser of the document address. The browser automatically
reconnects to this location and retrieves the new document.
Refresh
12 This header specifies how soon the browser should ask for an updated page. You can
specify time in number of seconds after which a page would be refreshed.
Retry-After
13 This header can be used in conjunction with a 503 (Service Unavailable) response
to tell the client how soon it can repeat its request.
Set-Cookie
14
This header specifies a cookie associated with the page.
The HttpServletResponse Object
The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the
server creates the request object, it also creates an object to represent the response to the client.
The response object also defines the interfaces that deal with creating new HTTP headers. Through
this object, the JSP programmer can add new cookies or date stamps, HTTP status codes etc.
The following methods can be used to set HTTP response header in your servlet program. These
methods are available with the HttpServletResponse object. This object represents the server
response.
S.No. Method & Description
4 boolean isCommitted()
33
Returns a boolean indicating if the response has been committed.
void flushBuffer()
9
Forces any content in the buffer to be written to the client.
void reset()
10
Clears any data that exists in the buffer as well as the status code and headers.
void resetBuffer()
11 Clears the content of the underlying buffer in the response without clearing headers
or status code.
34
been committed yet.
<head>
<title>Auto Refresh Header Example</title>
</head>
<body>
<center>
<h2>Auto Refresh Header Example</h2>
<%
// Set refresh, autoload time as 5 seconds
response.setIntHeader("Refresh", 5);
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
out.println("Current Time is: " + CT + "\n");
%>
35
</center>
</body></html>
Now put the above code in main.jsp and try to access it. This will display the current system time
after every 5 seconds as follows. Run the JSP. You will receive the following output: −
36
Remote method invocation
The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
application in java. The RMI allows an object to invoke methods on an object running in another
JVM.
RMI uses stub and skeleton object for communication with the remote object.
A remote object is an object whose method can be invoked from another JVM. It is a mechanism that
allows an object residing in one system (JVM) to access/invoke an object running on another JVM.
RMI is used to build distributed applications; it provides remote communication between Java
programs. It is provided in the package java.rmi.
37
Let us now discuss the components of this architecture.
Transport Layer − This layer connects the client and the server. It manages the existing
connection and also sets up new connections.
Stub − A stub is a representation (proxy) of the remote object at client. It resides in the client
system; it acts as a gateway for the client program.
Skeleton − This is the object which resides on the server side. stub communicates with this
skeleton to pass request to the remote object.
RRL(Remote Reference Layer) − It is the layer which manages the references made by the
client to the remote object.
When the client makes a call to the remote object, it is received by the stub which eventually
passes this request to the RRL.
When the client-side RRL receives the request, it invokes a method called invoke() of the
object remoteRef. It passes the request to the RRL on the server side.
The RRL on the server side passes the request to the Skeleton (proxy on the server) which
finally invokes the required object on the server.
The result is passed all the way back to the client.
38
To invoke a remote object, the client needs a reference of that object. At that time, the client fetches
the object from the registry using its bind name (using lookup() method).
The following illustration explains the entire process −
Goals of RMI
Following are the goals of RMI −
To minimize the complexity of the application.
To preserve type safety.
Distributed garbage collection.
Minimize the difference between working with local and remote objec
Declare all the business methods that can be invoked by the client in this interface.
Since there is a chance of network issues during remote calls, an exception
named RemoteException may occur; throw it.
Following is an example of a remote interface. Here we have defined an interface with the
name Hello and it has a method called printMsg().
39
import java.rmi.Remote; import java.rmi.RemoteException;
// Creating Remote interface for our application public interface Hello extends Remote {
void printMsg() throws RemoteException; }
Developing the Implementation Class (Remote Object)
We need to implement the remote interface created in the earlier step. (We can write an
implementation class separately or we can directly make the server program implement this
interface.)
To develop an implementation class −
Implement the interface created in the previous step.
Provide implementation to all the abstract methods of the remote interface.
Following is an implementation class. Here, we have created a class named ImplExample and
implemented the interface Hello created in the previous step and provided body for this method
which prints a message.
// Implementing the remote interface public class ImplExample implements Hello {
Create a client class from where you want invoke the remote object.
Create a remote object by instantiating the implementation class as shown below.
Export the remote object using the method exportObject() of the class
named UnicastRemoteObject which belongs to the package java.rmi.server.
Get the RMI registry using the getRegistry() method of the LocateRegistry class which
belongs to the package java.rmi.registry.
Bind the remote object created to the registry using the bind() method of the class
named Registry. To this method, pass a string representing the bind name and the object
exported, as parameters.
40
// Binding the remote object (stub) in the registry
Registry registry = LocateRegistry.getRegistry();
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}}
Developing the Client Program
Write a client program in it, fetch the remote object and invoke the required method using this object.
To develop a client program −
Create a client class from where your intended to invoke the remote object.
Get the RMI registry using the getRegistry() method of the LocateRegistry class which
belongs to the package java.rmi.registry.
Fetch the object from the registry using the method lookup() of the class Registry which
belongs to the package java.rmi.registry.
To this method, you need to pass a string value representing the bind name as a parameter.
This will return you the remote object.
The lookup() returns an object of type remote, down cast it to the type Hello.
Finally invoke the required method using the obtained remote object.
Following is an example of an RMI client program.
import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry;
public class Client {
private Client() {}
public static void main(String[] args) {
try {
// Getting the registry
Registry registry = LocateRegistry.getRegistry(null);
41
Or,
In the previous chapter, we created a sample RMI application where a client invokes a method which
displays a GUI window (JavaFX).
In this chapter, we will take an example to see how a client program can retrieve the records of a
table in MySQL database residing on the server.
Assume we have a table named student_data in the database details as shown below.
+----+--------+--------+------------+---------------------+
| ID | NAME | BRANCH | PERCENTAGE | EMAIL |
+----+--------+--------+------------+---------------------+
| 1 | Ram | IT | 85 | [email protected] |
| 2 | Rahim | EEE | 95 | [email protected] |
| 3 | Robert | ECE | 90 | [email protected] |
+----+--------+--------+------------+---------------------+
Assume the name of the user is myuser and its password is password.
42
public void setPercent(int percent) {
this.percent = percent;
}
public void setEmail(String email) {
this.email = email;
}
}
Defining the Remote Interface
Define the remote interface. Here, we are defining a remote interface named Hello with a method
named getStudents () in it. This method returns a list which contains the object of the class Student.
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.*;
Here we are implementing the getStudents() method of the Remote interface. When you invoke this
method, it retrieves the records of a table named student_data. Sets these values to the Student class
using its setter methods, adds it to a list object and returns that list.
import java.sql.*;
import java.util.*;
// Database credentials
String USER = "myuser";
String PASS = "password";
43
//Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT * FROM student_data";
ResultSet rs = stmt.executeQuery(sql);
Following is the server program of this application. Here, we will extend the above created class,
create a remote object and register it to the RMI registry with the bind name hello.
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
44
public static void main(String args[]) {
try {
// Instantiating the implementation class
ImplExample obj = new ImplExample();
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Client Program
Following is the client program of this application. Here, we are fetching the remote object and
invoking the method named getStudents(). It retrieves the records of the table from the list object and
displays them.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.*;
// System.out.println("bc "+s.getBranch());
System.out.println("ID: " + s.getId());
System.out.println("name: " + s.getName());
System.out.println("branch: " + s.getBranch());
System.out.println("percent: " + s.getPercent());
System.out.println("email: " + s.getEmail());
}
45
// System.out.println(list);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
46