You are on page 1of 46

Chapter 2 JSP

JSP
2.1 Overview:
JSP stands for “Java server page” and built by SUN Microsystem.
JSP technology is used to create web application. It focuses more on presentation logic of the
web application. JSP pages are easier to maintain then a Servlet. JSP pages are opposite of
Servlets. Servlet adds HTML code inside Java code while JSP adds Java code inside HTML.
Everything a Servlet can do, a JSP page can also do it.
JSP enables us to write HTML pages containing tags that run powerful Java programs. JSP
separates presentation and business logic as Web designer can design and update JSP pages
without learning the Java language and Java Developer can also write code without concerning
the web design.

JSP Architecture:
The web server needs a JSP engine ie., container to process JSP pages. The JSP container is
responsible for intercepting requests for JSP pages. A JSP container works with the Web server
to provide the runtime environment and other services a JSP needs. It knows how to understand
the special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web Application.

Fig: Architecture of jsp


JSP Processing:

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

The following steps explain how the web server creates the web page using JSP:
i. User requesting a JSP page through internet via web browser.
ii. The JSP request is sent to the Web Server.
iii. Web server accepts the requested .jsp file and passes the JSP file to the JSP Servlet
Engine.
iv. If the JSP file has been called
» the first time then the JSP file is parsed
» otherwise servlet is instantiated.
v. The next step is to generate a servlet from the JSP file.
[In that servlet, all the HTML code is converted in println statements.]
vi. Now, the servlet source code file is compiled into a class file (bytecode file).
vii. The servlet is instantiated by calling the init and service methods of the servlet’s life
cycle.
v. Now, the generated servlet output is sent via the Internet form web server to user's
web browser.
vi. Now in last step, HTML results are displayed on the user's web browser.
In the end, a JSP is just a Servlet.
Life Cycle:
A JSP life cycle can be defined as the entire process from its creation till the destruction which is
similar to a servlet life cycle with an additional step which is required to compile a JSP into
servlet. The following are the paths
followed by a JSP
 Compilation
 Initialization
 Execution
 Cleanup

The four major phases of JSP life cycle


are very similar to Servlet Life Cycle and
they are as follows:

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

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

JSP initialization:
When a container loads a JSP it invokes the jspInit() method which is identical in both Java
Servlet and applet. It is called first when the JSP is requested and is used to initialize objects and
variables that are used throughout the life of the JSP.
Syntax: public void jspInit(){
//Initialization code...
}

