Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

ADVANCED JAVA

JSP

JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet such
as expression language, JSTL, etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than
Servlet because we can separate designing and development. It provides some additional
features such as Expression Language, Custom Tags, etc.

Advantages of JSP over Servlet

There are many advantages of JSP over the Servlet. They are as follows:

1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the features of the
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.

2) 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.

3) 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.

4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the
code. Moreover, we can use EL, implicit objects, etc.

The Lifecycle of a JSP Page

The JSP pages follow these phases:

o Translation of JSP Page

o Compilation of JSP Page

o Classloading (the classloader loads class file)

1
ADVANCED JAVA
o Instantiation (Object of the Generated Servlet is created).

o Initialization ( the container invokes jspInit() method).

o Request processing ( the container invokes _jspService() method).

o Destroy ( the container invokes jspDestroy() method).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP
translator. The JSP translator is a part of the web server which is responsible for translating
the JSP page into Servlet. After that, Servlet page is compiled by the compiler and gets
converted into the class file. Moreover, all the processes that happen in Servlet are performed
on JSP later like initialization, committing response to the browser and destroy.

Creating a simple JSP Page

To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the
web-apps directory in apache tomcat to run the JSP page.

2
ADVANCED JAVA
index.jsp

Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in
the JSP page. We will learn scriptlet tag later.

1. <html>

2. <body>

3. <% out.print(2*5); %>

4. </body>

5. </html>

It will print 10 on the browser.

How to run a simple JSP Page?

Follow the following steps to execute this JSP page:

o Start the server

o Put the JSP file in a folder and deploy on the server

o Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example,


http://localhost:8888/myapplication/index.jsp

Do I need to follow the directory structure to run a simple JSP?

No, there is no need of directory structure if you don't have class files or TLD files. For
example, put JSP files in a folder directly and deploy that folder. It will be running fine.
However, if you are using Bean class, Servlet or TLD file, the directory structure is required.

The Directory structure of JSP

The directory structure of JSP page is same as Servlet. We contain the JSP page outside the
WEB-INF folder or in any directory.

3
ADVANCED JAVA

The JSP API

The JSP API consists of two packages:

1. javax.servlet.jsp

2. javax.servlet.jsp.tagext

javax.servlet.jsp package

Package javax.servlet.jsp
Classes and interfaces for the Core JSP 2.3 API.

Interface Summary
Interface Description
HttpJspPage The HttpJspPage interface describes the interaction that a JSP Page
Implementation Class must satisfy when using the HTTP protocol.
JspApplicationContext Stores application-scoped information relevant to JSP containers.
JspPage The JspPage interface describes the generic interaction that a JSP Page
Implementation class must satisfy; pages that use the HTTP protocol
are described by the HttpJspPage interface.

4
ADVANCED JAVA
Class Summary

Class Description

ErrorData Contains information about an error, for error pages.

JspContext JspContext serves as the base class for the PageContext class and abstracts all
information that is not specific to servlets.

JspEngineInfo The JspEngineInfo is an abstract class that provides information on the current
JSP engine.
JspFactory The JspFactory is an abstract class that defines a number of factory methods
available to a JSP page at runtime for the purposes of creating instances of various
interfaces and classes used to support the JSP implementation.

JspWriter The actions and template data in a JSP page is written using the JspWriter object
that is referenced by the implicit variable out which is initialized automatically
using methods in the PageContext object.
PageContext PageContext extends JspContext to provide useful context information for when
JSP technology is used in a Servlet environment.

Exception Summary
Exception Description
JspException A generic exception known to the JSP engine; uncaught JspExceptions
will result in an invocation of the errorpage machinery.
JspTagException Exception to be used by a Tag Handler to indicate some unrecoverable
error.
SkipPageException Exception to indicate the calling page must cease evaluation.

Package javax.servlet.jsp Description


Classes and interfaces for the Core JSP 2.3 API.

The javax.servlet.jsp package contains a number of classes and interfaces that describe and define
the contracts between a JSP page implementation class and the runtime environment provided
for an instance of such a class by a conforming JSP container.

The JspPage interface

According to the JSP specification, all the generated servlet classes must implement the
JspPage interface. It extends the Servlet interface. It provides two life cycle methods.

5
ADVANCED JAVA

Methods of JspPage interface

1. public void jspInit(): It is invoked only once during the life cycle of the JSP when
JSP page is requested firstly. It is used to perform initialization. It is same as the init()
method of Servlet interface.

2. public void jspDestroy(): It is invoked only once during the life cycle of the JSP
before the JSP page is destroyed. It can be used to perform some clean up operation.

The HttpJspPage interface

The HttpJspPage interface provides the one life cycle method of JSP. It extends the JspPage
interface.

Method of HttpJspPage interface:

1. public void _jspService(): It is invoked each time when request for the JSP page
comes to the container. It is used to process the request. The underscore _ signifies
that you cannot override this method.

6
ADVANCED JAVA
Package javax.servlet.jsp.tagext
Classes and interfaces for the definition of JavaServer Pages Tag Libraries.

See:
Description

