Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Server Pages: March 2012

Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/268076772

Java Server Pages

Chapter · March 2012


DOI: 10.13140/2.1.1715.9365

CITATIONS READS
0 1,974

1 author:

Somasundaram Karuppanagounder
Gandhigram Rural Institute
166 PUBLICATIONS   962 CITATIONS   

SEE PROFILE

Some of the authors of this publication are also working on these related projects:

Parallel Computing for Image Processing View project

Brain Tumor Segmentation and Validation View project

All content following this page was uploaded by Somasundaram Karuppanagounder on 10 November 2014.

The user has requested enhancement of the downloaded file.


Chapter 25
Java Server Pages (JSP)

In chapter 24 the servlet technology was explained. Servlets perform the roles of
presentation part by generating HTML codes and the business processing part by
generating the dynamic content. It is like HTML embedded in a Java code. For
generating complex page layout, writing servlets becomes cumbersome. To over-come
this problem servlet technology has been extended to form Java Server Pages (JSP). JSP,
like servlet, is a server side programming technology. JSP can process the HTTP request
sent by a client and return a response to it. In JSP the presentation part and business
processing part are separated. The static presentation part called template data is taken
care by the HTML designed by page authors and the dynamic part is taken care by Java
Codes written by programmers. JSP is like Java code embedded in a HTML page. In
fact any HTML page with .htm extension can be converted to a JSP file by renaming it to
.jsp extension. JSP provides varying degrees of binding HTML with Java codes, starting
from scriptlets which allows java codes to be placed directly inside JSP file to JavaBean
where Java codes are completely separated from HTML. JavaBeans mentioned in JSP are
not the Enterprise Java Beans (EJP). In this chapter we will see the basics of JSP, the
syntax, how to compile, deploy in a webserver and execute them.

25.1 How JSPs work?

A JSP source code is first translated in to a servlet code. The servlet code is then
compiled using javac and the corresponding class is produced.

JSP Source Translation Compile Servlet Class


Code Servlet Code

Fig. 25.1 Conversion of JSP to Servelet Class.

A JSP is a web component. It runs inside a web container in a J2EE application


server (like Sun Java Application Server, Tomcat etc). It is the responsibility of the web
container to translate a JSP source code to servlet code, compile and create the servlet
class. This is called translation phase.

When a request comes from a client to a JSP for the first time, the web container
translates the JSP to servlet, compile the servlet and execute it. The execution part is
called execution phase. For subsequent requests an instance of the servlet is created and
a response is sent to the request. In the meantime if the JSP code is modified, and when a
request comes the JSP undergoes a translation phase, executes and returns a response to
it.

1
Request

Is it
Yes first time No
for the
code

Convert
JSP to Servlet

Compile
Servlet

Execute
the Servlet

Response

Fig. 25.2 Execution of a JSP inside a JSP Container.

As an example a simple JSP file is given in Program 25.1. This JSP just gives a
welcome note to JSP programming. For simplicity few default statements are removed.

Program 25.1 Welcomjsp.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<%@ page import ="java.util.*" %>
<html>
<head>
<title> JSP Lesson</title>
</head>
<body>
<h1>Welcome to JSP Programming</h1>
<p> A JSP page can be prepared as per the syntax of JSP. This
JSP program is prepared as per the specification of JSP2.0. A JSP
contains templates, sciptlets, expressions, dirctive and actions. It
looks more like a HTML document. This text is displayed from a JSP
compiled in NetBeans and deployed in a web container in GlassFish V2
Server. </p>
<p> Program by Dr.K.Somasundaram </p>
<p> ka.somasundaram@gmail.com</p>
<%

2
Date dt = new Date();
%>
Today is <%= dt%>
</body>
</html>

The web container generated servlet code Welcomjsp_jsp.java is given in


program 25.2.

Program 25.2 Welcomjsp_jsp.java

package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.*;

public final class Welcomjsp_jsp extends


org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {

private static final JspFactory _jspxFactory =


JspFactory.getDefaultFactory();

private static java.util.Vector _jspx_dependants;

private org.apache.jasper.runtime.ResourceInjector
_jspx_resourceInjector;

public Object getDependants() {


return _jspx_dependants;
}

public void _jspService(HttpServletRequest request,


HttpServletResponse response)
throws java.io.IOException, ServletException {

PageContext pageContext = null;


HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;

try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request,
response, null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();

3
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector =
(org.apache.jasper.runtime.ResourceInjector)
application.getAttribute("com.sun.appserv.jsp.resource.injector");

out.write("\n");
out.write("<html>\n");
out.write(" <head>\n");
out.write(" <title> JSP Lesson</title>\n");
out.write(" </head>\n");
out.write(" <body>\n");
out.write(" <h1>Welcome to JSP Progamming</h1>\n");
out.write(" <p> A JSP page can be prepared as per the
syntax of JSP. This JSP program \n");
out.write(" is prepared as per the specification of
JSP2.0. A JSP contains templates\n");
out.write(" sciptlets, expressions , dirctive and actions.
It looks more like a HTML\n");
out.write(" dcoument. This text is displayed from a JSP
compiled in NetBeans and \n");
out.write(" deployed in a web container in Sun Java
Application Server9.0. </p>\n");
out.write(" <p> Program by Dr.K.Somasundaram </p>\n");
out.write(" <p> somasundaramk@yahoo.com</p>\n");
out.write(" ");

Date dt = new Date();

out.write("\n");
out.write(" <tr><td> ");
out.print( dt);
out.write("</td></tr>\n");
out.write(" \n");
out.write(" </body> \n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null)
_jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}

4
The output of program 25.1 is shown in Fig.25.3

Fig 25.3 Output Screen for program 25.1

25.2 Syntax of a JSP Page

A JSP page is a text based file. It contains two types of text that generate static
template data and dynamic data. The static data is expressed in any text-based format
such as HTML, WML, and XML. The dynamic data is generated by JSP elements. The
JSP files have .jsp extension. The JSP elements in a JSP page are expressed in two
syntaxes, standard (in HTML) and XML (Extensible Markup Language). The standard
HTML format is called JSP file. The XML format is called JSP document. As per
JSP2.0 specification there are five types of elements in a JSP page. They are:
i) Directives
ii) Scripting elements
iii) Comments
iv) Action Elements
v) Expression Language (EL)

We present the standard syntax for the JSP elements in the following section.

5
25.2.1 Directives

Directives are instructions meant for the JSP container. It describes what codes
are to be generated in creating a servlet. They affect the entire page. The general form a
directive is:

<% directive_name [attribute = ‘value”, attribute = “value”] %>

Spaces, tabs and newline can follow <%@ but before %>. There are three directives.
They are:
i) page
ii) include
iii) taglib