JSP execution:
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine
invokes the _jspService() method is automatically and retrieves a connection to HTTP. It will
call doGet or doPost() method of servlet created.
Syntax:
void _jspService(HttpServletRequest request,
HttpServletResponse response) {
// Service handling code... }

JSP cleanup:
The jspDestroy() method is automatically called when the JSP terminates normally. Override
jspDestroy() for cleanup where resources used during the execution of the JSP, such as such as
releasing database connections or closing open files.
Syntax: public void jspDestroy{
// Initialization code...
}

All the above mentioned steps can be shown below in the following diagram:

Fig: Flow diagram of the JSP life Cycle

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

JSP Operations in Various Scenarios:

2.2 Advantage of JSP over different technologies:

Advantage of JSP over Servlet:

 Extension to Servlet:
JSP technology is the extension to servlet technology. We can use all the features of
servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression
language and Custom tags in JSP that makes JSP development easy.

 Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In servlet technology, we mix our business logic with the presentation
logic.

 Fast Development: No need to recompile and redeploy


If JSP page is modified, we don't need to recompile and redeploy the project. The servlet
code needs to be updated and recompiled if we have to change the look and feel of the
application.

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

 Less code than Servlet


In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the
code. Moreover, we can use EL, implicit objects etc.

Advantages of JSP vs. Active Server Pages (ASP):


 First, the dynamic part is written in Java, not Visual Basic or other MS specific
language, so it is more powerful and easier to use.
 Second, it is portable to other operating systems and non-Microsoft Web servers.

Advantages of JSP Vs PHP[“Hypertext Preprocessor”]:


 First, is that the dynamic part is written in Java, which already has an extensive API for
networking, database access, distributed objects, and the like, whereas PHP requires
learning an entirely new, less widely used language.
 A second, is that JSP is much more widely supported by tool and server vendors than is
PHP.

Advantages of JSP Vs. JavaScript:


 JavaScript can generate HTML dynamically on the client but can hardly interact with the
web server to perform complex tasks like database access and image processing etc.

2.3 Basic syntax:


JSP tags are an important syntax element of Java Server Pages which start with "<%" and end
with "%>" just like HTML tags. Fundamental tags used in Java Server Pages are classified into
the following categories: -
 Comments
 Declaration tag
 Expression tag
 Scriptlet tag
 Directive tag
 Expression language tag

Tags Description Syntax


HTML Text HTML content to be passed unchanged to <H1>Blah</H1>
the client
HTML HTML comment that is sent to the client <!- - Blah - ->
Comments but not displayed by the browser <! Blah >
Comments

Text sent unchanged to the client. HTML Anything


Template
text and HTML comments are just special <\% - - - - - %\>
Text
cases of this.
JSP Developer comment that is not sent to the <%- - Blah - -%>
Comment client <%! Blah %>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

is used within a Java Server page to <%! Field Definition; %>


declare a variable or method that can be
Types of Scripting Elements
<%! Method Definition;%>
JSP referenced by other declarations, Eg:-
Declaration scriptlets, or expressions in a java server <%! int var = 1; %>
page, when page is translated into a <%! int x, y ; %>
servlet.
Expression that is evaluated at requested <%= Java Value %>
JSP Eg:-
time and sent to the client each time the
Expression <%=new java.util.Date()%>
page is requested.
<% Java Statement %>
JSP Statement or statements that are executed Eg:-
Scriptlet each time the page is requested. <% out.println("Your IP
address is " +
request.getRemoteAddr());%>
<%@ directive att="val" %>
page High-level information about the structure <%@page
JSP Directive

of the servlet code import="java.util.*"%>

code that is included at page-translation <%@ include


include: file="/header.jsp" %>
time.
<%@ taglib
used to use the custom tags in the JSP
taglib: uri="tlds/taglib.tld"
pages. prefix="mytag" %>
JSP Expression The purpose of EL is to produce scriptless ${ EL Expression }
Language JSP pages.
<jsp:actionTag>
Action that takes place when the page is ..........
JSP Action requested </jsp:actionTag>
Table 2.1: Basic Syntax of JSP
Jsp Comments[Creating Template Text]:
JSP comment marks text or statements that the JSP container should ignore. A JSP comment
is useful when you want to hide or "comment out" part of your JSP page.
There are a special constructs you can use in various cases to insert comments or characters
that would otherwise be treated specially.
Syntax Purpose
<%-- comment --%> A JSP comment. Ignored by the JSP engine.
<!-- comment --> An HTML comment. Ignored by the browser.
<\% Represents static <% literal.
%\> Represents static %> literal.
\' A single quote in an attribute that uses single quotes.
\" A double quote in an attribute that uses double quotes.

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Example 1:
Comments.jsp
<%--
Document : SimpleJsp
Created on : Mar 2, 2015, 5:09:35 AM
Author : Suma
--%>
<%@page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<%-- This comment will not be visible in the page source --%>
<p><b> Creating Template text: </b>
<\% out.println("Hello World"); \%><br>
</p>
</body>
</html>
Types of JSP Scripting Elements [invoking java code with JSP Scripting element]:
JSP scripting elements let you insert Java code into the servlet that will be generated from the
JSP page. There are three forms:
a. Declaration Tag
b. Scriptlet Tag
c. Expression Tag (For Definition refer table 2.1)
Example 2:
<html>
<head>
<title>Demo</title>
</head>
<%! int a=2, b=3; %>
<%! int sum(int x, int y){
return(x+y);
}
%>
<body>
<h1>Demo for Declaration tag</h1>
Addition of two values: <%= a+b %><br>
Addition of two values using function: <%= sum(10,20) %>
</body>
</html>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Control-Flow Statements:
JSP provides full power of Java to be embedded in your web application. You can use all
the APIs and building blocks of Java in your JSP programming including decision making
statements, loops etc.
Conditional Statements are:
 Branching Statements: if, if-else, nested else-if, else-if Ladder, switch
 Looping Statements: while, do-while, for, foreach
 Jumping Statements: continue, break

Branching / Decision Statements:


You can also use all if statements are if, if-else, nested else-if, else-if Ladder, switch in
your JSP programming.
The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each
line with HTML text included between Scriptlet tags.
Example 3:

Value.html

<html>
<head>
<title>Demo on Conditional Statements</title>
</head>
<body>
<form action="CondDemo.jsp" method="get">
Enter the Value:<input type="text" name="Evalue"/>
<input type="submit" name="Click Here"/>
</form>
</body>
</html>

CondDemo.jsp [using Scriptlet tag]

<%@page="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Check Value using Conditions</title>
</head>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

CondDemo.jsp[ using Scriptlet tag] continued

<body>
<%
String str=request.getParameter("Evalue");
if(str.equals(""))
out.println("String is Empty");
else {
int i= Integer.parseInt(str);
if(i==10)
out.println("Entered Value is Equal");
else
out.println("Entered Value is not equal");
}
%>
</body>
</html>

CondDemo.jsp [Scriptlet is closed at each line with HTML text included between
Scriptlet tags]

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Check Value using Conditions</title>
</head>

<body>
<%
String str=request.getParameter("Evalue");
if(str.equals("")) { %>
<h2>String is Empty</h2>
<% } else {
int i= Integer.parseInt(str);
if(i==10) { %>
<h3>Entered Value is Equal</h3>
<% } else { %>
<h3>Entered Value is not equal</h3>
<% } %>
</body>
</html>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Output:

Now look at the following switch...case block which has been written a bit differently using
out.println() and inside Scriptlet as:

Example 4:

CondDemo.jsp [switch statement]

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Check Value using Conditions</title>
</head>

<body>
<%
String str=request.getParameter("Evalue");
int i;
switch(i=(Integer.parseInt(str)==10)?1:0)
{
case 0: out.println("Entered Value is not Equal");
break;
case 1: out.println("Entered Value is Equal");
break;
default: out.println("Entered Proper Input");
}
%>
</body>
</html>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Looping Statements:
You can also use three basic types of looping blocks in Java: for, while, and do…while blocks
in your JSP programming.
Example 5:

Value.html

<html>
<head>
<title>Demo on Conditional Statements</title>
</head>
<body>
<form action="LoopDemo.jsp" method="get">
Enter the Value:<input type="text"
name="Evalue"/>
<input type="submit" name="Click Here"/>
</form>
</body>
</html>

LoopDemo.jsp

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


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Looping Page</title>
</head>
<body>
<% String str=request.getParameter("Evalue");
int n=Integer.parseInt(str);
int i=1;
while(i<=n)
{
out.println(i+ "<br>");
i++;
}
%>
</body>
</html>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Output:

foreach Statement:

The for-each loop is mainly used to traverse array or collection elements. The advantage of
for-each loop is that it eliminates the possibility of bugs and makes the code more readable.

Syntax:
for(data_type variable : array | collection){}

Example 6:

foreach.html

<html>
<head>
<title>foreachDemo</title>
</head>
<body>
<h1>Select knowing Laguages</h1>
<form action="LoopDemo.jsp" method="get">
<input type="checkbox" name="lang" value="C/C++" />
C/C++<br>
<input type="checkbox" name="lang" value="Java/J2EE" />
JAVA/J2EE<br>
<input type="checkbox" name="lang" value="JQuery" />
JQuery<br>
<input type="checkbox" name="lang" value="Python" />
Python<br>
<input type="submit" value="submit" name="clickhere" />
<br>
</form>
</body>
</html>
By Rama Satish K V, Dept. of MCA 1 | 46
Chapter 2 JSP

LoopDemo.jsp (Continued)

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


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-
8">
<title>Looping Page</title>
</head>
<body>
<h1>Selected Languages are</h1>
<%
String[] languages=request.getParameterValues("lang");
for(String l:languages)
out.println(l + "<br>");
%>
</body>
</html>

Output:

Jumping Statements:
You can also use jumping statements are break, continue in the JSP Programming.
Example 7:

index.html
<html>
<head>
<title>Demo on Looping Statements</title>
</head>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

<body>
<form action="LoopDemo.jsp" method="get">
Enter the Value:<input type="text" name="Evalue"/>
<input type="submit" value="Click Here"/>
</form>
</body>
</html>

LoopDemo.jsp

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


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-
8">
<title>Looping Page</title>
</head>
<body>
<% String str=request.getParameter("Evalue");
int n=Integer.parseInt(str);
int i=1;
while(i<=n){
if(i==5)
break;
else{
out.println(i+ "<br>");
i++;
}
}
%>
</body>
</html>
Output:

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Invoking Java Code from JSP:

There are a number of different ways to generate dynamic content from JSP, as illustrated in the
below figure.

 Call Java code directly: Scripting elements calling servlet


code directly.

 Call Java code indirectly: Scripting elements calling


servlet code indirectly (by means of utility classes).
JSP Directives:
 Use beans: Develop separate utility classes structured as
beans. Use jsp:useBean, jsp:getProperty etc.

 Use the MVC architecture: Have a servlet respond to


original request, look up data, and store results in beans.
Forward to a JSP page to present results. JSP page uses
beans.

 Expression Language: Use shorthand syntax to access and


output object properties.

 Custom tags: Develop tag handler classes. Invoke the tag


handlers with XML-like custom tags.

Fig: Strategies for invoking dynamic code from JSP.


Each of these approaches has a legitimate place; the size and complexity of the project is the
most important factor in deciding which approach is appropriate. However, be aware that people
err on the side of placing too much code directly in the page much more often than they err on
the opposite end of the spectrum. Although putting small amounts of Java code directly in JSP
pages works fine for simple applications, using long and complicated blocks of Java code in JSP
pages yields a result that is hard to maintain, hard to debug, hard to reuse, and hard to divide
among different members of the development team. For Details, see the following stages.

Limiting java code in JSP:


You have 25 lines or more lines of Java code that you need to invoke. You have two options:
i. Put all 25 lines directly in the JSP page
ii. Put the 25 lines of code in a separate Java class, put the Java class in WEB-INF / classes
/directoryMatchingPackageName, and use one or two lines of JSP-based Java code
to invoke it.

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Which is better? The second. Here’s Why?

 Development: You generally write regular classes in a Java-oriented environment (e.g.,


an IDE like JBuilder, Eclipse or editor like UltraEdit, emacs). You generally write JSP in
an HTML oriented environment like Dreamweaver.

The Java-oriented environment is typically better at balancing parentheses, providing


tooltips, checking the syntax, colorizing the code, and so forth.

 Compilation: To compile a regular Java class, you press the Build button in your IDE or
invoke javac. To compile a JSP page, you have to drop it in the right directory, start the
server, open a browser, and enter the appropriate URL.

 Debugging: We know this never happens to you, but when we write Java classes or JSP
pages, we occasionally make syntax errors. If there is a syntax error in a regular class
definition, the compiler tells you right away and it also tells you what line of code
contains the error. If there is a syntax error in a JSP page, the server typically tells you
what line of the servlet (i.e., the servlet into which the JSP page was translated) contains
the error. For tracing output at runtime, with regular classes you can use simple
System.out.println statements if your IDE provides nothing better.

 Division of labor: Many large development teams are composed of some people who are
experts in the Java language and others who are experts in HTML but know little or no
Java. The more Java code that is directly in the page, the harder it is for the Web
developers (the HTML experts) to manipulate it.

 Testing: Suppose you want to make a JSP page that outputs random integers between
designated 1 and some bound (inclusive). You use Math.random, multiply by the range,
cast the result to an int, and add 1.

Example: return(1 + ((int)(Math.random() * range)));

If you do this directly in the JSP page, you have to invoke the page over and over to see if
you get all the numbers in the designated range but no numbers outside the range. After
hitting the Reload button a few dozen times, you will get tired of testing. But, if you do
this in a static method in a regular Java class, you can write a test routine that invokes the
method inside a loop and then you can run hundreds or thousands of test cases with no
trouble. For more complicated methods, you can save the output, and, whenever you
modify the method, compare the new output to the previously stored results.

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Example:

public class RanUtilities {


/*A random int from 1 to range (inclusive)*/

public static int randomInt(int range) {


return(1 + ((int)(Math.random() * range)));
}
/*Test routine. Invoke from the command line with the desired
range. Will print 100 values. Verify that you see values from
1 to range (inclusive)and no values outside that interval.*/

public static void main(String[] args) {


int range = 10;
try {
range = Integer.parseInt(args[0]);
}
catch(Exception e) { // Array index or number format
// Do nothing: range already has default value.
}

for(int i=0; i<100; i++) {


System.out.println(randomInt(range));
}
}
}

 Reuse: You put some code in a JSP page. Later, you discover that you need to do the
same thing in a different JSP page. What do you do? Cut and paste? Boo! Repeating code
in this manner is a cardinal sin because if you change your approach, you have to change
many different pieces of code. Solving the code reuse problem is what object-oriented
programming is all about. Don’t forget all your good OOP principles just because you are
using JSP to simplify the generation of HTML.

Using Scripting Elements, Comparing servlets and jsp:


Example 8: illustrate the difference in how the three JSP scripting elements are typically used by
calling the java code indirectly.

cssStyle.css

body {
background-color: #ffdd88;
font-family: CurlZ MT, tahoma, helvetica, arial,;
font-size: 1.9em;
}

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

ScriptletPage.jsp

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


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
<link rel=stylesheet href="cssStyle.css" type="text/css">
</head>

<%! int n=5;%> <!Delcaration Tag>


<body>
<%
for(int i=0;i<n;i++) { %> <!Scriptlet Tag>
<!Expression Tag>
<%= Corepack.DisplayUtilities.display()%><br>
<%}%><!Scriptlet Tag>

</body>
</html>

DisplayUtilities.java

package Corepack;

public class DisplayUtilities {


public static String display()
{
return("Welcome");
}
}
Output:

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

In the above example, the goal is to generate a message of n times using scripting elements and
compare how the statements are translated into the servlet from the JSP page as shown below.
Since the structure of this page is fixed and we use a separate helper class for the display
method.
 JSP declarations result in code that is placed inside the servlet class definition but
outside the _jspService method. Since fields and methods can be declared in any order,
it does not matter whether the code from declarations goes at the top or bottom of the
servlet.

 JSP Expression result in code that we oversimplified the out variable (which is a
JspWriter, not the slightly simpler PrintWriter that results from a call to getWriter).

» JSP expressions basically become print (or write) statements in the servlet that
results from the JSP page.
» Whereas regular HTML becomes print statements with double quotes around
the text, JSP expressions become print statements with no double quote.

 JSP Scriptlets can perform a number of tasks that cannot be accomplished with
expressions alone. These tasks include setting response headers and status codes,
invoking side effects such as writing to the server log or updating a database, or
executing code that contains loops, conditionals, or other complex constructs.
It is easy to understand how JSP scriptlets correspond to servlet code: the Scriptlet code
is just directly inserted into the _jspService method: no strings, no print statements, no
changes whatsoever.

..... }

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Note: JSP expressions contain Java values and JSP scriptlets contain Java statements.

Controlling the Structure of generated servlets:


The JSP page directive:

JSP directives provide directions and instructions to the container, telling it how to handle certain
aspects of JSP processing.

A JSP directive affects the overall structure of the servlet class. It usually has the following form:

Syntax: i. <%@ directive attribute="value" %>

ii. <%@ directive attribute1="value1" attribute2="value2"


................
attributeN="valueN" %>

Note:
 Directives can have a number of attributes which you can list down as key-value pairs
and separated by commas.

 The blanks between the @ symbol and the directive name, and between the last attribute
and the closing %>, are optional.

 To obtain quotation marks within an attribute value, precede them with a backslash, using \’ for ’
and \" for ".

In JSP, there are three main types of directives:

i. <%@ page . . . %> Let’s you control the structure of the servlet by importing classes,
customizing the servlet superclass, setting the content type, and
the like.

ii. <%@ include . . . %> Let’s you insert a file into the JSP page at the time the JSP file is
translated into a servlet.

iii. <%@ taglib . . . %> defines custom markup tags.

i. The “page” attribute:

The page directive is used to provide instructions to the container that pertain to the current
JSP page.

The page directive can define one or more of the following attributes and all are case-sensitive:

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Sl.
Attributes Description
No.

i. import is used to define a set of class, interface or all the members of a package
that must be imported in servlet class definition
Syntax:

 <%@ page import = "package.class" %>

 <%@ page import = "package.class1,.......,


package.classN" %>

Note: By default, the servlet imports following packages :


java.lang.*; javax.servlet.*; javax.servlet.jsp.*; javax.servlet.http.*;

For example: Refer Example-a

ii. contentType Defines the MIME (Multipurpose Internet Mail Extension) type of the
HTTP response.
Syntax:

 <%@ page contentType = “MIME Type" %>

 <%@ page contentType = “MIME Type”


charset = “Character - Set” %>

Note: By default value is "text/html; charset=ISO-8859-1".

For example: Refer Example-b

iii. pageEncoding is used to change the character set.


Syntax:

 <%@ page pageEncoding=" ISO-8859-1" %>


You can change this by specifying US-ASCII, Shift-JIS and etc.,

For example: Refer Example-b

iv. session Specifies whether or not the JSP page participates in HTTP sessions
Syntax:

 <%@ page session = “true" %>

 <%@ page session = “false” %>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

It can have two values: true or false.


Default value is true: which means if you do not mention this attribute,
server may assume that HTTP session is required for this page.
For example: Refer Example-c

v. isELIgnored Specifies whether the JSP Expression Language (EL) is ignored (true)
or evaluated normally (false).
Syntax:
 <%@ page isELIgnored = “true" %>

 <%@ page isELIgnored = “false” %>


//By default false means EL is enabled

It can have two values: true or false.


Default value is false: which means Expression Language is enabled by
default.
For example: Refer Example-d

vi. buffer specifies the buffer size in kilobytes used by the out variable, which is
of type JspWriter.
Syntax:
 <%@ page buffer = “size kb" %>

 <%@ page buffer = “none” %>

Note:
 Default size is 8Kb
 Servers can use a larger buffer than you specify, but not a
smaller one.
For example: Refer Example-e

vii. autoFlush specifies whether the output buffer should be automatically flushed
when it is full (the default) or whether an exception should be raised
when the buffer overflows ( autoFlush="false").
Syntax:

 <%@ page autoFlush = “true" %>

 <%@ page autoFlush = “false” %>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

It can have two values: true or false

Default value is true : which means automatically flushed when


buffered is full

For example: Refer Example-e

A value of false is illegal when buffer="none" as shown below:

 <%@ page buffer=“none” autoFlush=“false” %>

viii. info defines a string that can be retrieved from the servlet by means of the
getServletInfo method.
Syntax:

 <%@ page info = “some message" %>

For example: Refer Example-f

ix. errorPage is used to define the error page, if exception occurs in the current page,
it will be redirected to the another JSP Page by the runtime.
Syntax:

 <%@ page errorPage = “RelativeURL” %>

The exception thrown will automatically be available to the designated


error page by means of the exception variable.

For example: Refer Example-g

x. iserrorPage indicates whether or not the current page can act as the error page for
another JSP page.
Syntax:

 <%@ page isErrorPage = “true” %>

 <%@ page isErrorPage = “false” %>

It can have two value: true or false

Default is false: which means not an error page.

For example: Refer Example-g

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

xi. isThreadSafe Servlet and JSP both are multithreaded. You can control that using
“isThreadSafe” atttribute.
Syntax:

 <%@ page isThreadSafe = “true” %>

 <%@ page isThreadSafe = “false” %>

The default value of isThreadSafe is true.

If you make it false, the web container will serialize the multiple
requests, i.e. it will wait until the JSP finishes responding to a request
before passing another request to it.

For Example: Refer Example-h

xii. language The “language’ attribute is intended to specify the scripting language
being used.
Syntax:

 <%@ page language = “java” %>


Default is java. But its support C++, PHP and other Scripting language
For Example: Refer Example-i

xiii. extends It specifies the superclass of the servlet that will be generated for the
JSP page.
Syntax:

 <%@ page extends= “package.class” %>

For Example: Refer Example-i

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Examples for the page directive attributes:


Example-a:

<%@page import="java.util.Date" contentType="text/html"


pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
</body>
</html>

Output:

Example-b:

Welcome.java

package JavaPack;

public class Welcome {


public static String display()
{
return("Welcome");
}
}
Contentandpage.jsp
<%@page import="java.util.Date,JavaPack.*"
contentType="application/msword"
pageEncoding="Shift-JIS"%>
<!DOCTYPE html>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Contentandpage.jsp [continued]

<!html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= Welcome.display()%>
</body>
</html>

Output:

Example-c:

sessionAtt.jsp
<%@page import="java.util.Date,JavaPack.*"
contentType="text/html" pageEncoding="Shift-JIS"
session= "true"%>
<!DOCTYPE html>
<!html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= Welcome.display()%>
</body>
</html>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Output:

Example-d:

ReadEL.html

<html>
<head>
<title>Expression Language</title>
</head>
<body>
<form action="ExprLang.jsp">
Enter name: <input type="text" name="uname" /> <br><br>
<input type="submit" value="click here" />
</form>
</body>
</html>

ExprLang.jsp

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


isELIgnored="true"%>
<!DOCTYPE html>
<html>
<body>
Welcome, ${param.uname}
</body>
</html>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Output:

if attribute value is true, then: ignored EL so output as shown below:

Example-e:

buffAflush.jsp

<%@page import="java.util.Date,JavaPack.*"
contentType="text/html"
pageEncoding="Shift-JIS"
session= "true"
buffer="16kb"
autoFlush="true"%>
<!DOCTYPE html>
<!html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
<link rel=STYLESHEET href="stylesheet.css" type="text/css">
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= Welcome.display()%>
</body>
</html>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Example-f:
infoAtt.jsp
<%@page import="java.util.Date,JavaPack.*"
contentType="text/html"
pageEncoding="Shift-JIS"
info="Composed by Sonu Nigam"%>
<!DOCTYPE html>
<!html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
<link rel=STYLESHEET href="stylesheet.css"
type="text/css">
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= Welcome.display()%>
</body>
</html>

Output:

Example-g:

ErrorDemo.jsp

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


errorPage="SendError.jsp"%>
<!DOCTYPE html>
<html>
<head>
<title>Error Page Demo</title>
</head>
<%! int a=0;%>
<body>
Result: <%= 100/a %>
</body>
</html>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

SendError.jsp

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


isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<title>Caught Error</title>
</head>
<body>
<h3>Sorry an exception occured!</h3><br/>
<h2>The exception is: <%= exception %> </h2>
</body>
</html>

Output: If A=2: If A=0:

Example-h:

threadDemo.jsp

<%@page import="java.util.Date,JavaPack.*"
contentType="text/html" pageEncoding=" UTF-8"
isThreadSafe="false"%>
<!DOCTYPE html>
<!html>
<head>
<title>Attributes demo</title>
<link rel=STYLESHEET href="stylesheet.css" type="text/css">
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= Welcome.display()%>
</body>
</html>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Output:

Example-i:

<%@page import="java.util.Date,JavaPack.*"
contentType="text/html"
pageEncoding="Shift-JIS"
language="java"
extends="org.apache.jasper.runtime.HttpJspBase"
%>
<!DOCTYPE html>
<!html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Attributes demo</title>
<link rel=STYLESHEET href="stylesheet.css" type="text/css">
</head>
<body>
<h1>Today Time is: <%= new Date() %></h1>
<%= Welcome.display()%>
</body>
</html>

XML Syntax for Directives:

If you are writing XML-compatible JSP pages follow the below syntax:

 <jsp:directive.directiveTypeattribute = “value” >


Example: <%@ page import="java.util.*" %>

XML equivalent as follows below:

<jsp:directive.page import="java.util.*" />

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

ii. The “include” attribute:

The include directive tells the Web Container to copy everything in the included file and
paste it into current JSP file.

Syntax: <%@ include file="filename.jsp" %>


Example:

Welcome.jsp

<html>
<head>
<title>Welcome Page</title>
</head>

<body>
<%@ include file="header.jsp" %>
Welcome, User
</body>
</html>

Header.jsp

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


<!DOCTYPE html>
<html>
<body>
<img src="images8.jpg" alt="This is Header image" / >
</body>
</html>

Output:

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

iii. The “Taglib” directive:

The JSP taglib directive is used to define a tag library that defines many tags. We use the
TLD (Tag Library Descriptor) file to define the tags. In the custom tag section we will use
this tag so it will be better to learn it in custom tag.

Syntax: <%@ taglib uri="uriofthetaglibrary"


prefix="prefixoftaglibrary" %>

Example: <%@ taglib uri="http://www.javapoint.com/tags" prefix="mytag" %>

JSP Action Tags:


There are many JSP action tags or elements. Each JSP action tag is used to perform some
specific tasks.

Action Tags Descriptions


forward forward the request to a new page
param Adds parameters to the request
include Includes a file at the time the page is requested
plugin Generates client browser-specific construct that makes an OBJECT or
EMBED tag for the Java Applets
element Defines XML elements dynamically
attribute defines dynamically defined XML element's attribute
fallback Supplies alternate text if java applet is unavailable on the client
body Used within standard or custom tags to supply the tag body.
text Use to write template text in JSP pages and documents.
getProperty retrieve a property from a JavaBean instance.
setProperty store data in JavaBeans instance.
useBean instantiates a JavaBean

All the above action tag have to write using syntax as mentioned below:

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Syntax:
<jsp:ActionTags Attribute= “names” >

<!- - Write any child tags- - >

</jsp:ActionTags>

i. forward action tag:

It is used to forward the request to another resource it may be jsp, html or another
resource.

Syntax:

Without Parameter
<jsp:forward page= “RelativeURL / <%= ExpressionTag %>” >
<!- - Write zero or more param tags- - >
</jsp:forward>

With Parameter
<jsp:forward page= “RelativeURL / <%= ExpressionTag %>” >
<jsp:param name=“paramname” value=“parmavalue”/>
</jsp:forward>

Example:

forwardDemo.jsp

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


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>This is ForwardDemo.jsp</h1>
<jsp:forward page="printDate.jsp">
<jsp:param name="user" value="suma"/>
</jsp:forward>
</body>
</html>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

printDate.jsp

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


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Print Date Page</h1>
Today date is <%= new java.util.Date()%> <br>
<%= request.getParameter("user")%>
</body>
</html>

Output:

ii. include action tag:


This tag is used to include the content of another resource it may be jsp, html or servlet
at request time.
Syntax:
Without Parameter

<jsp:include page= “RelativeURL / <%= ExpressionTag %>” >


<!- - Write zero or more param tags- - >
</jsp:include>

With Parameter

<jsp:include page= “RelativeURL / <%= ExpressionTag %>” >


<jsp:param name=“paramname” value=“parmavalue”/>
</jsp:include>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Example:
includeDemo.jsp

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


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Demo on include action tag</h1>
<jsp:include page="printDate.jsp">
<jsp:param name="user" value="suma"/>
</jsp:include>
</body>
</html>

printDate.jsp

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


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Print Date Page</h1>
Today date is <%= new java.util.Date()%> <br>
<%= request.getParameter("user")%>
</body>
</html>

Output:

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Difference b/n jsp:include and include directive

include Directive
jsp:include
<%@include ----- %>
includes resource at translation time. includes resource at request time.

better for static pages. better for dynamic pages.

includes the original content in the


calls the include method.
generated servlet.

org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response,
"printDate.jsp" + "?" +
rg.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("user",
request.getCharacterEncoding())+ "=" +
org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("suma",
request.getCharacterEncoding()), out, false);