Interface Summary
The BodyTag interface extends IterationTag by defining
BodyTag additional methods that let a tag handler manipulate the
content of evaluating its body.
For a tag to declare that it accepts dynamic attributes, it must
DynamicAttributes
implement this interface.
The IterationTag interface extends Tag by defining one
IterationTag
additional method that controls the reevaluation of its body.
This interface indicates to the container that a tag handler
JspIdConsumer
wishes to be provided with a compiler generated ID.
JspTag Serves as a base class for Tag and SimpleTag.
SimpleTag Interface for defining Simple Tag Handlers.
The interface of a classic tag handler that does not want to
Tag
manipulate its body.
The auxiliary interface of a Tag, IterationTag or BodyTag tag
TryCatchFinally
handler that wants additional hooks for managing resources.

Class Summary
An encapsulation of the evaluation of the body of an action
BodyContent
so it is available to a tag handler.
A base class for defining tag handlers implementing
BodyTagSupport
BodyTag.
FunctionInfo Information for a function in a Tag Library.
Encapsulates a portion of JSP code in an object that can be
JspFragment
invoked as many times as needed.
PageData Translation-time information on a JSP page.
A base class for defining tag handlers implementing
SimpleTagSupport
SimpleTag.
TagAdapter Wraps any SimpleTag and exposes it using a Tag interface.
TagAttributeInfo Information on the attributes of a Tag, available at

7
ADVANCED JAVA
translation time.
The (translation-time only) attribute/value information for
TagData
a tag instance.
Optional class provided by the tag library author to
TagExtraInfo describe additional translation-time information not
described in the TLD.
Tag information for a tag file in a Tag Library; This class
TagFileInfo is instantiated from the Tag Library Descriptor file (TLD)
and is available only at translation time.
Tag information for a tag in a Tag Library; This class is
TagInfo instantiated from the Tag Library Descriptor file (TLD)
and is available only at translation time.
Translation-time information associated with a taglib
TagLibraryInfo
directive, and its underlying TLD file.
TagLibraryValidator Translation-time validator class for a JSP page.
A base class for defining new tag handlers implementing
TagSupport
Tag.
Variable information for a tag in a Tag Library; This class
TagVariableInfo is instantiated from the Tag Library Descriptor file (TLD)
and is available only at translation time.
A validation message from either TagLibraryValidator or
ValidationMessage
TagExtraInfo.
Information on the scripting variables that are
VariableInfo
created/modified by a tag (at run-time).

Package javax.servlet.jsp.tagext Description


Classes and interfaces for the definition of JavaServer Pages Tag Libraries.

Custom actions can be used by JSP authors and authoring tools to simplify writing
JSP pages. A custom action can be either an empty or a non-empty action.

An empty tag has no body. There are two equivalent syntaxes, one with separate
start and end tags, and one where the start and end tags are combined. The two
following examples are identical:
<x:foo att="myObject"></foo>
<x:foo att="myObject"/>

8
ADVANCED JAVA
A non-empty tag has a start tag, a body, and an end tag. A prototypical example is
of the form:
<x:foo att="myObject" >
BODY
</x:foo/>

The JavaServer Pages(tm) (JSP) specification provides a portable mechanism for


the description of tag libraries.

A JSP tag library contains

 A Tag Library Descriptor


 A number of Tag Files or Tag handler classes defining request-time
behavior
 Additional classes and resources used at runtime
 Possibly some additional classes to provide extra translation information

JSP Scripting Element

Java provides various scripting elements that allow you to insert Java code from your
JSP code into the servlet. Scripting elements have different components that are
allowed by JSP. Understanding each of these components is essential to writing code
in JSP. Let us discuss each of the components in detail.

Scripting Element in JSP

Scripting elements in JSP must be written within the <% %> tags. The JSP engine will
process any code you write within the pair of the <% and %> tags, and any other
texts within the JSP page will be treated as HTML code or plain text while translating
the JSP page.

Example:

<!DOCTYPE html>
<html>
<head>
<title>w3schools JSP Tutorial</title>
</head>
<% int cnt = 6; %>
<body>
Calculated page count is <% out.println(cnt); %>
</body>

9
ADVANCED JAVA
</html>
Here are five different scripting elements:

 Comment <%-- Set of comment statements --%>


 Directive <%@ directive %>
 Declaration <%! declarations %>
 Scriptlet <% scriplets %>
 Expression <%= expression %>

Comment

Comments are marked as text or statements that are ignored by the JSP container.
They are useful when you want to write some useful information or logic to
remember in the future.

Example:

<%@ page import="java.util.Date"%>


<!DOCTYPE html>
<html>
<head>
<title>Comments in JSP Page</title>
</head>
<body>
<%-- A JSP comment --%>
<!-- An HTML comment -->
<!—The current date is <%= new Date() %>
-->
</body>
</html>

Directives

These tags are used to provide specific instructions to the web container when the
page is translated. It has three subcategories:

 Page: <%@ page ... %>


 Include: <%@ include ... %>
 Taglib: <%@ taglib ... %>

We will discuss these in detail in the coming chapter.

Declaration

10
ADVANCED JAVA
As the name suggests, it is used to declare methods and variables you will use in
your Java code within a JSP file. According to the rules of JSP, any variable must be
declared before it can be used.

Syntax:

<%! declaration; [ declaration; ]+ ... %>


Example:

<!DOCTYPE html>
<html>
<body>
<%! int variable_value=62; %>
<%= " Your integer data is :"+ variable_value %>
</body>
</html>

JSP Scriptlet Tag