Page directive

The page directive provides a mechanism to define attributes for a JSP page. The
following table 25.1 shows the attributes and values for the JSP page.

Table 25.1 Attributes of a JSP page.

Attribute Description Value

1. language This defines the language to be used in java


the scriptlets, expression and declarations. default:java

2. extends Refers to a fully qualified class name


of a super class that JSP container will className
extend to generate the servlet. default:not used
This must be a class that implements
the HttpJspPage.

3. import The same meaning as in a java program Comma Separated list


default : not used

4. session This specifies whether the JSP page true/false


requires an HTTP session or not. Default : true

5. buffer Specifies the size of the output buffer. nkb or none


Default : 8 kb

6. autoFlush When set to true the buffer is automatically true/false


flushed when the buffer is full. When set default : true
to false will throw an exception when the
buffer is full

6
7. isThreadSafe Tells the container, whether this page true/false
can handle requests from multiple theads. default : true
When set to true, the page can handle
multiple requests otherwise the requests
are qued and sent one at a time.

8. info This is used to set an informational text


string that can be accessed through the default : not used
getServletInfo() method.

9. isErrorPage Specifies whether this page will act as true/false


an error page URL for another JSP. default : false
When set to true, this page can be
given as the value for the errorPage
attribute of another JSP.

10. errorPage Specifies the URL of another JSP that error-URL


will be invoked to handle uncaught default : not used
exceptions.

11. ContentType Specifies the character encoding the CTinfo


Multipurpose Internet Mail Extension default MME text /
(MIME) for the response of the JSP. html (text/XML)
default charset:ISO-8859-1
(UTF-8)

12. Page Encoding Specifies the character encoding for the page-encoding - info
JSP. Value is of the form CHARSET. default : as given in
content Type
Otherwise ISO-8850-1

13. isELIgnored Specifies whether Expression Language true/false


(EL) can be used. default :
true for servlet 2.3
false for servlet 2.4

The details of the above attributes are given below.

1. language
This attribute defines the language used in the JSP. Though the design of JSP
technology is to allow more languages to be used, currently the only language
permitted is java.

2. extends
Generally the JSP container provides the required parent class for generating the
servlet. But use of this attribute will eliminate some of the benefits and

7
functionality provided by the container. For any class that is to be used as
superclass, it must implement any of the interface JSPPage or HttpJspPage.

3. import
This import attribute is used to refer to the classes used in JSP without using the
package prefix. By default the following packages are imported automatically.

java.lang.*
java.servlet.*
java.servlet.jsp.*
java.servlet.http.*
A comma separated list can be used for this attribute.

Example

<%@ page import = “java.io.*, java.net.*, java.awt.*”%>


or
<%@ page import = “
java.io.* ,
java.net.*,
java.awt.*
“%>
or
%@page import = “java.io.*” %>
%@page import = “java.net.*” %>
%@page import = “java.awt.*” %>

This is the only attribute that can be used more than once.

4. session

This attribute specifies whether the JSP page need to manage HTTP session. By
default this is true. But it is strongly adviced that the session be set to false as session
management consumes more memory and CPU cycles. When set to false no
HttpSession object is created.

Example:
<%@page session = “false” %>

5. buffer

The use of buffer is to increase the performance of the output process. This
attribute can be having ‘nkb” value where n is an integer or “none”. When buffer is set to
“none” the output is directly sent to the output stream of response object. By default its
value is 8 kb. It is specified by an integer followed by kb or just an integer number.

8
Examples:

1. <%@page buffer = “none” %>

2. <%@page buffer = “16 kb” %>


or
<%@page buffer = “16” %>

6. autoFlush

This attribute is linked to the buffer attribute. When set to true the JSP container
automatically flushes the buffer when it is full. When set to false, a buffer
overflow exception will occur when the buffer becomes full. To avoid this
flush() method has to be called manually.

7. isThreadSafe

This attribute is related to the way the multiple threads can access the JSP.
By setting this value to “true”, the page author guarantees that requests from
several threads can access this servlet. But it is likely that the same servlet may
be accessed by several threads simultaneously and may lead to thread collision.
When set to false the servlet container implements a single thread model for this
JSP page. The JSP page is accessed by one thread at a time. The default value is
true.

