0% found this document useful (0 votes)
10 views

ch 6 Notes

Uploaded by

rudraghankute07
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

ch 6 Notes

Uploaded by

rudraghankute07
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

MIT ART DESIGN & TECHNOLOGY UNIVERSITY

MIT College of Management (MITCOM), Pune

PROGRAMME: BCA

COURSE – BCA - SEM III

Second Year Semester III

Web Technology-I

Complied by Prof. Snehal Patil

Unit 6 Java script Control statements and Functions

6.1 JS Control Statements and JS Functions


6.2 JavaScript HTML DOM Events (on mouse up, on mouse down,
on click, on load, on mouse over, on mouse out).
6.3 JS Strings and JS String Methods
6.4 JS popup boxes (alert, confirm, prompt).

UNIT- 5: Creation of Dynamic Web Pages using JSP

5.0 Objective

A server-side dynamic web page is created by using server-side


scripts which are processed by an application server. The application
server controls the server-side dynamic web page. The parameters
of the server-side script determine the assembling of every new web
page that incorporates more customer side handling. The following
unit explains core concepts of creating dynamic web pages and
introducing the concepts of JSP. It also sheds light on JSP scripting
and page directive. With the help of this unit the reader will be able
to create the web pages dynamically and use various scripting.

5.1 Dynamic Web Page

Dynamic web page is one which reveals different information at


different time. A part of the web page can be changed easily rather
than loading the entire web page or document of the web page. To
make any change in the content of the web page, the dynamic web
page is reloaded by user or program. The server or the updated DOM
(document object model) of the page can call the updating
information. This can either lead to the truncation of the browsing
history or can create a saved version to go back to it. The advantage
of using Ajax technologies to update a dynamic web page will
eradicate this i.e. it will neither truncate the web browsing history of
the page being displayed nor create a page to go back. In spite of
varying webpage content, the Ajax technology renders the end user
only one dynamic page managed as a single page. The Ajax engine
resides on the browser only, requesting parts of the DOM (from an
application server to its clients).
The following are two types of web pages:
5.1.1 Server-Side Dynamic Web Page
Server-side scripting is used to create server-side dynamic web page.
The parameters of the server-side script determine the assembling of
every new web page that incorporates more customer side handling.
5.1.2 Client-Side Dynamic Web Page
Client-side scripting such as JavaScript is used to process client-side
dynamic web page. The script is then passed to the Document Object
Model (DOM).

5.2 Introduction to JSP (Java Server Pages)


Dynamic web applications can be developed using JSP technology.
The JSP pages are much easier to maintain than a Servlet. JSP pages
are quiet opposite of Servlets, as servlet embeds HTML code inside a
Java code, while JSP embeds Java code inside HTML with the help of
JSP tags. The JSP can perform every task a Servlet can do. The
Presentation and Business logic are easily separable in JSP as a web
designer design and update JSP pages using presentation layer
whereas, a java developer write server-side complex codes without
being concerned about web design. The presentation layer and the
business layer can easily interact over HTTP requests. The java codes
can be easily embedded into HTML tags in JSP.
Java Server Pages is a server-side technology which does all the
processing at server. It is generally used to create dynamic web
applications using java. Any html file can be easily converted to a JSP
file only by changing the file extension from “.html” to “.jsp”, and it
will run just fine. JSP differs from HTML in ability of using java code
inside HTML. In JSP, Java code is embedded in HTML using JSP tags.
For e.g. every time we run this code, it will display the current time.
This shows this code is dynamic.
<HTML>
<BODY>
Hi Beginner
Current time of the day: <%= new java.util.Date() %>
</BODY>
</HTML>

5.2.1 Your First JSP


Let us start our reading by a JSP
example Example:

<%-- JSP comments -- %>


<HTML>
<HEAD>
<TITLE>Title </TITLE>
</HEAD>
<BODY>
<%out.print ("This is a Sample JSP code");%>
</BODY>
</HTML>