iii. “plugin” action tag:

It is used to embed applet or bean in the jsp file. The jsp:plugin action tag downloads
plugin at client side to execute an applet or bean.
Syntax:

<jsp:plugin type=“applet/bean” code=“nameofclassfile.class”


codebase=“directorynameofclassfile” width=“pxl”
height=“pxl”>
</jsp:plugin>

Applet attributes list below:


Attributes Description
type = "bean/applet" bean or applet object executed by the plugin.
A java class file which has to be executed by the plugin.
code = "classFileName"
Extension of this file name must be the .class.
codebase = Directory name of the Java class file. i.e., directory of code
"classFileDirectoryName" attribute classFileName.
align Specifies the alignment
archive Specifies the list of archives
height Specifies the height
width Specifies the width

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

jreversion Specifies the version of jre.


hspace Specifies the horizontal space.
vspace Specifies the name of vertical space.
name Specifies the name of component.
overrides the default url where the plug in can be
nspluginurl
downloaded.
overrides the default url where the plug in can be
iepluginurl
downloaded.

<jsp:plugin> tags generates the element <OBJECT> or <EMBED> tags during the action time.

Example:

pluginDemo.jsp

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


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<jsp:plugin height="500" width="500" type="applet"
code="JspPluginApplet.class" codebase="."/>
</body>
</html>