The scriptlet tag allows writing Java code statements within the JSP page. This tag is
responsible for implementing the functionality of _jspService() by scripting the java
code.

Syntax:

<% JAVA CODE %>


Example:

<!DOCTYPE html>
<html>
<head>
<title>Scriptlet Tag</title>
</head>
<% int count = 2; %>
<body>
Calculated page count <% out.println(cnt); %>
</body>
</html>
Another code snippet that shows how to write and mix scriptlet tags with HTML:

Example:

<table border="1">
<% for ( int g = 1; g <= cnt; g++ ) { %>
<tr>
<td>Number</td>
<td><% = g+1 %></td>
</tr>

11
ADVANCED JAVA
<% } %>
</table>

Expressions

Expressions elements are responsible for containing scripting language expression,


which gets evaluated and converted to Strings by the JSP engine and is meant to the
output stream of the response. Hence, you are not required to write out.print() for
writing your data. This is mostly used for printing the values of variables or methods
in the form of output.

Example:

<!DOCTYPE html>
<html>
<body>
<%= "A JSP based string" %>
</body>
</html>

JSP - Implicit Objects


Objects are the Java objects that the JSP Container makes available to the
developers in each page and the developer can call them directly without being
explicitly declared. JSP Implicit Objects are also called pre-defined variables.
Following table lists out the nine Implicit Objects that JSP supports −

S.No. Object & Description

request
1 This is the HttpServletRequest object associated with
the request.

response
2 This is the HttpServletResponse object associated with
the response to the client.

out
3
This is the PrintWriter object used to send output to the

12
ADVANCED JAVA
client.

session
4 This is the HttpSession object associated with the
request.

application
5 This is the ServletContext object associated with the
application context.

config
6 This is the ServletConfig object associated with the
page.

pageContext
7 This encapsulates use of server-specific features like
higher performance JspWriters.

page
8 This is simply a synonym for this, and is used to call the
methods defined by the translated servlet class.

Exception
9 The Exception object allows the exception data to be
accessed by designated JSP.

The request Object


The request object is an instance of
a javax.servlet.http.HttpServletRequest object. Each time a client requests a page
the JSP engine creates a new object to represent that request.
The request object provides methods to get the HTTP header information including
form data, cookies, HTTP methods etc.
We can cover a complete set of methods associated with the request object in a
subsequent chapter − JSP - Client Request.

The response Object

13
ADVANCED JAVA
The response object is an instance of
a javax.servlet.http.HttpServletResponse object. Just as the server creates the
request object, it also creates an object to represent the response to the client.
The response object also defines the interfaces that deal with creating new HTTP
headers. Through this object the JSP programmer can add new cookies or date
stamps, HTTP status codes, etc.
We will cover a complete set of methods associated with the response object in a
subsequent chapter − JSP - Server Response.

The out Object


The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is
used to send content in a response.
The initial JspWriter object is instantiated differently depending on whether the page
is buffered or not. Buffering can be easily turned off by using the buffered =
'false' attribute of the page directive.
The JspWriter object contains most of the same methods as
the java.io.PrintWriter class. However, JspWriter has some additional methods
designed to deal with buffering. Unlike the PrintWriter object, JspWriter
throws IOExceptions.
Following table lists out the important methods that we will use to write boolean
char, int, double, object, String, etc.

S.No. Method & Description

out.print(dataType dt)
1
Print a data type value

out.println(dataType dt)
2 Print a data type value then terminate the line with new
line character.

out.flush()
3
Flush the stream.

The session Object


The session object is an instance of javax.servlet.http.HttpSession and behaves
exactly the same way that session objects behave under Java Servlets.

14
ADVANCED JAVA
The session object is used to track client session between client requests. We will
cover the complete usage of session object in a subsequent chapter − JSP - Session
Tracking.

The application Object


The application object is direct wrapper around the ServletContext object for the
generated Servlet and in reality an instance of
a javax.servlet.ServletContext object.
This object is a representation of the JSP page through its entire lifecycle. This
object is created when the JSP page is initialized and will be removed when the JSP
page is removed by the jspDestroy() method.
By adding an attribute to application, you can ensure that all JSP files that make up
your web application have access to it.
We will check the use of Application Object in JSP - Hits Counter chapter.

The config Object


The config object is an instantiation of javax.servlet.ServletConfig and is a direct
wrapper around the ServletConfig object for the generated servlet.
This object allows the JSP programmer access to the Servlet or JSP engine
initialization parameters such as the paths or file locations etc.
The following config method is the only one you might ever use, and its usage is
trivial −
config.getServletName();
This returns the servlet name, which is the string contained in the <servlet-
name> element defined in the WEB-INF\web.xml file.

The pageContext Object


The pageContext object is an instance of a javax.servlet.jsp.PageContext object.
The pageContext object is used to represent the entire JSP page.
This object is intended as a means to access information about the page while
avoiding most of the implementation details.
This object stores references to the request and response objects for each request.
The application, config, session, and out objects are derived by accessing
attributes of this object.
The pageContext object also contains information about the directives issued to the
JSP page, including the buffering information, the errorPageURL, and page scope.
The PageContext class defines several fields, including PAGE_SCOPE,
REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which
identify the four scopes. It also supports more than 40 methods, about half of which
are inherited from the javax.servlet.jsp.JspContext class.