Output:

This is a Sample JSP code.


5.2.2 Explanation of above code:

i) <%–JSP Comment–%>: This represent JSP Comments. This tag


is used for adding comments to a JSP page. Further details will be
discussed later
Note: Comments starts with a tag <%– and ends with –%>.

ii) The HTML tags like Head, Title and Body are frequently used.
The content within these tags will be delivered in a similar way to
client (Web browser).

iii) Scriptlets are the JSP elements that contain Java codes. <
%out.print (“Sample JSP code”) ;%> is an example of Scriptlet. Syntax
of scriptlet is: <%Executable java code%>. As the java code ends with
semicolon (;), so, the Scriptlets. out.print (“Sample JSP code”) is a
java statement, which prints“Sample JSP code ”.

Both static and dynamic contents are there in dynamic webpages.


Static content will have only text-based formats defined in HTML or
XML whereas, the java code embedded inside the HTML used as JSP
tags generates the dynamic content.

5.2.3 Difference between Servlet & JSP


Like JSP, Servlets also generates dynamic webpages. One of the
major difference is that servlet embed HTML code inside java while
the JSP does the opposite. Few other points are:

Servlets
1. A Servlet is a Java program.
2. Servlets supports HTML tags.
3. It is used for developing the business layer of an enterprise
application.
4. Java developers create and maintain the servlets.

JSP
1. JSP program is a HTML code.
2. It supports the java statements by embedding it into HTML
using JSP tags.
3. Differentiate the presentation layer and business layer. So,
both can be developed separately easily of an enterprise
application
4. Web developers uses JSP frequently used for designing
websites.

5.2.4 Advantages of JSP over Servlet


1. JSP has the preferences of servlet, as it gives better
performance than CGI built-in session features. It also inherits
java features like – multithreading, database connectivity,
exception handling and few more.
2. JSP also separates the content generation from content making
it more flexible.
3. With the use of the JSP, it will be now easy for a web designer
to present the information needed.
4. The web application programmers can now fully concentrate
on processing/building the information.

5.2.5 JSP Application Architecture


Before starting to develop a web application, we must have a basic
idea of its architecture. Based on the request processing location
(Servlet or JSP) two architectures for JSP has been formulated which
are– Model1 Architecture & Model2 Architecture.

1) Model 1 Architecture: In case of the Model 1 architecture JSP


will play key role. All the requests made by the client are processed
by JSP. A bean object is created by JSP as the client (web browser)
requests. The created object completes the request and passes the
response to the JSP. The response is sent by JSP to the client. In this
model, JSP performs most of the processing. Figure 5.1 represents
Model 1 Architecture.

Figure 5.1: Model 1 Architecture

2) Model 2 Architecture: In Model 2, the major role is played by


servlets and the client’s (web browser) request is processed by it.
The JSP only takes care of the presentation part (GUI part) by using
bean object created by servlet. Here, the controlling and request
processing tasks is performed by servlet only. The bean object is
created by servlet when required by the JSP page and then calls the
respective JSP page as the request made by client. For this type of
Model, JSP doesn’t do any type of processing whereas, Servlet
performs all the required processing. Figure 5.2 shows Model 2
Architecture.
Figure 5.2: Model 2 Architecture

5.3 Pages Overview

Java Server Pages (JSP) is an innovation which is utilized for building


up the Webpages that backings dynamic substance conveyance. It
helps the developers to embed java code in HTML pages, which
makes the utilization of JSP tags, Java Server Pages which begin with
<% and end with %> is generally a sort of servlet which fulfills the
role of a user interface is designed that is towards a Java web
application. Utilizing Java Server Pages, we can present records from
a database and could gather users through Webpage forms. Web
developers generally compose text files such as JSPs that combines
HTML or XHTML code. Or any other source, that creates Webpages
dynamically. These JSP tags are utilized for several purposes such by
accessing the JavaBeans components, as gathering database
information or registering user preferences, sharing information
between requests and passing control from one page onto the next,
and pages etc.