JspPluginApplet.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;

public class JspPluginApplet extends Applet {


public void paint(Graphics g){
Calendar cal = new GregorianCalendar();
String hour = String.valueOf(cal.get(Calendar.HOUR));
String minute = String.valueOf(cal.get(Calendar.MINUTE));
String second = String.valueOf(cal.get(Calendar.SECOND));
g.drawString(hour + ":" + minute + ":" + second, 20, 30);
}
}

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Output:

iv. “fallback” action tags:

This element which is used by the client browser in case the plugin cannot be started, that do
not support for OBJECT or EMBED. This action cannot be used elsewhere outside the
<jsp:plugin> action.
Syntax:

<jsp:plugin type=“applet/bean” code=“nameofclassfile.class”


codebase= “directorynameofclassfile” width=“pxl”
height=“pxl” >
<jsp:fallback>
Message displayed in case of plugin not loaded during the runtime.
</jsp:fallback>
</jsp:plugin>

v. “params” action tags:

A jsp:param entries must be enclosed within a “jsp:params” element. This action cannot
be used elsewhere outside the <jsp:plugin> action.
Syntax:
<jsp:plugin page= “RelativeURL / <%= ExpressionTag %>” >
<jsp:params>
<jsp:param name=“paramname1” value=“parmavalue1”>
<jsp:param name=“paramname2” value=“parmavalue2”>
</jsp:params>
</jsp:plugin>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Example:

pluginDemo.jsp

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


<!DOCTYPE html>
<html>
<head>

<meta http-equiv="Content-Type" content="text/html;


charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<jsp:plugin height="300" width="350" type="applet"
code="JspPluginApplet.class" codebase=".">
<jsp:params>
<jsp:param name="uname" value="Tom"/>
</jsp:params>
<jsp:fallback> Error! plugin not started
</jsp:fallback>
</jsp:plugin>
</body>
</html>

JspPluginApplet.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.JApplet;
import javax.swing.JLabel;

public class JspPluginApplet extends JApplet {


public void init() {
label.setHorizontalAlignment(JLabel.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 20));
label.setForeground(Color.BLUE);
setLayout(new BorderLayout());
add(label, BorderLayout.CENTER);
}
private JLabel label = new JLabel();
public void start(){
String uname=getParameter("uname");
label.setText("Hello " + uname);
}
}

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Output:

vi. useBean action tags:

Beans are simply Java classes that are written in a standard format( javaBeans API).

Following are the unique characteristics that distinguish a JavaBean from other
Java classes:
● It provides a default, no-argument constructor.
● It should be serializable and implement the java.io.Serializable interface.
● It may have a number of properties which can be read or written.
● It may have a number of "getter" and "setter" methods for the properties.
● Class must not define any public instance variables.