15
ADVANCED JAVA
One of the important methods is removeAttribute. This method accepts either one
or two arguments. For example, pageContext.removeAttribute
("attrName") removes the attribute from all scopes, while the following code only
removes it from the page scope −
pageContext.removeAttribute("attrName", PAGE_SCOPE);
The use of pageContext can be checked in JSP - File Uploading chapter.

The page Object


This object is an actual reference to the instance of the page. It can be thought of as
an object that represents the entire JSP page.
The page object is really a direct synonym for the this object.

The exception Object


The exception object is a wrapper containing the exception thrown from the previous
page. It is typically used to generate an appropriate response to the error condition.
We will cover the complete usage of this object in JSP - Exception Handling chapter.

Directives

Directives supply directions and messages to a JSP container. The directives provide global
information about the entire page of JSP. Hence, they are an essential part of the JSP code.
These special instructions are used for translating JSP to servlet code. In this chapter, you
will learn about the different components of directives in detail.

In JSP's life cycle phase, the code must be converted to a servlet that deals with the
translation phase. They provide commands or directions to the container on how to deal with
and manage certain JSP processing portions. Directives can contain several attributes that are
separated by a comma and act as key-value pairs. In JSP, directives are described with a pair
of <%@ .... %> tags.

The syntax of Directives looks like:

<%@ directive attribute="" %>


There are 3 types of directives:

1. Page directive
2. Include directive
3. Taglib directive
Let us now discuss each of them in detail.

Page Directive

16
ADVANCED JAVA
The page directive is used for defining attributes that can be applied to a complete JSP page.
You may place your code for Page Directives anywhere within your JSP page. However, in
general, page directives are implied at the top of your JSP page.

The basic syntax of the page directive is:

<%@ page attribute = "attribute_value" %>


The XML equivalent for the above derivation is:

<jsp:directive.page attribute = "attribute_value" />


The attributes used by the Page directives are:

1. buffer: Buffer attribute sets the buffer size in KB to control the JSP page's output.
2. contentType: The ContentType attribute defines the document's MIME (Multipurpose
Internet Mail Extension) in the HTTP response header.
3. autoFlush: The autofill attribute controls the behavior of the servlet output buffer. It
monitors the buffer output and specifies whether the filled buffer output should be
flushed automatically or an exception should be raised to indicate buffer overflow.
4. errorPage: Defining the "ErrorPage" attribute is the correct way to handle JSP errors.
If an exception occurs on the current page, it will be redirected to the error page.
5. extends: extends attribute used for specifying a superclass that tells whether the
generated servlet has to extend or not.
6. import: The import attribute is used to specify a list of packages or classes used in JSP
code, just as Java's import statement does in a Java code.
7. isErrorPage: This "isErrorPage" attribute of the Page directive is used to specify that
the current page can be displayed as an error page.
8. info: This "info" attribute sets the JSP page information, which is later obtained using
the getServletInfo() method of the servlet interface.
9. isThreadSafe: Both the servlet and JSP are multithreaded. If you want to control JSP
page behavior and define the threading model, you can use the "isThreadSafe"
attribute of the page directive.
10. Language: The language attribute specifies the programming language used in the JSP
page. The default value of the language attribute is "Java".
11. Session: In JSP, the page directive session attribute specifies whether the current JSP
page participates in the current HTTP session.
12. isELIgnored: This isELIgnored attribute is used to specify whether the expression
language (EL) implied by the JSP page will be ignored.
13. isScriptingEnabled: This "isScriptingEnabled" attribute determines if the scripting
elements are allowed for use or not.

Include Directive

The JSP "include directive" is used to include one file in another JSP file. This includes
HTML, JSP, text, and other files. This directive is also used to create templates according to
the developer's requirement and breaks the pages in the header, footer, and sidebar.

To use this Include Directive, you have to write it like:

<%@ include file = "relative url" >


The XML equivalent of the above way of representation is:

17
ADVANCED JAVA
<jsp:directive.include file = "relative url" />
Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding =


"ISO-8859-1"%>
<%@ include file="directive_header_code.jsp" %>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Include Directive Example</title>
</head>
<body>
<p>This file includes a header file named directive_header_code.jsp</p>
</body>
</html>
In the above example of JSP code, a JSP header file is being added to the current JSP file
using "include directive".

Taglib Directive

The JSP taglib directive is implemented to define a tag library with "taglib" as its prefix.
Custom tag sections of JSP use taglib. JSP's taglibdirective is used as standard tag libraries.

To implement taglib, you have to write it like this:

<%@ taglib uri="uri" prefix="value"%>


Example:

<%@ taglib uri = "http://www.example.com/custlib" prefix = "w3tag" %>


<!DOCTYPE html>
<html>
<body>
<mytag: hi/>
</body>
</html>

Exceptions
Exceptions can be defined as an object that is thrown during a program run. Exception
handling is the practice of handling errors at runtime. Exceptions can occur at any time in a
web application. Therefore, the web developer must handle exceptions to be on the safe side
and make the user work flawlessly on the web.

The exception Implicit Object

 An exception implicit object is implemented to handle exceptions to display error


messages.
18
ADVANCED JAVA
 The exception implicit object is an instance of the java.lang.Throwable class.
 It is only available for JSP pages, with the isErrorPage value set as "True". This