5.3.1 Why Use JSP?


JSP is similar to Common Gateway Interface (CGI). In case JSP provide
several advantages over CGI:
• Altogether better performance is provided because JSP embeds
Dynamic Elements in HTML Pages as opposed to have
distinguishable CGI files.
• The server always compiles JSP before processing whereas, the
server loads the interpreter and the target script each time the
page is requested in CGI/Perl.
• JSP are built over Java Servlets API, so JSP can use all the
powerful Enterprise which include JDBC, JNDI Java APIs, EJB,
JAXP, and so on.
• JSP pages that handle the business logic can be used in
combination with servlets
• This is supported by the Java servlet template engines model.

We lastly conclude that an integral part of Java EE, is JSP which is a


complete enterprise class applications platform. This illustrate that
JSP plays a major role from the simplest applications to the most
complex and demanding one.

5.3.2 Advantages of Using JSP


Following are the advantages of JSP over other technologies:
Versus Active Server Pages (ASP) technology
The twofold advantages using JSP are: a) The dynamic part written in
Java is more powerful and easier as compared to different MS
specific language like Visual Basic. b) It is versatile to nonMicrosoft
Web servers and other operating systems.
Versus Pure Servlets technology
Most convenient part is to adjust and to write customary HTML
rather to have a lot statements that produce the HTML like println.
Versus Server-Side Includes (SSI) technology
SSI is intended extremely intended that utilize form data for basic
inclusions, it makes database connections, and so forth.
Versus JavaScript technology
HTML could be however created dynamically on the client that can
barely interact to perform complex assignments with the web server
like image processing and database access and so forth.
Versus Static HTML
Normal regular HTML as it is statically defined cannot contain
dynamic information.

5.3.3 JSP Architecture

Figure 5.3: JSP Architecture


The above diagram shows the JSP architecture. can The JSP page of
web container is directly accessed by the web browser. The
JavaBeans of the web container representing the application model
is interacted by JSP pages. Upon request made by the client through
JSP page, the response is sent back to the client depending on the
requests which are invoked by the client request. The JavaBeans are
used by JSP pages to get data from the database, if response requires
accessing the database.

5.3.4 Life Cycle of JSP

JSP pages follow these stages:


• Translation to servlet code

• Compiling to byte code

• Loading the servlet class

• Creating the servlet instance

• Calling jspInit method

• Calling _jspService method

• Calling jspDestroy method

5.3.4.1 Translation: In the initial step, the JSP file is converted the
web container converts the into a Java source file containing servlet
class definition by the web container. The JSP pages and tag files are
validated by the web container.

5.3.4.2 Compilation: The servlet source code is compiled into a Java


class file by the web container in this step.

5.3.4.3 JSP Page Class Loading: The servlet class byte code is stacked
into the web container’s JVM software using class loader in this step.

5.3.4.4 JSP Page Servlet Instance: An instance of the servlet class is


created by the web container in this step.

5.3.4.5 JSP Page Initialization: The servlet is initialized by calling the


jspInit() method by the web container. As the method is created, it is
called immediately. It is called only once during JSP life cycle.To
perform initialization we need to override jspInit () method:

public void jspInit ()


{
//write your code
}

5.3.4.6 JSP Page Service: The requests are now serviced by the
initialized servlet. The user request is processed by calling _jspService
() method by the web container. This method is called for each
request during its life cycle. The method takes HttpServletRequest
and HttpServletResponse parameters.

5.3.4.7 JSP Page Destroyed: The JSP servlet instance is being


expelled (removed) from the web containers service by calling the
jspDestroy () method which permit JSP page to clean the resources.
This ends the JSP life cycle. This method can be written as follows:

public void jspDestroy()


{
//write your code
}

5.3.5 JSP Syntax


This section enlightens us about basic syntax in Java Server Page and
define them in brief such as Scriptlet, Declarative, Expression and
Comments.