Example :
<%@ page isThreadSafe = “false” %>
8. info

This attribute helps to set a desriptive information about the JSP page.
This information can be accessed by the getServletInfo() method.

Example :
<%@ page info = “Mark List Processing” %>

9. isErrorPage

This attribute informs the JSP container whether this page is to be


executed when an exception occurs in another JSP page and is not caught. This
declaration has to be complemented by the errorPage attribute by specifying this
page as error page. The default value is false.

Example :
<%@ page isErrorPage = “true” %>

9
10. errorPage

This attribute informs the JSP container that the URL specified in this
attribute is to be executed when an uncaught exception occurs.

Example :
<%@ page errorPage = “c/jsplessons/demoerrorp.jsp” %>

11. contentType

This attributes specifies the type of response sent to the client. The
specification is the MIME type. The default type is “text/html” and “charset =
ISO-8859-1”. The other type can also be in XML type, which can be specified as
“text/XML” and “charset = UTF-8”.

Example :
1. <%@ page contentType = “text/html; charset = ISO-8859-1” %>
2. <%@ page contentType = “text/html” %>
3. <%@ page contentType = “text/xml; charset = UTF-8” %>

12. pageEncoding

This attribute specifies the character set used in the JSP page. The
character set is the same as given in contentType attribute. The default value is
ISO-8859-1.

Example:
<%@ page pageEncoding = “GB2312” %>
GB2312 is chinese character set.

13. isELIgnored
This attribute specifies whether the Expression Language expressions are
evaluated in this page. When set to true, EL are ignored. When set to false, the
EL is evaluated. The default value for servlet 2.3 is true and for servlet 2.4 is
false.

Example:
<%@ page isELIgnored = “true” %>

All the page directive attribute can be placed in a single declaration as given
below:
<%@ page import = “java.io.*” buffer = 16kb” isErrorPage = “false”
contentType = “text/html; charset = iso-8859-1” autoFlush = “true”
info = “Demo JSP page”” isThreadSafe = “false”
%>
The following program 25.3 shows some of the page directives.

10
Program 25.3 Pagedir.jsp
<%--
Author : K.Somasundaram
e-mail : somasundaramk@yahoo.com
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<%@page import="java.util.Date" %>
<%@page info="Page directive lesson: by K.Somasundaram" %>
<%@page autoFlush="true" %>
<%@page isErrorPage="false" %>
<%@page isELIgnored="false" %>
<html>
<head>
<title> Page Directive</title>
</head>
<body>
<h2>Demo for Page Directive </h2>
<%= "Todays Date is :" + new Date() %><br>
<!-- Get the servlet information -->
<%= getServletInfo()%>
</body>
</html>

The output of program 25.3, executed through Netbeans 6.0 and viewed by
Mozilla Firefox is given in Fig. 25.4.

Fig 25.4 Output Screen for program 25.3

Include directive

JSP pages may need some statements that are already defined in a JSP page. The
include directive helps to merge such pages in the current JSP page. Pages such as
header and footer can be easily done using this directive. The codes merged can be static
template text or code. The syntax of include directive is:
<%@ include = “jspfileName” %>

11
Example:
<%@ include = “author.jsp” %>

The following program 25.4 illustrates the use of include directive.

Program 25.4 Includedir.jsp

<%--
Author : Dr.K.Somasundaram
e-mail : ka.somasundaram@gmail.com
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<html>
<head>

<title>Include DIrective</title>
</head>
<body>
<h2>Demo for Include Directive</h2>
<%@ include file="Pagedir.jsp" %>
<h2> The above result is obtained from Pagedir.jsp </h2>
</body>
</html>

The output for the program 25.4 is shown in Fig 25.5

Fig.25.5 Output screen for program 25.4

12
TagLib Directive

Higher level functions can be added to JSP using taglib directive. A tag refers to
a name that is associated with a procedure expressed in a XML like format. A collection
of tags can be stored in a directory called tag libraries. Such libraries can be referred
using taglib directive and the procedures can be executed.

The syntax of a taglib directive is:

<%@ taglib uri = “tagLibraryURI” prefix = “tagprefix” %>

where, URI – Specifies the URI that identifies the TLD (Tag Library Descriptor)
associated with this prefix

prefix – specifies the string to be used to access tags defined in the tag library.

25.2.2 Scripting Elements

Scripting elements help to insert Java code in JSP. Three types of scripting
elements are used in JSP. They are :

 Scriptlets <% Javac Code %>


 Expressions <% = Expression %>
 Declaractions <%! Method/ variable declaration %>

Scriptlets

A block of Java code in a JSP is called scriptlet. When a JSP is translated to


servlet these codes are inserted into it as such. A JSP can contain any number of
scriptlets. The scriptlets can be interleaved with html elements. For example the open
brace { can be in one scriptlet and the corresponding closing brace } can be in another
scriptlet. The syntax of a scriptlet is :

<% Java Statement %>

The following program 25.5 is an example for scriptlet in a JSP. This JSP
computes the factorial of a number.

Program 25.5 Scriptlet.jsp

<%--
Author :K. Somasundaram
e-mail :ka.somasundaram@gmail.com
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>

13
<head>
<title>Scriptlet</title>
</head>
<body>
<h2>This is a Sample for Scriptlet</h2>
This program finds the Factorial of a Number<br>
<!-- The following is a scriptlet -->
<% long fact = 1;
int n = 8, i;
for (i = 1; i <= n; i++) {
fact *= i;
}
%>
Factorial of <%= n %> is =<%= fact %> <br>
</body>
</html>