means Exception objects can only be used in error pages.

Types of Exceptions in JSP

There are three types of exceptions in JSP; these are:

 Checked Exception
 Runtime Exception
 Errors Exception
Let us now discuss each of them in detail.

Checked Exceptions

"Checked exceptions" are a type of exception that is usually a user fault or a problem that
cannot be foreseen by the programmer. This type of exception is checked at compile-time.
Here is a list of some common "Checked exceptions" that occur in the programming domain:

 IO Exception: This is an example of a checked exception where some exceptions may


occur while reading and writing a file. If the file format is not supported, then the IO
exception will occur.
 FileNotFoundException: This is an example of a checked exception where a file in
which data needs to be written is not found on that particular path on the disk.
 SQLException: This is also an example of a checked exception where the file is
associated with a SQL database. The exception will be if there is a problem or
concern with the connectivity of the SQL database.

Runtime Exceptions

"Runtime exceptions" can be defined as exceptions evaded by the programmer. They are left
unnoticed at compilation time. Here is the list of some of the common examples that occurred
in the programming domain:

 ArrayIndexOutOfBoundsException: This is a runtime exception; This occurs when


the array size goes beyond the elements or index value set.
 NullPointer Exception: This is also an example of a runtime exception raised when a
variable or object is empty or null, and users or programmers try to access it.
 ArithmeticException: This is an example of a runtime exception when a mathematical
operation is not allowed under normal circumstances. A common example of such a
scenario is to divide the number by 0.

Errors

"Error exception" arises solely because of the user or programmer. Here you might encounter
error due to stack overflows. Here is the list of some of the common examples that occurred
in the programming domain:

19
ADVANCED JAVA
 Error: This is a subclass of throwable that indicates serious problems the applications
cannot catch.
 Internal Error: This error occurs when a fault occurs in the Java Virtual Machine
(JVM).
 Instantiation error: This error occurs when you try to instantiate an object, ultimately
failing to do that.

ArithmeticException Example
Example (HTML file):

<!DOCTYPE html>
<html>
<head>
<title>Enter two Integers for Division</title>
</head>
<body>
<form action="submit.jsp">
Insert first Integer: <input type="text" name="numone" /><br />
Insert second Integer: <input type="text" name="numtwo" /><br />
<input type="submit" value="Get Results" />
</form>
</body>
</html>
Example (submit.jsp):

<%@ page errorPage="exception.jsp" %>

<%
String num1 = request.getParameter("numone");
String num2 = request.getParameter("numtwo");
int var1= Integer.parseInt(num1);
int var2= Integer.parseInt(num2);
int r= var1 / var2;
out.print("Output is: "+ r);
%>
Example (exception.jsp):

<%@ page isErrorPage='true' %>

<%
out.print("Error Message : ");
out.print(exception.getMessage());
%>

20
ADVANCED JAVA
Actions Tags

The JSP specification provides a standard tag called Action tag used within JSP code
and is used to remove or eliminate Scriptlet code from your JSP code as JSP
Scriptlets are obsolete and are not considered nowadays. There are many JSP action
tags or elements, and each of them has its own uses and characteristics. Each JSP
action tag is implemented to perform some precise tasks.

The action tag is also implemented to streamline flow between pages and to employ
a Java Bean. As it coincides with the XML standard, the syntax for the action element
is:

Syntax:

<jsp:action_name attribute = "attribute_value" />


Here is the list of JSP Actions:

1. jsp:forward: is used for forwarding the request and response to other


resources.
2. jsp:include: is used for including another resource.
3. jsp:body: is used for defining dynamically-defined body of XML element.
4. jsp:useBean: is used for creating or locating bean objects.
5. jsp:setProperty: is used for setting the value of property in the bean object.
6. jsp:getProperty: is used for printing the value of the property of the bean.
7. jsp:element: is used for defining XML elements dynamically.
8. jsp:plugin: is used for embedding other components (applets).
9. jsp:param: is used for setting the parameter for (forward or include) value.
10. jsp:text: is used for writing template text in JSP pages and documents.
11. jsp:fallback: is used for printing the message if plugins are working.
12. jsp:attribute: is used for defining attributes of dynamically-defined XML
element.

Basic Attributes of Action Tags

Two basic attributes are commonly used for all action tags. These are:

1. id: The id attribute defines unique action elements and allows actions to be
referenced within the JSP page. When the action creates an object's instance,
the id attribute is used to refer to it.
2. Scope: The scope attribute is used for identifying an action's life cycle. It
correlates with the id attribute because the scope attribute is used to establish
that particular object's lifespan associated with the ID.
Here the syntax and implementation of some actions are described below:

21
ADVANCED JAVA
jsp:include Action

This "include action" allows you to include another resource in the page being
generated.

Syntax:

<jsp:include page = "Page URL" flush = "Boolean Value" />


Example:

<!DOCTYPE html>
<html>
<head>
<title>JSP include Action</title>
</head>
<body>
<h2>JSP page: with include</h2>
<jsp:include page="header.jsp" flush="false" />
</body>
</html>

jsp:forward Action

This "forward action" terminates the current page and allows you to forward the
request to other resources.

Syntax:

<jsp:forward page = "URL of another static, JSP, OR Servlet page" />


Example:

<!DOCTYPE html>
<html>
<head>
<title>Example for Forward Action</title>
</head>
<body>
<h2>JSP page: Demo forward</h2>
<jsp:forward page="forward_eg.jsp" />
</body>
</html>
It is to be noted that this JSP file and forward_eg.jsp file should have to reside in the
same directory to make it work.

jsp:param Action

This "param action" is used for setting the parameter for (forward or include) value.

22
ADVANCED JAVA
Syntax:

<jsp: param name = "param_name" value = "value_of_parameter" />


Example:

<!DOCTYPE html>
<html>
<head>
<title>Example of param Action</title>
</head>
<body>
<h2>JSP page: Param with forward</h2>
<jsp:forward page="forward_eg.jsp">
<jsp:param name="date" value="06-09-2019" />
<jsp:param name="time" value="10:30PM" />
<jsp:param name="data" value="GKR" />
</jsp:forward>
</body>
</html>

jsp:useBean Action

This "useBean action": is used for creating or locating bean objects.

Syntax:

<jsp: useBean id="unique_name_to_identify_bean" class="package_name.class_name" />


Example:

<!DOCTYPE html>
<html>
<head>
<title>JSP Page for showing use of useBean action</title>
</head>
<body>
<h2>UseBean Action</h2>
<jsp:useBean id="teacher" class="packageName.Teacher" />
<jsp:setProperty name="teacher" property="*" />
<h2>
name:<jsp:getProperty name="teacher" property="t_name" /> <br />
empno:<jsp:getProperty name="teacher" property="dept" /> <br />
</h2>
</body>
</html>
Example: Java Class:

package samplePackageName;

public class Teacher {

23
ADVANCED JAVA
public Teacher() {}

private String t_name;


private int deptno;

public void setName(String t_name) {


this.t_name = t_name;
}

public String getName() {


return t_name;
}

public void setDept(int deptno) {


this.deptno = deptno;
}

public int getDept() {


return deptno;
}
}

What is Expression Tag?


The expression tag is used to evaluate Java's expression within the JSP, which then converts
the result into a string and forwards the result back to the client browser via the response
object. Essentially, it is implemented for printing the result to the client (browser). An
expression tag can hold any java language expression that can be employed as an argument to
the out.print() method.

The syntax of the expression tag in JSP looks something like:

Syntax:

<%= expression %>


This is how the JSP container sees this when it encounters the above expression:

<%= (6*4) %>


It turns out to be:

out.print((6*4));
It is to be noted that you will never terminate an expression using semicolon within
Expression Tag. Like this:

<%= (6*4); %>


Here is an example of an Expression tag:

24
ADVANCED JAVA
Example:

<!DOCTYPE html>
<html>
<head>
<title>Expression Tag in JSP</title>
</head>
<% int rollNo = 02; %>
<body>
The next roll number is: <%= ++rollNo %>
</body>
</html>
Different Expression Tags with Different Expression Types:

Expression of Values

In this chase, you have to pass the expression of values within the expression tag.

Example:

<!DOCTYPE html>
<html>
<head>
<title>JSP expression tag example1</title>
</head>
<body>
<%= 2+4*5 %>
</body>
</html>

Expression of Variables

In this case, you have to initialize a few variables, which can then be passed as the expression
of variables within the expression tag in order to evaluate the result.

Example:

<!DOCTYPE html>
<html>
<head>
<title>JSP expression tag example2</title>
</head>
<body>
<% int g = 60; int k = 40; int r = 20; %>
<%= g+k+r %>
</body>
</html>

String with Implicit Object Output

25
ADVANCED JAVA
Here, you have to set an attribute using an application implicit object and then display it with
a simple string on another JSP page via an expression tag.

Example(start.jsp):

<!DOCTYPE html>
<html>
<head>
<title>Example of JSP expression tag</title>
</head>
<body>
<% application.setAttribute("EmpName", "Alex"); %>
<a href="show.jsp"> Click to See </a>
</body>
</html>
Example(show.jsp):

<!DOCTYPE html>
<html>
<head>
<title>Show Employee Name Page</title>
</head>
<body>
<%="A String value:" %> <br />
<%= application.getAttribute("EmpName") %>
</body>
</html>

Difference Between Scriptlet Tag and Expression Tag

1. In Scriptlet tag, it evaluates your Java expression but does not print or show your
result in conjunction with the HTML created. The declared variables have a local
scope only and hence can't take access from another place in the .jsp. In contrast, the
Expression Tag has the capability to evaluate the Java expression. It is used for
inserting the result in the form of a string in conjunction with the HTML in the JSP.
2. You don't have to write the out.println in the expression tag to print the expression
based output because these are changed into out.print() statement (as shown above the
process of transformation of expression), which gets inserted by the container in
the _jspService(-, -) of the servlet class.

26
ADVANCED JAVA
MVC Architecture in JSP with Example
Prashant Srivastava MVC in jsp
MVC stands for Model View Controller. It is a design pattern which is used to separate the
business logic, presentation logic and data. It can be used to design a web application in a
standard manner ie: It will provide a pattern to design web application. It is able to define
which element is used for which purpose. As per MVC, our application will be divided
into three layers.

1.Model Layer:
 Model Layer is the data layer.
 It consists of all the data of our web application.
 It represents a state of an application.
 The Model Layer is responsible to connect with the database as well as stores the data