Syntax Name Code


Scriptlet Tag <% java code for
statement %>
Declarative tag <%! Statements
%>
Expression tag <% = Statements
%>
Comment tag <%-----
comments provided------ %>
5.3.5.1 The Scriptlet Tag
This tag is used to embed Java code in JSP. The
syntax is as follows:

<% java code %>

Example using scriptlet


tag Example:

<% float j=5.0; %>

5.3.5.2 The Declarative Tag


This tag is used for including members either attributes or methods
in to the JSP servlet class. The syntax is as follows:
<! Statement for loop %>

Example using declarative


tag Example:

<! int increment=0; %>

5.3.5.3 The Expression Tag


The Java language expression is written in this tag for evaluation
during HTTP request and is then included in HTTP response stream.
The syntax is as follows:

<%= expression %>

Example using expression


tag Example:

The time and date of the day is: <%= new java.util.Date () %>
5.3.5.4 The Comment Tag
This tag is used to ignore or hide some parts of the code. The syntax
is as follows:
<% - -comment -- %>

Example using comment


tag Example:

<%-- JSP comment is like this -- %>

Example to demonstrate use of above mentioned


scripting languages Example:

<%! int fontSize=5;%><br>


<html>
<head>
<title>our example</title>
</head>
<body>
<%-- program to add --%><br>
<%
int x =
9 ;<br> int y
= 1; <br>
int output = x+y; %><br>
<font color="blue" size="<%= fontSize %>"><br>
<% out.print(" Total=" +output); %><br>
</font><br>
</body>
</html>

Output:

Total=10

5.4 JSP Scripting


For JSP Scripting element <% %> tags are used to write the code.
During translation of the JSP page, the code inside <% %> tags are
processed by the JSP engine. Any other text in the JSP page is
considered as HTML code or plain text. Just for experiment, try
removing the <% %> scriplet tag from the above code and run it as
JSP. We will see that everything is printed as it is on the browser,
because without the scriplet tag, everything is considered plain
HTML code.

5.4.1 JSP Scripting Elements


In this Book we will figure out the use of JSP Expressions. JSP uses
three types of scripting elements:
• JSP Expressions: The linguistic structure is “<%= some java code
%>”. Small java code can incorporate into a JSP page using this
tag.
• JSP Scriptlet: Multiple lines of Java code can be inserted using
this tag. The syntax for scriptlet is “<% some java code %>”.
• JSP Declaration: This tag is used for declaring variable or
method. The syntax for declaration is “<%! Variable or method
declaration %>”, in here we let’s have a look at these in detail.

5.4.1.1 JSP Expressions


This element is used compute a single line small expression and the
HTML containing the result is returned to the browser.
Example:

The time on the server is <%= new java.util.Date () %>

Output:

The time on the server is Friday March 23 05:24:33 GMT 2018.

Explanation
The “new java.util.Date ()” has processed the actual date and time of
the HTML on the browser. Few other examples:
Examples
• This example shows expression for converting lower case string
to upper case. Here is the code:
The Expression: Following expression is used for converting a string
to uppercase.
<%= new String(“Hello World”).to Uppercase () %>. A “string” object
with value “Hello World” is created. After that, a Java function
“.toUpperCase” is called to convert the string to upper case.
The HTML: Converting a string to uppercase: HELLO WORLD
• Mathematical expressions can also be used in JSP.

The Expression: 40 multiplied to 5: <%= 40*5 %>. We can easily


compute and get answers to mathematical problems using simple
mathematical expressions embedded in our HTML.
The HTML: 40 multiplied to 5: 200.
• Boolean expressions can also be used in JSP.

The Expression: Is 79 less than 65? <%= 79 <65 %>. The return type is
always string either going to be “true” or “false” of these Boolean
expressions.
The HTML: Is 79 less than 65? False

5.4.1.2 JSP Scriptlets