The output screen for program 25.5 is shown in Fig. 25.6

Fig.25.6 Output Screen for program 25.5

Expressions

A JSP expression is used to send values directly to the output. The syntax of an
expression is :
<% = Java Expression %>

In a JSP page, the expression is evaluated and the result is converted into a string and
placed in the output statement. For example the following expression will print out a
random number between 0 to 10 directly.

<% = (int) (10* Math,random())%>

The following program 25.6 illustrates the use of the above expression.

14
Program 25.6 Expression.jsp

<%--
Author :K. Somasundaram
e-mail :ka.somasundaram@gmail.com
--%>

<%-- This program illusteas the use of Expression in a JSP --%>


<%-- The expression finds a random number between 0 and 10 --%>

<head><title>Random Number</title></head><body>
Random Number generated is: <%= (int) (10 * Math.random()) %>
</body>

The output screen for program 25.6 is shown in Fig.25.7

Fig.25.7 Output Screen for Program 25.6

Declarations

A JSP declaration helps to declare variables, methods and classes. A declaration


supports JSP expression or statement and hence it is always used along with the M.
Some times a variable can be declared in the scriptlet itself but not the method or class.
The general form of declaration in JSP is:

<%! Variable / Method / Class definition %>

JSP declaration can be placed any where in the JSP. Declarations can also be
used for initialization and clean up codes. Unlike scriptlets, a declaration can not access
implicit objects (like request, response, out etc.). The following program 25.7 illustrates
the use of declaration. This JSP defines a method that finds the factorial of a number. It
is then called in the body of the JSP to compute the factorial of 5, 8 and 10.

15
Program 25.7 Declaration.jsp