into a database.
 It consists of all the classes in our application which have the connection to the
database.

2. View Layer:
 It represents the presentation layer
 It normally represents the User Interface (UI) of the application.
 We can use HTML,CSS,JS etc to create presentation layer.
3. Controller Layer:
 It is an interface between the view layer and the model layer.
 It receives the request from View Layer.
 It read the data which is coming from the presentation layer.
 To read data from the presentation layer, we can use Servlet, JSP, Filter, etc.
The MVC Architecture is given below:

MVC Architecture

27
ADVANCED JAVA

The advantage of MVC architecture are:


 It is easy to maintain.
 It is easy to test.
 It is easy to extend.
 The navigation control is centralized.

MVC Example in JSP


In this example, we are using servlet as a controller, jsp as a view component, Java Bean
class as a model.
In this example, we have created 5 pages:
o index.jsp a page that gets input from the user.
o ControllerServlet.java a servlet that acts as a controller.
o login-success.jsp and login-error.jsp files acts as view components.
o web.xml file for mapping the servlet.
o LoginMvcBean.java: It acts as a Model layer.

index.jsp

ControllerServlet.java

28
ADVANCED JAVA

LoginMvcBean.java

29
ADVANCED JAVA

loginSuccess.jsp

30
ADVANCED JAVA

loginError.jsp

web.xml

Output: When we enter the right credential.

31
ADVANCED JAVA

Output: When we enter the wrong credential.

32
ADVANCED JAVA

33
ADVANCED JAVA
JSTL Tags

 JSTL stands for JSP Standard Tag Library.


 It can be used only in JSP pages.
 JSTL tag can be used for conditional, iteration tags for manipulating the XML
document, internationalization tags, and SQL tags.
 It is used to remove scriptlet code from a JSP page.
Advantages of JSTL
1. Fast Development: we can provide many tags which simplify the JSP.
2. Code Reusability: Use the JSTL tags on the previous page.
3. It avoids the scriptlet tag.
Types of tags in JSTL
1. Core tags
2. Formatting tags
3. Function tags.
4. XML tags
5. SQL tags

1. JSTL Core Tags:


JSTL Core tags include those which are related to variables, and flow control, as well as it is
a generic way to access URL based resources.
Syntax:

The following are the JSTL Core tags:

i) c:out:
it is used to display the result of an expression. It is just like an expression tag.

ii) c:set:

34
ADVANCED JAVA
It is used to set the value of a variable in a specified scope.

iii) c:remove:
This JSTL core tag is used to remove an attribute from a specified scope or from all scope.

iv) c:catch:
It is used for exception handling in JSP.

35
ADVANCED JAVA

v) c:forEach:
It is used for iteration. It is just like for loop in java.

vi) c:param:
It is used to add a parameter and their values to the output of these tags.

vii) c:redirect:
It is used for redirecting the current page to another URL.

36
ADVANCED JAVA

viii) c:url:
To rewrite URL returned from a JSP page, we can use url tag.

ix) c:if:
It is used to testing the condition. It is just like to if statement in java.

x) c:import:
It is used for importing the content from another file/page to the current JSP page.

37
ADVANCED JAVA

2. JSTL Formatting tags:


JSTL formatting tags are used to formatting the text, date, number, etc. The JSTL Formatting
tags are also used to formatting the date, and time of internationalization websites.
Syntax:

The following are the JSTL Formatting Tags:

i) fmt:timeZone:
It specifies the time zone for any time formatting or parsing action nested in its body.

ii) fmt:setTimeZone:
Stores the given time zone in the time zone configuration variable.

iii) fmt:formatDate:
Formats a date and/or time using the supplied styles and pattern.

iv) fmt:message:
used to display an internationalized message.

v) fmt:formatNumber:
It is used to render numerical value with a specific precision or format.

vi) fmt:parseNumber:
Parses the string representation of number, currency, or percentage.

vii) fmt:parseDate:

38
ADVANCED JAVA
Parses the String representation of the date and/or time.

viii) fmt:bundle:
Load a resource bundle to be used by its tag body.

ix) fmt:setBundle:
Loads a resource bundle and stores it in the named scoped variable or the bundle
configuration variable.

3. JSTL Function tags:


This tag provides a number of predefined function that can be used to perform a common
operation such as String concatenation, String split etc. It is used for String manipulation.
Syntax:

The following are the JSTL Function Tags:


i) fn:contains():
It tests if an input string contains the specified substring.

ii) fn:containsIgnoreCase():
It tets if an input string contains the specified substring in a case-insensitive way.

iii) fn:endsWith():
It tets if an input string ends with the specified suffix.

iv) fn:indexOf():
Return the index writing a string of the first occurrence of the specified string.

v) fn:join():
It joins all the elements of an array into a String.

vi) fn:length():
It returns the number of character in a String or number of collection in a String.

vii) fn:replace():

It is used to replacing an input string all occurrences with the given String.

viii) fn:split():
Split a string into an array of a substring.

ix) fn:startsWith():
It tests if an input string starts with the specified prefix.

39
ADVANCED JAVA
x) fn:substring():
It returns a subset of a string

xi) fn:substringAfter():
It returns a subset of a String after a specific substring.

xii) fn:substringBefore():
It returns a subset of a String before a specific substring.