A lot of Java code can be embedded in your HTML code by using this
JSP Scripting Element. While the web server processing the page, the
Java code is processed from top to bottom. The syntax is very similar
as we don’t have to put in an equal sign after the opening % sign.
Here, we have to use “out.println()” to show what we want to mix
with HTML rather than directly combining the result of the code with
the HTML rather. Here is an example:
Example:

<h2> Hello World</h2>


<%
for ( int I =0; I <= 5; i++)
{ out.println(“<br/> I love
counting: ” + i);
}
%>

Output:

I love counting: 1
I love counting: 2
I love counting: 3
I love counting: 4
I love counting: 5

Explanation
In the above example, a basic h2 heading has been set up. Then, we
have a “for loop” in the scriptlet. Don’t put in a lot of code in a
scriptlet in JSP. It will be easily manageable and readable. Try
refactoring this code into different Java classes and make use of MVC
to keep it under control if we can’t find any other option.
In each iteration of the loop we are printing the “I really love
counting” and appending it with the integer value of the “i” printed
through the HTML.

5.4.1.3 JSP Declarations


Using the JSP declaration we are declaring the method in the
beginning of the code and then calling the same method whenever
we need in the same page. This declaration come in handy when we
have a code snippet that we want to be executed more than once.
The syntax is simple:

Code:

<%!
String makeItLower(String data)
{
returndata.toLowerCase();
}
%>

Example:

Lower case “My Program” :< %=


makeItLower (“My Program”) %>

Output:

Lower case “My Program” :< %=


makeItLower (“My Program”) %>

Explanation
In the method declaration we are having our standard java method
with the return type of a String. We take a string as an argument and
return it converted to a lower case. Later we call this function
through a JSP Expression.

5.5 Standard Action

In this topic, we are discussing Actions in JSP. We can dynamically


insert any file, reusing JavaBeans components, generating HTML for
the Java plugin or forward the user to another page. There is just a
single syntax for, as it fits in to the XML to the elements Action.
<jsp:action_name attribute = "value of the attribute" />

The accompanying lists out the table accessible to JSP actions:


Syntax Purpose
jsp:include file is Included or a record is made
at the time the page is asked
jsp:forward Forwards the request into a new
page
jsp:setProperty It sets the property of a JavaBean
and includes it
jsp:getProperty The property of a JavaBean is
inserted into our output
jsp:useBean This Finds a JavaBean or
instantiates it
jsp:body This dynamically Defines element's
body which is in XML
jsp:element It is defining dynamically XML
elements
jsp:attribute This Defines element's attribute
which is dynamically-defined in
XML
jsp:text It reports and is used for
composing template and text in JSP
pages
jsp:plugin It Generates makes an EMBED or
OBJECT tag code particular to
browser than for the Java module
Table 5.1: JSP Actions
5.5.1 Common Attributes
For the most part that are common, basically to all components of
Action are: the scope attribute and the id characteristic.
5.5.1.1 Id attribute
If an instance of the Action is created of an object, through the
implicit object, it can be referenced through its id value can be used
to it through certain PageContext. The id attribute is uniquely
recognizing the Action element, and enables the action to be
referenced inside the JSP page.

5.5.1.2 Scope attribute


The scope attribute is distinguishing that the characterized Action
lifecycle of an element or component. As the scope attribute decides
the object lifespan which is associated with the id value, the id
property and the scope attribute are straightforwardly relating to
each other. This attribute consists of four possible values identified
to it: (a) session, (b) request, (c) page (d) application.

5.5.2 The <jsp:include> Action


The above include action allows us to embed into the page the files
being that have been created (generated). The syntax is depictes as
follows:

<jsp:include page = "relative URL" flush = "true" />

This activity embeds a file at the time requested by the page.


Different from the include directive, at the time the JSP page is
translated (converted) it inserts the file into a servlet. Next follows a
table that lists out the properties associated with the incorporate
action:

Attribute Description
Flush Whether or not the included asset
has its buffer removed is decided
by the boolean attribute before it is
included.
Page The predefined page which is to be
incorporated its relative URL is
found.
Table 5.2: Properties Associated with
<include> Action Example:
Give us a chance to characterize the two records main.jsp and
date.jsp which are as shown below. Following is the substance of the
record for date.jsp:

<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>

Following is the substance of the main.jsp:

<html>
<head>
<title>Example of include action</title>
</head>
<body>
<center>
<h3> Example of “include action” </h3>
<jsp:include page = "date.jsp" flush = "true" />
</center>
</body>
</html>

Output:

Example of “include action”

Today's date: 12-Sep-2010 14:54:22

5.5.3 The <jsp:useBean> Action


The useBean action normally searches for an object that is existing, it
uses the id and scope variables. This action is quite versatile. It tries
to create a particular object, when an object is not found.
The least difficult syntax for a bean to be able to load it is:

<jsp:useBean id = "name" class = "package.class" />

Once any bean class to be loaded into the page has been loaded, we
can jsp: getProperty and use jsp: setProperty actions for retrieving
and modifying the properties of the bean. The table below lists the
attributes of useBean action

Attribute Description

Type Type of the variable is Specified


which will be included to refer to
an object.
Class Full package name is assigned to
the bean.
bean Name The name of the bean as indicated
by the instantiate () method of the
java.beans.Beans class is shown.
Table 5.2 attributes of useBean Action
Give us now a chance to talk about the jsp:setProperty and the
jsp:getProperty actions before giving a valid example related to these
actions.
5.5.3.1 The <jsp: setProperty> Action
The Bean ought to have been defined beforehand using this action.
This action sets the Bean properties. There are ways to utilize the
setProperty action mainely two of them are given below: The
jsp:setProperty can be used after but outside of an element which is
jsp:useBean , as given below:
<jsp:useBean id = "Name" ... />
...
<jsp:setProperty name = "Name" property = "Property" .../>

Context for which jsp:setProperty appears is inside jsp:useBean


body. The jsp:setProperty is executed regardless of whether we are
executing a new bean or an existing bean is found as shown below:

<jsp:useBean id = "Name" ... >


...
<jsp:setProperty name = "Name" property =
"Property" .../> </jsp:useBean>
In the case the jsp:setProperty is not executed if an existing
one was found. It is executed only if a new object is
instantiated.
5.5.3.2 The <jsp:getProperty> Action
The getProperty action is utilized in recovering the value of a given
property is changed to string, which is embedded into its output. The
getProperty action comprises of two characteristics, the properties
are required. The getProperty action syntax is as per the following:

<jsp:useBean id = "Name" ... />


...
<jsp:getProperty name = "Name" property = "Property" .../>

Example
On testing the bean class:
/* File:
TestBean.java */
package action;
public class
TestBean {
private String message = "No message
specified"; public String getMessage() {
return(msg);
}
public void setMessage(String msg) {
this.message = msg;
}
}

On Compiling code to generate TestBean.class file which ensure that


we copied into C:\apachetomcat-7.0.2\webapps\WEB-INF\classes\
action path the TestBean.class and the CLASSPATH variable this
folder is ought to be set .This code is used in main.jsp file. This
sets/gets the bean and loads it in a straightforward String parameter:
Output:

Using JavaBeans in JSP


Got Text….
Hi JSP.....

5.5.4 The <jsp: forward> Action


This action is used to terminate the current page action and the
request is forwarded to another resource such as static page, Java
Servlet, JSP page. Following is the syntax for the forward action:

<jsp:forward page = "Relative URL" />

Example:
On reusing the files date.jsp and main.jsp.The content of the date.jsp
file is:

<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>

The main.jsp file content:


<html>
<head>
<title> This is index page </title>
</head>
<body>
<center>
<h2> This is index page </h2>
<jsp: forward page = "date.jsp" />
</center>
</body>
</html>

By keeping every one of the document in the directory which is the