Advantages:
 it is a reusable software component.
 A bean encapsulates many objects into one object, so we can access this object
from multiple places. Moreover, it provides the easy maintenance.
 No Java Syntax

Basic Tasks of useBean:


You use three main constructs to build and manipulate JavaBeans components in JSP pages:

<jsp:useBeans> This element builds a new bean.


Syntax:

<jsp:useBean id=“beanName” class=“package.class”


scope=“page| request | session | application” />

Example:
<jsp:useBean id=“person” class=“PersonBean” scope=“request”/>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

jsp:getProperty This element reads and outputs the value of a bean property.
Syntax:

<jsp:getProperty name= “beanName”


property= “propertyName” />

Example:
<jsp:getProperty name=“person” property=“name”/>
jsp:setProperty This element modifies a bean property.
Syntax:

<jsp:setProperty name= “beanName”


property= “propertyName” />

Example:
<jsp:setProperty name=“person” property=“name”/>
The setProperty tag is used to store data in JavaBeans instances. The syntax of setProperty
tag is
<jsp:setProperty name="beanName" property="*" >
or
<jsp:setProperty name="beanName" property="propertyName">
or
<jsp:setProperty name="beanName“ property="propertyName"
param="parameterName" >
or
<jsp:setProperty name="beanName" property="propertyName"
value="propertyValue" >