<%--
Author :K. Somasundaram
e-mail :ka.somasundaram@gmail.com
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>JSP Declaration</title>
</head>
<%-- Method declaration--%>
<%!
long Fact(int n) {
long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
%>
<body>
<h2>Factorial of 5 is: <%= Fact(5) %></h2>
<h2>Factorial of 8 is: <%= Fact(8) %></h2>
<h2>Factorial of 10 is: <%= Fact(10) %></h2>
</body>
</html>

The output screen for program 25.7 is shown in Fig 25.8.

Fig. 25.8 Output screen for program 25.7

16
25.2.3 Comments

Comments, that will provide information to the developers and page authors, can
be placed in a JSP file. There are three syntaxes for the comments.

JSP Comment

The first type, called JSP comment, has the following format:

<%-- This text will appear only in JSP --%>

This type of comments are meant only for the JSP. When it is compiled, anything
contained between <%-- and --%> are ignored.

HTML Comment

The second type, called HTML comment, has the following syntax.

<! – This text will appear in the HTML generated - - > when JSP is compiled, the
characters enclosed between <! – and - - > are again generated and placed in the HTML
document generated.

Java Comments

The third type, called Java comments, is the traditional comment made in Java.
This comment is placed inside the scriptlets and has the following syntax.

<% /* This is a Java Comment */>

This comment is ignored while JSP is compiled.

25.2.4 Implicit Objects

A JSP file can access certain objects created by the web container. Methods
defined in these objects can be called to support the functions required in a JSP. For
example, to get the parameters sent by clients, the request object is needed by the JSP.
Such objects are made available automatically the JSP by the web container. The objects
which are available to the JSP in the web container are called implicit objects. These
objects are instances of classes defined by the servlet and JSP specifications. These
objects are created by the web container. These objects can be accessed by scripting
elements, action elements and Expression Language (EL). There are nine such objects
and are given in Table 25.2

17
Table 25.2 Implicit Objects available to JSP

Object Type Semantics and Scope

1. request HttpServletRequest The request triggering the service


invocation
Scope : request

2. response HttpServletResponse The response to the request.


Scope : page

3. pageContext PageContext The page context for this JSP page.


Scope : page

4. session HttpSession The session object created for the


requesting client. This object is valid
only for HTTP protocols.
Scope : session

5. application ServletContext The servlet context obtained from the


servelet configuration object.
Scope : application

6. out JspWriter An object that writes into the output


stream.
Scope : page

7. config ServletConfig The ServletConfig for this JSP page


scope : page

8. page Object The instance of this page’s


implementation class processing the
current request page scope.

9. exception Throwable The uncaught Throwable that resulted


in the error page being invoked.
Available only in Error Page.
Scope : page.

25.2.5 Action Elements

Actions may affect the current out stream and use, modify and create objects.
These objects are made available to the scripting elements through scripting specific
variable. Action elements bind the HTML codes with Java codes that are written
separately. An action element is written only in XML syntax. Standard actions are

18
represented using XML elements with a prefix of jsp. The following standard actions are
available in JSP2.0 specification. The action elements are to be written in XML syntax.

1. <jsp:useBean>
2. <jsp:setProperty>
3. <jsp:getProperty>
4. <jsp:include>
5. <jsp:forward>
6. <jsp:param>
7. <jsp:plugin>

JavaBeans

Before looking into the individual action elements it is better that we understand
about the JavaBeans used in actions. The JavaBean referred here are not the same as that
of Enterprise Java Beans(EJP). The JavaBeans are simple helper classes, written in a
specific format in Java. Every variable in the class is called as property.

A bean contains setter and getter methods for each property. If a property is to be
assigned a value, then the beans class should contain set XXX method, where XXX is the
name of the property or variable. Similarly if the value of any property of a bean is to be
accessed in the JSP page, then there should be a getXXX method in the beans class for
that property. In addition to setxxx and getxxx method, a bean can have other methods
also. Such methods can be accessed inside a JSP, if that beans has been declared using
<jsp:useBean> element. A beans class need to have a no-agrument constructor (even
otherwise the default constructor will be used for this purpose). A JavaBean has to be
packaged. Program 25.8 is an example for JavaBean. This bean contains setxxx and
getxxx for properties title, author and price.

Program 25.8 Book.Java

package demoaction;
public class Book {
String title;
String author;
int price;
public Book() { }
public void settitle(String txt) {
title = txt;
}
public String gettitle() {
return title;
}
public void setauthor(String txt) {
author = txt;
}
public String getauthor() {
return author;
}
public void setprice(int p) {

19
price = p;
}
public int getprice() {
return price;
}
public double royalty(int rate){

return price*rate/100.0;
}
}

We will see in the foregoing sections the syntax of the action elements.

<jsp: useBean>

This element declares the availability of an instance of JavaBean, what is its class
name, type and scope. It also gives identification (id) to the bean using which the
JavaBean can be accessed by JSP elements. The syntax of this element is:
<jsp:useBean id = “assignedName”
scope = “page|request|session|application”
class = “class Name”|
class = “className” type= “typeName”|
beanName = “beanName” type = “typeName”|
type = “typeName>
</jsp:useBean>

where,

id - The name used to identify the object in the specified scope. The
name is assigned by the user. The name is case sensitive and shall
conform to the current scripting language variable-naming
convention.

scope - The scope within which the reference is available


page – active only in this page. This is the default value.
request – active for the current request.
session – active for the current session.
application - active for the current application.

class - The fully qualified name of the class (bean) that defines the
implementation of the object. If the className and beanName are
not specified, then the object must be present in the given scope.

beanName - The name of a bean as provided to the instance() method of the


java.bean.Beans class. When beanName and type are specified
class attribute should not be used.

20
Type - If specified, it defines the type of the scripting variable defined.
The type is required to be the either the class itself, a super class of
the class, or an interface which the class implements. This
parameter is optional.

<jsp : setProperty>

This element is used to set the values of properties in a bean. The


name attribute that denotes the bean must be defined before this
action appears. Properties in a bean can be set from one or more
parameters in the request object from a string constant, or from a
computed request time. This element can be used only if <jsp :
setProperty> element is :

<jsp : setProperty name = “id” property – expression/>


where property-expression can be any one of the following.

property = “*” 1
property = “propertyName” 1
property = “propertyName” param = “paramName” 1
property = “propertyName” value = “propertyValue” 1
property = “propertyName” value = “<% = expression %>”
where,

param - is the name of the request parameter whose value is given to a bean
property. If param is omitted, the request parameter name is
assumed to be the same as the bean property name.

name - is the name of a bean instance defined by <jsp:useBean>action.


The bean instance must contain the property to be set.

property - is the name of the property whose value will be set.

value - is the value to be assigned to the given property. An action may


not have both param and value attributes.

<jsp : getProperty>

This action element returns the value of the specified bean property. The value is
converted to string and can be displayed in the output. The syntax of this action element
is :

<jsp : getProperty name = “id of the javaBean”,


property = “propertyName”/>

This element can be used, only if <jsp : UseBean> is already defined.

21
The three action elements <jsp : useBean>, <jsp :setProperty> and
<jsp:getProperty>, are linked to each other. Without defining <jsp : useBean> the other
two elements can not be used. We will now see an example to illustrate the usage of the
three action elements. Program 25.9 is a JSP page that makes use of a JavaBean called
Book.java given in program 25.8.

Program 25.9 Bookdetail.jsp

<%--
This is a simple JSP page that makes use of a JavaBean called
Book.java. It is available in the package demoaction.
Three properties, title,author, and price are set using setXXX
method and all the three properties are accessed using getXXX method.
The properties can also obtained by directly calling
the getXXX . Other methods defined in that can aslo
called. The royalty() method is called like that.
Program created ,compiled and executed using NetBeans IDE 6.0

Author : Dr.K.Somasundaram
e-mail : ka.somasundaram@gmail.com
--%>
<jsp:directive.page contentType="text/html" pageEncoding="UTF-8"/>
<jsp:useBean id="trial" class ="demoaction.Book" scope="page">
<jsp:setProperty name="trial" property="title" value="Programming
in Java2"/>
<jsp:setProperty name="trial" property ="author"
value="Dr.K.Somasundaram"/>
<jsp:setProperty name="trial" property ="price" value ="350"/>
</jsp:useBean>
<html>
<title> Welcome to jsp:useBean </title>
<h3><head>JSP ACTION: useBean Demo</head></h3>
<h2>Title of the Book:<jsp:getProperty name="trial"
property="title"/></h2>
<h2>Author :<jsp:getProperty name="trial"
property="author"/></h2>
<h2>Price Rs: <jsp:getProperty name ="trial"
property="price"/></h2>
<h2>Price Rs: <%= trial.getprice() %></h2>
<h2>Royalty per book is Rs: <%= trial.royalty(10) %> </h2>
</html>

In the program 25.9, the action element <jsp:useBean> informs the JSP about the
details of the bean that is going to be used in that page. Tells the JAP that the name of
the bean is demoaction.Book and assigns an id, “trial”. This id “trial” is the logical name
used in the remaining part of the JSP to identity the bean. The <jsp :setProperty>
element is used to set the values for the properties title, author and price. Then the html
is used to design the page. Inside the page design the three properties of the bean are
accessed using <jsp : getProperty> element and inserted dynamically in the page. The
output of the program when executed by NetBeans IDE 6.0 and viewed through Mozilla
Firefox browser is shown in Fig.25.9

22
Fig 25.9 Output screen for Program 25.9.

In the above program 25.9 the three properties title, author and price are assigned
static values in the server side itself. But in most applications value for the properties of
the bean used in the JSP are supplied by the client. For this we take up a problem of
calculating the obesity a person.

The expected weight of a person is 23 times the square of the height, when weight
is measure in kg and height in metres. (See program 22.9 in chapter 22). If the weight of
a person is more than the expected weight then that person has obesity. First write the
bean, the helper class, that receives the properties height and weight calculate the
expected weight, compare it with the weight of the person and returns a message
overweight when it is more and normal when it is lower. This beans class is named as,
height.java and is given in program 22.10.

Program 25.10 Height.java

package demoaction;
// a JavaBean processing the height and weight
public class Height{
double height=0, weight=0,maxweight=0;
String message="", name="";
public Height(){}
public void setname(String str){

23
name=str;
}

//When height is read , it is in String type.


//Hence conversion of the String to double is needed
public void setheight(String x){
height=Double.parseDouble(x);
}
public void setweight(String y){
weight=Double.parseDouble(y);
}
public String getmessage(){
maxweight=Math.ceil(23.0*height*height);
if(weight<maxweight)
{message="Your expected weight is "+maxweight+" Kg. ";
message += " You are within the limit. Keep it up";
return message;
}
else
{
message="Your expected weight is "+ maxweight+" Kg. ";
message += " You are over weight. Try to reduce it";
return message;
}
}
public String getname(){
return name;
}
}

Then we write a JSP which makes use of the beans class. In the JSP, the
<jsp:setProperty> element is used to receive the values for the properties of the bean
from the client side and assigns it to height, weight and name properties, and calls the
bean to process the properties. The processed value is obtained through message
property using <jsp : getProperty> element. This JSP, named Htgwgt.jsp, is given in
program 25.11.

Program 25.11 Htgwgt.jsp

<%--
Program created, compiled and executed using NetBeans IDE 6.0
Author : Dr.K.Somasundaram
e-mail : ka.somasundaram@gmail.com
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<%-- Using useBean action. --%>
<html>
<jsp:useBean id = "obs" class ="demoaction.Height" scope ="page">
<%-- The following statement can also written as: --%>
<%-- <jsp:jsp:setProperty name="obs" property ="name" value="<%=
request.getParameter("name")%>"/> --%>
<jsp:setProperty name="obs" property ="name" param="name"/>
<jsp:setProperty name="obs" property ="height" value= "<%=
request.getParameter("height")%>"/>

24
<jsp:setProperty name="obs" property ="weight" value= "<%=
request.getParameter("weight")%>"/>
</jsp:useBean>
<html>
<title>Obesity Test Result</title>
<h1><head> Obesity Test Result </head></h1>
<h1>Welcome <jsp:getProperty name="obs" property="name"/></h1>
<h2><p> <jsp:getProperty name="obs" property ="message" />
</p></h2>
</html>

</html>

Please note the different forms of assigning values to the properties using param
and <% = expression>

Then we write the client side html page to receive values for the parameters from
the user and call the Htgwgt.jsp to process the parameters. This html page, named as
Hgtwgthtm.html, is given in program 25.12

Program 25.12 Hgtwgthtm.html

<!--
Author : Dr.K.Somasundaram
e-mail : ka.somasundaram@gmail.com
-->
<html>
<head>
<title> Test Your Obesity</title>
</head>
<body>
<h1>Test Your Obesity </h1>
<form method="get" action ="Htgwgt.jsp">
<p> Give your height in meters and weight in Kg</P>
<p>Type in Your Name: <input type ="text" name ="name"></p>
<p>Height(in Meters):<input type= "text" name="height"></p>
<p>Weight (in Kg):<input type="text" name ="weight"></p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>

The output of the program 25.12, when executed using NetBeans IDE 6.0 is
shown in Fig.25.10(a). The screen shot after the user has filled in the input field is shown
in Fig.25.10.b.

25
Fig. 2510a.bmp
(a)

Fig. 2510b.bmp
(b)

26
Fig. 2510c.bmp
(c)

Fig. 25.10 Screen Output for Program 25.12(a) Empty form (b) Filled in form(c)
Response from server after submitting the form.

<jsp : include>

This element provides for the inclusion of static and dynamic resources in the
same context as the current page. The output of the included file is merged with the
output of the current page at run time. This is in contrast with the page include, where
the named page is merged with the source code of jsp file at translation phase.

The <jsp : include> has two syntax. The syntax of first form is :

<jsp : include page = “URL” flush = “true\false”/>


where URL is the page URL of the included resource. When the requested file needs
input parameters then the second form of the syntax is used. The second form of the
syntax is :
<jsp :include page = “URL” flush = “true\ flase”/>
<jsp : param = “paramName” value = “paramValue”/>
<jsp : param = “paramName” value = “paramValue”/>
.
.
.
<jsp : param = “paramName” value = “paramValue”/>
</jsp : include>

27
To illustrate the use of <jsp : include> element we consider a simple example.
There is an html file named author.html. When viewed it will display the author of the
page. We want to include that author.html file in a JSP. Program 25.13 shows the JSP
that includes author.html file.

Program 25.13 Inclde1.jsp

<%--
This program is an illustration for <jsp:include> action
element. This page includes another html page
author.html, which displays the name of the page author.
Program created ,compiled and executed using NetBeans IDE 6.0

Author : K.Somasundaram
email : ka.somasundaram@gmail.com
--%>
<jsp:directive.page contentType="text/html" pageEncoding="UTF-8"/>

<html>
<head>
<title>Action: Include Demo</title>
</head>
<body>
<h2>This is a demo for jsp:include </h2>
<jsp:include page ="author.html" flush="true"/>
</body>
</html>

The output of program 25.13 is shown in Fig.25.11.

Fig.25.11 Screen output for program 25.13

28
Next we write a JSP to include another JSP which needs input parameter. This
program illustrate the second form of <jsp : include> syntax. The JSP which will be
included needs two parameters nam and age at run time. After receiving them it sends a
response. This JSP, named as Age.jsp is shown in program 25.14.

Program 25.14 Age.jsp

<%--
Author : Dr.K.Somasundaram
e-mail : ka.somasundaram@gmail.com
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%
String sname = request.getParameter("nam");
%>
<h2>The Author of the this Page is :<%= sname%></h2>
<% String sage = request.getParameter("age");
int age = Integer.parseInt(sage);
%>
<h2> Age= <%= age%></h2>

Next we write the container JSP, that includes the Age.jsp and is given in program
25.15.

Program 25.15 Inclde1.jsp

<%--
This program is an illustration for <jsp:include> action
element. This page includes another html page
author.html, which displays the name of the page author.
Program created, compiled and executed using NetBeans IDE 6.0

Author : K.Somasundaram
email : ka.somasundaram@gmail.com
--%>

<jsp:directive.page contentType="text/html" pageEncoding="UTF-8"/>

<html>
<head>
<title>Action: Include Demo</title>
</head>
<body>
<h2>This is a demo for jsp:include </h2>
<jsp:include page ="author.html" flush="true"/>
</body>
</html>

You will notice that the two parameters nam and age that the Age.jsp requires are
passed from the container JSP using param and value attributes. We mentioned earlier
that in <jsp.include> the output of the included file will be merged with the output of the

29
container page. To illustrate this we added a line in html at the end of this JSP with a text
“This is end of the result”. The output of program 25.15 when executed is shown in
Fig.25.12.

Fig. 25.12 Screen output for program 25.15

<jsp:forward>

This action element forwards the HTTP requests to a static resource, a JSP page
or a Java servlet class. A <jsp:forward> terminates the execution of the current page,
while forwarding, the current page may also add parameters, in addition to the request
parameters, and forward the request to the target JSP or Servlet. The JSP that contains
<jsp:forward> element acts as an interface between the client request and JSP/Servlet.

The syntax for <jsp :forward> has two formats. One is a simple forward and
another is forward with parameters.

<jsp:forward page = “URL”/>

or

<jsp:forward page = “URL”/>


<jsp:param = “paramname” value = “paramValue”/>
<jsp:param = “paramname” value = “paramValue”/>

30
.
.
.
</jsp:forward>

<jsp:forward> can be used to receive requests and divert them to different


destinations based on the input parameters. To illustrate this we consider the problem of
testing the obesity of a person using their height and weight as given in program 25.11.
The flow of request and response of program 25.10, 25.11 and 25.12 are given in Fig.25.

Htgwgt.jsp Height.java
Request
Hgtwgthtm.html JavaBean
Response

Client Server
Htgwgt.jsp Htgwgt.jsp
Fig.25.13 Normal request-response

Now we introduce another JSP, Hwforwrd.jsp, that will intercept the request and
inspect the value of the weight parameter. If weight>80 the request is forwarded to
sorry.jsp otherwise to Htgwgt.jsp and the flow of request-response are given in Fig.25.14.
Sorry.jsp
Response

Hwforwrd.jsp

Yes
Request Weight Forward
Htgwgthtm.htm No
>80

Forward
Response

Client

Hgtwgt.jsp

Fig.25.14

An interceptor JSP receiving the request and forwarding it to any one of the target
JSP based on the input parameter weight.

The client side html program is given in program 25.12. The only change is :
<form method = “get” action = “Hwforward.jsp”>

31
The target page and the JavaBean are given in program 25.11 and program 25.10
respectively. The interceptor JSP, named Hwforwrd.jsp and the second target page
sorry.jsp are given in programs 25.16 and 25.17.

Program 25.16 Hwforwrd.jsp


<%--
This program illustrates the use of <jsp:forward> action.
It does not do anyhting on its own. The requests addressed
to it are forwarded to another JSP named Htgwgt.jsp.

Author : K.Somasundaram
email : ka.somasundaram@gmail.com
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<html>
<% String wt = request.getParameter("weight");
double w = Double.parseDouble(wt);
String fpage = "";
if (w > 80.0) {
fpage = "sorry.jsp";
} else {
fpage = "Htgwgt.jsp";
}
%>
<jsp:forward page="<%= fpage %>" />
</html>

Program 25.17 sorry.jsp

<%--
Author : Dr. K.Somasundaram
e-mail : ka.somasundaram@gmail.com
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
<head>
<title>Sorry Page</title>
</head>
<body>
<h2>We are Sorry <%= request.getParameter("name")%>. You are too
heavy to process </h2>
</body>
</html>

32
The output screen for program 25.12 is given in Fig.25.15.

Fig2515a.bmp
(a)

Fig2515b.bmp
(b)
Fig. 25.15 Output screens for program 25.12.
(a) For weight <=80 (b) For weight >80

33
<jsp : param>

This <jsp : param> element is used to provide key/value information. This


element is used in <jsp: include>, <jsp:forward> and <jsp:plugin> elements. It should not
be used elsewhere. The syntax for this element is :

<jsp : param = “paramName” value = “paramValue”/>

where paramName is the parameter name and paramValue is the parameter value. The
value can be static or can be assigned using request-time expression. Examples of
using<jsp:param> have already been given in the previous sections.

<jsp:plugin>

This element enables a JSP page to generate HTML that contains the appropriate
client browser dependent constructs (<object> or <embed>) that will result in the
download of the Java plugin software, if needed, and subsequent execution of the Applet
or JavaBeans component specified therein. As a result the <jsp:plugin> tag is replaced
by either an <object> or <embed> tag that facilitates the display of the embedded
component. The <jsp : plugin> action element can display an applet/bean object in the
client web browser using a plug-in that is part of the browser or downloaded from a
specified URL.

The syntax of the <jsp:plugin> is:

<jsp : plugin
type = “bean/applet”
code = “ClassFileName”
codebase = “classFileDirectory”
[name = “instanceName”]
[archive = “archiveList”]
[align = “bottom/top/Middle/left/right”]
[height = “height”]
[hspace = “hspace”]
[jreversion = “jreversionNo”]
[vspace = “vspace”]
[width = “width”]
[nspluginurl = “URLtoplugin”]
[iepluginure = “URLtoplugin”]
[<jsp:params>
<jsp:param name = “pname” value = “pvalue”/>
.
.
</jsp:params>]
.
</jsp:plugin>

34
where

type - The type of the object the plugin will execute. You must specify
either a bean or an applet. There is no default value for this
attribute.

code - The name of the Java class file the plugin will execute.

codebase - The absolute or relative path to the directory that contains the
applet/bean code. If a path is not specified, the path of the JSP file
that calls <jsp:plugin> is used.

name - The name for the bean or applet.

archive - A comma separated list of paths that locate archive files to be


preloaded with a class loader located in the directory named in
codebase.

align - The alignment of the image displayed by applet/bean.

height, width - The initial height and width, in pixels, of the image the applet or
bean displays.

hspace,vspace - The amount of space, in pixels, to the left and right of the image
the applet or bean displays.

nspluginure - The URL where the user can download the JRE plugin for
Netscape Navigator.

iepluginure - The URL where the user can download the JRE plugin for Internet
Explorer.

<jsp:params> . . . </jsp : params>

- The parameter and values that you want to pass to the applet or
Bean. To specify more than one parameter and value, use multiple
<jsp:param> tags. Applets read parameters with getParameter()
method.

<jsp : fallback> text </jsp : fallback>

- A text message to display for the user if the plugin can not be
started.

35
To illustrate the <jsp: plugin> action element, we write an applet named appbook.java
that reads the author name, age, designation and the institute of the author using
getparcmeter() method and display it. This applet appbook.java is given in program
25.17.

Program 25.17 Appbook.java

import java.applet.*;
import java.awt.*;

/*
<applet code = appbook width = 250 height = 200>
</applet>
*/
public class appbook extends Applet {

public void paint(Graphics gp) {


String au = getParameter("author");
String ag = getParameter("age");
int balance = 65 - Integer.parseInt(ag);
String desg = getParameter("designation");
String inst = getParameter("institute");
gp.drawString("Author : " + au, 20, 40);
gp.drawString("Age : " + ag, 20, 60);
gp.drawString("Designation: " + desg, 20, 80);
gp.drawString("Affliation : " + inst, 20, 100);
gp.drawString("Will retire after:"+ balance+"years", 20, 120);
showStatus("Parameter method");
}
}

We then write a JSP that plug in that applet appbook.java the required parameters are
passed to the applet by the JSP through <jsp: params> tag. This JSP, named plugin.jsp, is
given in program 25.18.

Program 25.18 Plugin.jsp

<%--
This program inserts a an applet at the server side,
to be sent to the client browser and executed in the client
Browser. The required plugin to run the applet will be done
by the client browser.

Program created, compiled and executed using NetBeans IDE 6.0


Author : K.Somasundaram
email : ka.somasundaram@gmail.com
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
<head> <title>Plugin Demo</title></head>
<body>
<h2>Welcome to jsp plugin </h2>

36
<jsp:plugin type = "applet" code = "appbook.class"
codebase="WEB-INF/classess" align="middle">
<jsp:params>
<jsp:param name = "author" value = "Dr.K.Somasundram"/>
<jsp:param name = "age" value = "55"/>
<jsp:param name = "designation" value = "Professor"/>
<jsp:param name = "institute" value = "Gandhigram Rural
University"/>
</jsp:params>
<jsp:fallback> Sorry. Unable to load the specified applet>
</jsp:fallback>
</jsp:plugin>
</body>
</html>

The output of program 25.18 is given in Fig. 25.16

Fig.25.16 Screen output for program 25.18.

37

View publication stats

You might also like