root and trying to access main.jsp. The result will be as depicted
underneath. Here the content of it is discarded from the main page
and show content from page requested only.
Output:

Today's date: 15-Sep-2015 15:55:22

5.5.5 The <jsp:plugin> Action


This action is utilized typically in inserting some components of Java
into page. It decides the browser type and helps in inserting the
<object> or <embed> needed tags. On the off chance that the
required plugin is not there, then it is downloaded and then Java
components are executed.
The plugin action contains of attributes that correspond to common
HTML tags used to format Java components. The Java component
can be likewise an Applet or a JavaBean. The parameters for Applet
or Bean is sent by using the <param>. The syntax of plugin action
usage:

Example:
<jsp:plugin type = "applet" codebase = "dir" code =
"Applet.class" width = "80" height = "100">
<jsp:param name = "fontcolor" value = "blue" />
<jsp:param name = "background" value = "red" />
<jsp:fallback>
Unable to initialize the Java Plugin
</jsp:fallback>
</jsp:plugin>

We try using some applet for this action. A new <fallback> element,
to specify a message can be used error string to be sent to the user
in case the component fails.
Output:

The <jsp:element> Action


The <jsp:attribute> Action
The <jsp:body> Action

5.6 Page Directive

We can code the page directives at anyplace in our JSP page. The
guidelines to the container relating to JSP current page is provided by
the page directive. The directives of page are coded at top of the JSP
page by convention. The basic syntax of page directive is as follows:

<%@ page attribute = "value attr" %>

The XML code equivalent to the above syntax is as follows:

<jsp:directive.page attribute = "value attr" />

The attributes associated with the page directive are listed below:
Attribute Purpose
Buffer A buffering model is specified for
the output stream.
autoFlush Servlet output buffer behavior is
controlled by this.
contentType It characterizes the character
encoding scheme.
errorPage This characterizes the URL of
another JSP that reports on Java
unchecked runtime exceptions
(special cases).
isErrorPage It shows if this JSP page is a URL
indicated by another JSP page's
errorPage characteristic.
Extends Determines a superclass that the
produced servlet must extend.
Import Indicates a bundle of packages or
classes for use in the JSP as the
Java import statement does for
Java classes.
Info Characterizes a string that can be
accessed with the servlet's
getServletInfo() method.
isThreadSafe Characterizes the threading model
for the generated servlet.
Language Characterizes the programming
language used in the JSP page.
Session Specifies whether or not the JSP
page participates in HTTP sessions.
isELIgnored Characterizes whether or not the
EL expression within the JSP page
will be ignored.
isScriptingEnabled Characterizes if the scripting
elements are allowed for use.
Table 5.4 Attributes of Page Directive
Some of the above attributes are being explained below:

5.6.1 The buffer Attribute


The buffer attribute is used to specify the buffering characteristics for
the server output response object. It directs the servlet to write to
the buffer before writing to the response object. We may code an
estimation of "none" to indicate no buffering so that the servlet
output is promptly directed to the response object or you may code
a maximum buffer size in kilobytes. To coordinate the servlet to write
the output directly to the response output object, use the following:

<%@ page buffer = "none" %>

Use the accompanying to direct the servlet to compose (write) the


output to a buffer of size not less than 8 kilobytes

<%@ page buffer = "16kb" %>

5.6.2 The autoFlush Attribute


This attribute is used to flush automatically or to generate an
exception message when the buffer is full. The autoFlush
characteristic i.e. attribute specifies whether or not the buffered
output should be flushed automatically. The true value (default)
indicates automatic buffer flushing and a value of false throws an
exception. The accompanying directive is responsible for throwing an
exception when the servlet's output buffer is full:

<%@ page autoFlush = "false" %>


This directive directly flush the output buffer when full:

<%@ page autoFlush = "true" %>

Generally, the autoFlush attributes and the buffer are coded on a


single page directive as follows:

<%@ page buffer = "16kb" autoflush = "true" %>

5.6.3 The contentType Attribute


The default content type is text/html, which is the standard content
type of HTML pages. The contentType attribute is used to set the
character encoding for a JSP page and for the generated response
page.
If we want to write out XML from our JSP, we can do using following
directive:

<%@ page contentType = "text/xml" %>

The accompanying statement directs the browser to render the


generated page as HTML:

<%@ page contentType = "text/html" %>

The accompanying directive sets the content type as a Microsoft


Word document

<%@ page contentType = "application/msword" %>

5.6.4 The errorPage Attribute


The errorPage attribute is used for telling the JSP engine to run a
page if there is an error while the current page running. The
corresponding URL serve as the value of the errorPage attribute.
When all uncaught special cases are caught, then the directive
displays MyErrorPage.jsp as foolow:
<%@ page errorPage = "MyErrorPage.jsp" %>

5.6.5 The isErrorPage Attribute


The default value of the isErrorPage attribute is false. The isErrorPage
characteristic indicates that the current JSP can be utilized as the
error page for another JSP. The value of isErrorPage is either true or
false. For instance, the handleError.jsp sets the isErrorPage option to
true because it should deal with errors:

<%@ page isErrorPage = "true" %>

5.6.6 The extends Attribute


The extends attribute is determining a superclass that a produce a
servlet must extend. For instance, the following directive directs the
JSP translator, to create the servlet such that the servlet extends
somePackage.SomeClass:

<%@ page extends = "somePackage.SomeClass" %>

5.6.7 The import Attribute


The import attribute is serving an indistinguishable function as, and
carries on like, the Java import explanation. The value for the import
alternative is the name of the package we are importing .To import
java.sql.*, use the following page directive:

<%@ page import = "java.sql.*" %>

For importing multiple packages, we can specify them separated by


comma as follows:

<%@ page import = "java.sql.*,java.util.*" %>


The info Attribute
The info attribute lets you provide a description of the JSP. The
following is a coding example:

<%@ page info = "This JSP Page Written by ZARA” %>

The language Attribute


The language attribute specifies the programming language used in
scripting the JSP page. For instance, since we usually use Java as the
scripting language, our language option looks like this:

<%@ page language = "java" %>

Include Directive

A file is included during the translation phase by using include


directive. The content of the other external files is merged with the
current JSP by the container upon instruction from the directive. The
Include Directive can be anywhere in your JSP page. The syntax of
the directive is as follows:

<%@ include file = "relative url" >

The filename in the include directive is a relative URL. If only a


filename with no associated path is specified, the JSP compiler
searches that file in the same directory as your JSP. The XML code
equivalent of the above syntax is as follows:
<jsp:directive.include file = "relative url" />

Example
Including a typical header and footer with multiple pages of content
is a good example of include directive. Following three files have
been defined below: (a)header.jps,(b)footer.jsp, and (c)main.jsp.
header.jsp content is as follows:
<%!
int pageCount =
0; void
addCount() {
pageCount++;
}
%>
<% addCount(); %>
<html>
<head>
<title>An example of Include Directive </title>
</head>
<body>
<center>
<h2> An example of Include Directive </h2>
<p>You have visited this site <%= pageCount %>
times.</p> </center>
<br/><br/>

footer.jsp content is as follows:

<br/><br/>
<center>
<p>Copyright © 2015</p>
</center>
</body>
</html>
main.jsp content is
as follows:
<%@ include file = "header.jsp" %>
<center>
<p>Thank you for visiting this page.</p>
</center>
<%@ include file = "footer.jsp" %>

Output:

An example of Include
Directive You have visited
this site 1 times.
Thank you for visiting this page

By refresh main.jsp and the page hit counter keeps increasing.


Webpages can be designed based on your creative instincts; it is
recommended to keep the dynamic parts of the website in separate
files and then merging them in the main file. This is convenient for
whenever a part of the webpage need to be changed.

You might also like