Example:

useBeanDemo.jsp

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


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

useBeanDemo.jsp [continued]

<jsp:useBean id="bean" class="bean.PersonBean"/>


<body>
<h2> Welcome,
<jsp:getProperty name="bean" property="name"/>
</h2><hr>
<jsp:setProperty name="bean" property="name"
value="Sachin"/>
<h3> Hello,
<jsp:getProperty name="bean" property="name"/></h3>
</body>
</html>

package bean;

import java.io.Serializable;

public class PersonBean implements Serializable{


//you should not have public fields and name should be unique
private String name;

//Default Constructor
public PersonBean(){
this.name="RNSIT";
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
}

Output:

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

Generating Excel Spreadsheet:

First Last Email Address


Marty Hall hall@corewebprogramming.com
Larry Brown brown@corewebprogramming.com
Bill Gates gates@sun.com
Larry Ellison ellison@microsoft.com
<%@ page contentType="application/vnd.ms-excel" %>
<%-- There are tabs, not spaces, between columns. --%>

Output:

Conditionally Generating Excel Spreadsheet:

<!html>
<head>
<title>Attributes demo</title>
<link rel=stylesheet href="stylesheet.css" type="text/css">
</head>
<body>
<h2>List of Names and Address</h2>
<% String str=request.getParameter("format");
if(!str.isEmpty()&& str.equals("excel"))
response.setContentType("application/vnd.ms-excel");
%>
<TABLE BORDER=1>
<TR><TH>First</TH><TH>Last</TH><TH>Email Address</TH></TR>
<TR><TD>Marty</TD><TD>Hall</TD><TD>hall@corewebprogramming.com
</TD></TR>
<TR><TD>Larry</TD><TD>Brown</TD><TD>brown@corewebprogramming.com
</TD></TR>

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

<TR><TD>Bill</TD><TD>Gates</TD><TD>gates@sun.com</TD></TR>

<TR><TD>Larry</TD><TD>Ellison</TD><TD>ellison@microsoft.com
</TD></TR>
</TABLE>
</body>
</html>

Output:

Implicit Objects:

Implicit
Description
Object
request The HttpServletRequest object associated with the request.
The HttpServletRequest object associated with the response that is sent
response
back to the browser.
out The JspWriter object associated with the output stream of the response.
The HttpSession object associated with the session for the given user of
session
request.
application The ServletContext object for the web application.

config The ServletConfig object associated with the servlet for current JSP page.

By Rama Satish K V, Dept. of MCA 1 | 46


Chapter 2 JSP

The PageContext object that encapsulates the enviroment of a single


pageContext
request for this current JSP page
The page variable is equivalent to this variable of Java programming
page
language.
The exception object represents the Throwable object that was thrown by
exception
some other JSP page.

By Rama Satish K V, Dept. of MCA 1 | 46

You might also like