xiii) fn:toLowerCase():
It converts all of the characters of a string to lower case.

xiv) fn:toUpperCase():
It converts all of the characters of a string to upper case.

xv) fn:trim ():


It removes white spaces from both ends of a string.

4) JSTL XML Tags:


JSTL XML Tags are used to work with XML documents.It is used for manipulating and
creating XML document. It provide flow control, Transformation etc.
Syntax:

The following are the JSTL XML Tags:


i) x:out:
It evaluates the expression of XPath. It is just Like <%= %>, but for XPath expression.

ii) x:parse:
It is used to parse the XML data specified either via an attribute or in the tag body.

iii) x:set:
It sets the value of a variable of an XPath expression.

iv) x:choose:
Subtag of that will include its body if the condition evaluated to be 'true'.

v) x:when:
Subtag of <choose> that includes its body if its expression evaluates to 'true'.

vi) x:otherwise:
subtag of <choose> that follows the <when> tags and run only if all of the prior condition
evaluated to 'false'.

vii) x:if:

40
ADVANCED JAVA
It evaluates a test XPath expression and if it is true, it processes its body. If the condition is
false, then the body is ignored.

viii) x:param:

It is used along with the transform tag to set a parameter in the XSLT stylesheet.

ix) x: transform:
It applies an XSL transformation on a XML document.

5. JSTL SQL Tag:


This tag provides SQL support. It is used for interacting with RDBS(Relational Database
Management System) such as MySql, Oracle etc. we can run database queries using SQL
tags.
Syntax:

The following are the JSTL SQL Tags:


i) sql:setDataSource:
It creates a simple data source suitable for prototyping.

ii) sql:query:
It is used to executes the SQL queries defined in its body or through the SQL attribute.

iii) sql:update:
It executed the SQL update defined in its body or through the SQL attribute.

iv) sql:param:
It sets a parameter in an SQL statement to the specified value.

v) sql:dateParam:
It sets a parameter in an SQL statement to the specified java.util.Date value.

vi) sql:transaction:
It provides nested database action elements with a shared connection, set up to execute all
statement as one transaction

41
ADVANCED JAVA
Custom Tags in JSP with Example

Custom tags are user-defined tags. By using Custom tags we can get the following
advantages:
1. We can reduce the java code into a JSP page.
2. We can provide security in JSP.
3. We can get the logic reusability.
4. By using the custom tag we can separate the business logic from the JSP page.
To creating any Custom Tag we need three things:
1. The Tag Handler Class.
2. The Tag Library Descriptor.
3. A JSP page.

1. The Tag Handler Class:


The Tag Handler class is a java class in which the custom tag logic is defined. For every
custom tag, there should be an associated tag handler class. The number of custom tags in a
JSP page is equal to the number of tag handler classes. To create a tag handler class our java
class should extend one of the following two classes.
i) TagSupport Class
ii) BodyTagSupport class

These two classes are available inside the javax.servlet.jsp.tagext. package. if we want to
define the logic for a custom tag start and custom tag end then we override the following two
methods of the Tag Support class.
i) doStartTag()
ii) doEndTag()

42
ADVANCED JAVA
2. The Tag Library Descriptor:
A TLD file is like an XML file in which custom tags are configured. The main purpose of the
TLD file is to connect the Tag handler class with a tag name that will appear in the JSP
document. It also gives more information to the JSP container about the tags it describes. It
describes the tag attributes that can be used with the tag and tells whether they're required or
are optional.

3. A JSP page:
A JSP page is a page where we will be using our custom tag. In the JSP page to define some
prefix for our custom tags, we use taglib directive in JSP. Using taglib directive we also
define a unique identification name for the tag started with the same prefix. To add a prefix
and a unique identification name we use two attributes URI and prefix.

43
ADVANCED JAVA
Pagination in JSP
To divide a large number of records into multiple parts, we use pagination. It allows users to
display a part of records only. Loading all records on a single page may take time, so it is
always recommended to created pagination. In java, we can develop pagination examples
easily. In this pagination example, we are using the MySQL database to fetch records.

We can create pagination example in JSP easily. It is required if you have to display many
records. Displaying many records in a single page may take time, so it is better to break the
page into parts. To do so, we create pagination application.
In this pagination example, we are using MySQL database to fetch records.
We have created “emp” table in “test” database. The emp table has three fields: id, name and
salary. Either create table and insert records manually or import our sql file.

CRUD - CREATE, READ, UPDATE and DELETE Operations


CREATE - Here, CREATE in the sense to SAVE, the inputs which we initially want to store
in the database from the User.
READ - Soon as we CREATE or SAVE the details in the database, we want them to access
in our USER INTERFACE. So for that we have to read the saved values (which we done
earlier, i.e CREATE). This READ can be achieved through a SELECT query.
Note: If you want only the detail which is saved at that point then you have to make sure that
you change the SELECT QUERY to the current processing USERID.
UPDATE - To UPDATE the detail that is SAVED in the database, you have to CREATE a
dummy page of your MAIN page with same details which are mentioned in the registration
or a particular page and whenever the user clicks on EDIT button or link we should redirect
to that dummy page with the values which are requested by the user to EDIT & UPDATE.
DELETE - DELETE operation delete the particular record which is requested from the
database.

44

You might also like