Unit 5 - JSP

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

Java Server Pages (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.
Java Server Pages (JSP) - Fundamentals
• Java Server Pages are HTML pages embedded with
snippets of Java code.
– It is an inverse of a Java Servlet
• Four different elements
are used in constructing JSPs
1. Implicit Objects
2. Scripting Elements
3. Actions
4. Directives
How Is a JSP Processed?
How does JSP work?
JSP Document
Translation
.java file
Compilation
.class file

Reinitialization

.class file ready to run

Subsequent
User Requests

Response Document
Advantages of JSP over Servlet
There are many advantages of JSP over the Servlet. They are as follows:
1. Extension to Servlet
2. 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.
3. Easy to maintain
4. 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.
5. Fast Development: No need to recompile and redeploy
6. 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.
7. Less code than Servlet
8. 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.
Applications of JSP
As mentioned before, JSP is one of the most widely used language over
the web. I'm going to list few of them here:
•JSP vs. Active Server Pages (ASP)
The advantages of JSP are twofold. 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.
•JSP vs. Pure Servlets
It is more convenient to write (and to modify!) regular HTML than to
have plenty of println statements that generate the HTML.
•JSP vs. Server-Side Includes (SSI)
SSI is really only intended for simple inclusions, not for "real" programs
that use form data, make database connections, and the like.
•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.
•JSP vs. Static HTML
Regular HTML, of course, cannot contain dynamic information.
The Lifecycle of a JSP Page
The JSP pages follow these phases:
 Translation of JSP Page
 Compilation of JSP Page
 Classloading (the classloader loads class file)
 Instantiation (Object of the Generated Servlet is created).
 Initialization ( the container invokes jspInit() method).
 Request processing ( the container invokes _jspService()
method).
 Destroy ( the container invokes jspDestroy() method).
Lifecycle of a JSP Page
Translation – JSP pages doesn’t look like normal java classes,
actually JSP container parse the JSP pages and translate them to
generate corresponding servlet source code. If JSP file name is
home.jsp, usually its named as home_jsp.java.
Compilation – If the translation is successful, then container
compiles the generated servlet source file to generate class file.
Class Loading – Once JSP is compiled as servlet class, its lifecycle
is similar to servlet and it gets loaded into memory.
Instance Creation – After JSP class is loaded into memory, its
object is instantiated by the container.
Initialization – The JSP class is then initialized and it transforms
from a normal class to servlet. After initialization, ServletConfig
and ServletContext objects become accessible to JSP class.
Request Processing – For every client request, a new thread is
spawned with ServletRequest and ServletResponse to process
and generate the HTML response.
Destroy – Last phase of JSP life cycle where it’s unloaded into
memory.
 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.
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.
<html>
<body>
<% out.print(2*5); %>
</body> </html>
It will print 10 on the browser.
1.JSP Implicit Objects
These objects are created by JSP Engine
during translation phase (while translating
JSP to Servlet).
They are being created inside service method
so we can directly use them
within Scriptlet without initializing and
declaring them.
There are total 9 implicit objects available in
JSP.
out javax.servlet.jsp.JspWriter
request javax.servlet.http.HttpServletRequest

response javax.servlet.http.HttpServletResponse

session javax.servlet.http.HttpSession
application javax.servlet.ServletContext
exception javax.servlet.jsp.JspException
page java.lang.Object
pageContext javax.servlet.jsp.PageContext
config javax.servlet.ServletConfig
1. Out: This is used for writing content to the client (browser). It
has several methods which can be used for properly
formatting output message to the browser and for dealing
with the buffer.

2. Request: The main purpose of request implicit object is to


get the data on a JSP page which has been entered by user
on the previous JSP page. While dealing with login and
signup forms in JSP we often prompts user to fill in those
details, this object is then used to get those entered details
on an another JSP page (action page) for validation and other
purposes.

3. Response: It is basically used for modfying or delaing with


the response which is being sent to the client(browser) after
processing the request.
4. Session: It is most frequently used implicit object,
which is used for storing the user’s data to make it
available on other JSP pages till the user session is
active.

5. Application: This is used for getting application-wide


initialization parameters and to maintain useful data
across whole JSP application.

6. Exception: Exception implicit object is used in


exception handling for displaying the error messages.
This object is only available to the JSP pages, which has
isErrorPage set to true.
7. Page: Page implicit object is a reference to the current
Servlet instance (Converted Servlet, generated during
translation phase from a JSP page). We can simply
use this in place of it. I’m not covering it in detail as it is
rarely used and not a useful implicit object while building
a JSP application.

8. pageContext: It is used for accessing page, request,


application and session attributes.

9. Config: This is a Servlet configuration object and mainly


used for accessing getting configuration information such
as servlet context, servlet name, configuration parameters
etc.
2.JSP Scripting
In JSP there are three types of scripting elements:

•JSP Expressions: It is a small java code which you


can include into a JSP page.
The syntax is “<%= some java code %>”
•JSP Scriptlet: The syntax for a scriptlet is “<%
some java code %>”. You can add 1 to many lines
of Java code in here.
•JSP Declaration: The syntax for declaration is
“<%! Variable or method declaration %>”, in here
you can declare a variable or a method for use
later in the code.
JSP Scripting: Example
<%! … %> JSP declaration tag
<%= … %> JSP expression tag
<% … %> JSP scriptlet tag

<html>
<body>
<%! int data=50; %>
<% out.print(“Data=“+data); %>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
JSP Expressions
Using the JSP Expression you can compute a small expression,
always a single line, and get the result included in the HTML
which is returned to the browser. Using the code we have
previously written, let’s explore expressions.

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

Output
The time on the server is Thursday January 21 07:21:43 GMT
2016.

Explanation
Here the “new java.util.Date()” is processed into the actual date
and time shown through HTML on the browser. Let’s explore
expressions through a couple of more examples.
The Expression: 25 multiplied to 4: <%= 25*4 %>
Using simple mathematical expressions you can
always compute and get answers to your
mathematical problems embedded in your HTML.

The HTML: 25 multiplied to 4: 100


You can also have Boolean expressions in JSP.

The Expression: Is 75 less than 69? <%= 75 <69 %>


The return type of these Boolean expressions is
string which is either going to be “true” or “false”

The HTML: Is 75 less than 69? False


JSP Scriptlets
• This JSP Scripting Element allows you to put in a
lot of Java code in your HTML code.
• This Java code is processed top to bottom when
the page is the processed by the web server.
• Here the result of the code isn’t directly
combined with the HTML rather you have to use
“out.println()” to show what you want to mix
with HTML.
• The syntax is pretty much the same only you
don’t have to put in an equal sign after the
opening % sign.
EXAMPLE

<h2> Hello World</h2>


<%
for(inti=0; i<= 5; i++)
{
out.println(“<br/> I really love counting: ” + i);
}
%> Output:
I really love counting: 1
I really love counting: 2
I really love counting: 3
I really love counting: 4
I really love counting: 5
JSP Declarations
The declarations come in handy when you
have a code snippet that you want
executed more than once. Using the
declaration, you can declare the method in
the beginning of the code and then call the
same method whenever you need in the
same page. The syntax is simple:
<%!
//declare a variable or a method
%>
Code Example
Here is the method declaration:
<%!
String makeItLower(String data)
{
returndata.toLowerCase();
}
%>
Here is how you call it
Lower case “Hello World”:<%= makeItLower(“Hello
World”) %>
Output
Lower case “Hello World”: hello world
3. JSP Action

•JSP actions use the construct in XML syntax to control the


behavior of the servlet engine.
•We can dynamically insert a file, reuse the beans
components, forward user to another page, etc. through JSP
Actions like include and forward.
•Unlike directives, actions are re-evaluated each time the
page is accessed.

Syntax:
<jsp:action_name attribute="value" />
JSP Action Tags
JSP Action Tags Description
jsp:forward forwards the request and response to another resource.

jsp:include includes another resource.


jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.

jsp:getProperty prints the value of property of the bean.

jsp:plugin embeds another components such as applet.

jsp:param sets the parameter value. It is used in forward and include


mostly.
jsp:fallback can be used to print the message if plugin is working. It is
used in jsp:plugin.
jsp:forward Action
• jsp:forward action allows you to forward a request to the
other page.
• The syntax of the jsp:forward action is listed as below.
• There is one attribute called page which value is a page you
want to forward the request to.
• You can specify the page statically or dynamically by using
the expression.
• <jsp:forward page="relativeURL | <%= expression %>“ />

<jsp:forward page="error.jsp" />


<jsp:forward page="<%= java-expression %>" />
jsp:forward with parameter
• Jsp:param can use with jsp:forward action tag
• Syntax
• <jsp:forward page="relativeURL | <%= expression %>">
• <jsp:param name="parametername" value="parametervalue | <%
=expression%>" />
• </jsp:forward>
index.jsp printdate.jsp
<html> <html>
<body> <body>
<h2>this is index page</h2>
<% out.print("Today
<jsp:forward page="printdate.jsp" > is:"+java.util.Calendar.getInstance().getTime());
<jsp:param name="name" %>
value="javatpoint.com" /> <%= request.getParameter("name") %>
</jsp:forward>
</body>
</body> </html>
</html>
jsp:include action
JSP include action allows you to include a file at runtime. The syntax
of JSP include action is as follows: In the page attribute, you insert a
relative URL of a file which could be an HTML file or another
JSP page. Unlike the include directive, the jsp include action insert a
file at the time page is being requested.

<jsp:include page="Relative URL" | <%= expression %> flush="true" />

Jsp:include action with param

<jsp:include page="relativeURL | <%= expression %>">

<jsp:param name="parametername" value="parametervalue | <%=expression%>"


/>

</jsp:include>
jsp:include action vs JSP include directive

JSP include directive JSP include action

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.
A JavaBean is a Java class that should follow the following
conventions:
It should have a no-arg constructor.
It should be Serializable.
It should provide methods to set and get the values of the properties,
known as getter and setter methods.
Why use JavaBean?
It is a reusable software component. A bean encapsulates many objects into
one object so that we can access this object from multiple places and
provides easy maintenance.

jsp:useBean action
JSP useBean action lets you load a JavaBean component into the page
and use it later.
JSP useBean action allows you to reuse other Java classes.
The jsp:useBean action tag is used to locate or instantiate a bean class.
The syntax of JSP useBean action is as follows:
<jsp:useBean id= "instanceName" scope= "page | request | session | application"
class= "packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression >" >
</jsp:useBean>
jsp:useBean action..
1.id: is used to identify the bean in the specified scope.
2.scope: represents the scope of the bean. It may be page, request, session or
application. The default scope is page.
1. page: specifies that you can use this bean within the JSP page. The
default scope is page.
2. request: specifies that you can use this bean from any JSP page that
processes the same request. It has wider scope than page.
3. session: specifies that you can use this bean from any JSP page in the
same session whether processes the same request or not. It has wider
scope than request.
4. application: specifies that you can use this bean from any JSP page in the
same application. It has wider scope than session.
3.class: instantiates the specified bean class (i.e. creates an object of the bean
class) but it must have no-arg or no constructor and must not be abstract.
4.type: provides the bean a data type if the bean already exists in the scope. It is
mainly used with class or beanName attribute. If you use it without class or
beanName, no bean is instantiated.
5.beanName: instantiates the bean using the java.beans.Beans.instantiate()
method.
jsp:setProperty action tags
Tags are used for developing web application with Java Bean

Syntax of jsp:setProperty action tag

<jsp:setProperty name="instanceOfBean" property= "*" |


property="propertyName" param="parameterName" |
property="propertyName" value="{ string | <%= expression %>}"
/>

<jsp:setProperty name="bean" property="username" value="Kumar" />


jsp:getProperty action tags
Tags are used for developing web application with Java Bean

The jsp:getProperty action tag returns the value of the property.

Syntax of jsp:getProperty action tag

<jsp:getProperty name="instanceOfBean" property="propertyName" />

Simple example of jsp:getProperty action tag


<jsp:getProperty name="obj" property="name" />
jsp:plugin Action

jsp:plugin action allows you to embedded Java


Applet into a page. Suppose you have an applet
which demonstrates the JSP page life
cycle called com.jsp.jspapplet.
Here is the way we use jsp:plugin action
to embedded that applet into a page:
<html>
<head>
<title>jsp:plugin Demo</title>
</head>
<body>
<jsp:plugin type="applet"
code="com.jsp.jspapplet"
codebase="."
width="500"
height="400">
<jsp:fallback>
<p>Unable to use Java Plugin</p>
</jsp:fallback>
</jsp:plugin>

</body>
</html>
4.JSP - Directives
What are JSP Directives?
• JSP directives are the messages to JSP container. They
provide global information about an entire JSP page.
• JSP directives are used to give special instruction to a
container for translation of JSP to servlet code.
• In JSP life cycle phase, JSP has to be converted to a
servlet which is the translation phase.
• They give instructions to the container on how to
handle certain aspects of JSP processing
• Directives can have many attributes by comma
separated as key-value pairs.
• In JSP, directive is described in <%@ %> tags.
Syntax of Directive:
<%@ directive attribute="" %>

There are three types of directives:


1.Page directive

2.Include directive

3.Taglib directive
JSP Page directive
Syntax of Page directive:
<%@ page…%>
• It provides attributes that get applied to entire JSP page.
• It defines page dependent attributes, such as scripting language, error page, and
buffering requirements.
• It is used to provide instructions to a container that pertains to current JSP page.
Following are its list of attributes associated with page directive:
1. Language
2. Extends
3. Import
4. contentType
5. info
6. session
7. isThreadSafe
8. autoflush
9. buffer
10.IsErrorPage
11.pageEncoding
12.errorPage
13.isELIgonored
1.language:
It defines the programming language (underlying
language) being used in the page.
Syntax of language:
<%@ page language="value" %>
Here value is the programming language (underlying
language)
Example:
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
Explanation of code: In the above example, attribute
language value is Java which is the underlying language
in this case. Hence, the code in expression tags would
be compiled using java compiler.
2.Extends: This attribute is used to extend (inherit) the
class like JAVA does
Syntax of extends:
<%@ page extends="value" %>
Here the value represents class from which it has to be
inherited.
Example:
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page extends="demotest.DemoClass" %>
Explanation of the code: In the above code JSP is
extending DemoClass which is within demotest package,
and it will extend all class features.
3.Import: This attribute is most used attribute in page
directive attributes.It is used to tell the container to import
other java classes, interfaces, enums, etc. while generating
servlet code.It is similar to import statements in java classes,
interfaces.
Syntax of import:
<%@ page import="value" %>
Here value indicates the classes which have to be imported.
Example:
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" import="java.util.Date"
pageEncoding="ISO-8859-1"%>
Explanation of the code:
In the above code, we are importing Date class from java.util
package (all utility classes), and it can use all methods of the
following class.
4.contentType:
•It defines the character encoding scheme i.e. it is used to
set the content type and the character set of the response
•The default type of contentType is "text/html;
charset=ISO-8859-1".
Syntax of the contentType:
<%@ page contentType="value" %>
Example:
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
Explanation of the code:
In the above code, the content type is set as text/html, it
sets character encoding for JSP and for generated response
page
5.info
•It defines a string which can be accessed by
getServletInfo() method.
•This attribute is used to set the servlet description.
Syntax of info:
<%@ page info="value" %>
Here, the value represents the servlet information.
Example:
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" info="Guru Directive JSP"
pageEncoding="ISO-8859-1"%>
Explanation of the code:
In the above code, string "Guru Directive JSP" can be
retrieved by the servlet interface using getServletInfo()
6.Session
•JSP page creates session by default.
•Sometimes we don't need a session to be created in JSP, and hence, we
can set this attribute to false in that case.The default value of the session
attribute is true, and the session is created.
When it is set to false, then we can indicate the compiler to not create the
session by default.
Syntax of session:
<%@ page session="true/false"%>
Here in this case session attribute can be set to true or false
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1" session="false"%>
Explanation of code:
In the above example, session attribute is set to "false" hence we are
indicating that we don't want to create any session in this JSP
7.isThreadSafe:
•It defines the threading model for the generated servlet.
•It indicates the level of thread safety implemented in the page.
•Its default value is true so simultaneous
•We can use this attribute to implement SingleThreadModel interface in
generated servlet.
•If we set it to false, then it will implement SingleThreadModel and can
access any shared objects and can yield inconsistency.
Syntax of isThreadSafe:
<% @ page isThreadSafe="true/false" %>
Here true or false represents if synchronization is there then set as true
and set it as false.
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1" isThreadSafe="true"%>
Explanation of the code:
In the above code, isThreadSafe is set to "true" hence synchronization
will be done, and multiple threads can be used.
8.AutoFlush:
This attribute specifies that the buffered output should be flushed
automatically or not and default value of that attribute is true.
If the value is set to false the buffer will not be flushed automatically and
if its full, we will get an exception.
When the buffer is none then the false is illegitimate, and there is no
buffering, so it will be flushed automatically.
Syntax of autoFlush:
<% @ page autoFlush="true/false" %>
Here true/false represents whether buffering has to be done or not
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1" autoFlush="false"%>
Explanation of the code:
In the above code, the autoflush is set to false and hence buffering won't
be done and it has manually flush the output.
9.Buffer:
•Using this attribute the output response object may be buffered.
•We can define the size of buffering to be done using this attribute and
default size is 8KB.
•It directs the servlet to write the buffer before writing to the response
object.
Syntax of buffer:
<%@ page buffer="value" %>
Here the value represents the size of the buffer which has to be defined.
If there is no buffer, then we can write as none, and if we don't mention
any value then the default is 8KB
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1" buffer="16KB"%>
Explanation of the code:
In the above code, buffer size is mentioned as 16KB wherein the buffer
would be of that size
10.isErrorPage:
•It indicates that JSP Page that has an errorPage will be checked in
another JSP page
•Any JSP file declared with "isErrorPage" attribute is then capable to
receive exceptions from other JSP pages which have error pages.
•Exceptions are available to these pages only.
•The default value is false.
Syntax of isErrorPage:
<%@ page isErrorPage="true/false"%>
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1" isErrorPage="true"%>
Explanation of the code:
In the above code, isErrorPage is set as true. Hence, it will check any
other JSPs has errorPage (described in the next attribute) attribute set and
it can handle exceptions.
index.jsp
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>

process.jsp error.jsp
<%@ page errorPage="error.jsp" %> <%@ page isErrorPage="true" %>
<% <h3>Sorry an exception occured!</h3>
Exception is: <%= exception %>
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");

int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);

%>
index.jsp
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>

process.jsp error.jsp
<%@ page errorPage="error.jsp" %> <%@ page isErrorPage="true" %>
<% <h3>Sorry an exception occured!</h3>
Exception is: <%= exception %>
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");

int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);

%>
11.PageEncoding:
The "pageEncoding" attribute defines the character
encoding for JSP page.
The default is specified as "ISO-8859-1" if any other is
not specified.
Syntax of pageEncoding:
<%@ page pageEncoding="vaue" %>
Here value specifies the charset value for JSP
Example:
<%@ page language="java" contentType="text/html;"
pageEncoding="ISO-8859-1" isErrorPage="true"%>
Explanation of the code:
In the above code "pageEncoding" has been set to default
charset ISO-8859-1
12.errorPage:
This attribute is used to set the error page for the JSP page if
JSP throws an exception and then it redirects to the exception
page.
Syntax of errorPage:
<%@ page errorPage="value" %>
Here value represents the error JSP page value
Example:
<%@ page language="java" contentType="text/html;"
pageEncoding="ISO-8859-1"
errorPage="errorHandler.jsp"%>
Explanation of the code:
In the above code, to handle exceptions we have
errroHandler.jsp
13.isELIgnored:
•IsELIgnored is a flag attribute where we have to decide whether to
ignore EL tags or not.
•Its datatype is java enum, and the default value is false hence EL is
enabled by default.
Syntax of isELIgnored:
<%@ page isELIgnored="true/false" %>
Here, true/false represents the value of EL whether it should be ignored
or not.
Example:
<%@ page language="java" contentType="text/html;"
pageEncoding="ISO-8859-1" isELIgnored="true"%>
Explanation of the code:
In the above code, isELIgnored is true and hence Expression Language
(EL) is ignored here.
In the below example we are using four attributes(code line 1-2)
Example with four attributes
1.<%@ page language="java" contentType="text/html;"
pageEncoding="ISO-8859-1"
2.isELIgnored="false"%>
3.<%@page import="java.util.Date" %>
5.<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
6.<html>
7.<head>
8.<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
9.<title>Directive Guru JSP1</title>
10.</head>
11.<body>
12.<a>Date is:</a>
13.<%= new java.util.Date() %>
14.</body>
15.</html>
Explanation of the code:
Code Line 1-2: Here we have defined four attributes i.e.
•Language: It is set as Java as programming language
•contentType: set as text/html to tell the compiler that html has to be
format
•pageEncoding: default charset is set in this attribute
•isELIgnored: Expression Tag is false hence it is not ignored
Code Line 3: Here we have used import attribute, and it is importing
"Date class" which is from Java util package, and we are trying to
display current date in the code.
When you execute the above code, you will get the following output
JSP Include directive
• The include directive is used to include a file during the
translation phase.
• This directive tells the container to merge the content
of other external files with the current JSP during the
translation phase.
• You may code include directives anywhere in your JSP
page.
• The filename in the include directive is actually a
relative URL.
• Syntax
– <%@ include file = "relative url" >
– <jsp:directive.include file = "relative url" />
Example: Include directive
• include directive
• A common header and footer with multiple pages of content.
– header.jsp
– footer.jsp and
– main.jsp
main.jsp
Main.jsp
<%@ include file = "header.jsp" %>
<center>
<p>Thanks for visiting my page.</p>
</center>
<%@ include file = "footer.jsp" %>
JSP 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 JSP Taglib directive
– <%@ taglib uri="uriofthetaglibrary"
prefix="prefixoftaglibrary" %>
Example: Taglib directive
<html>
<body>

<%@ taglib uri="http://www.javatpoint.com/tags"


prefix="mytag" %>

<mytag:currentDate/>

</body>
</html>
Custom Tags in JSP
Custom Tags
• Custom tags are user-defined tags.
• They eliminates the possibility of scriptlet tag and separates the
business logic from the JSP page.
• The same business logic can be used many times by the use of
custom tag.
Advantages of Custom Tags: The key advantages of Custom tags are
as follows
1. Eliminates the need of scriptlet tag The custom tags eliminates
the need of scriptlet tag which is considered bad programming
approach in JSP.
2. Separation of business logic from JSP The custom tags separate
the the business logic from the JSP page so that it may be easy to
maintain.
3. Re-usability The custom tags makes the possibility to reuse the
same business logic again and again.
Syntax to use custom tag
There are two ways to use the custom tag. They
are given below:
<prefix:tagname attr1=value1....attrn=valuen />

<prefix:tagname attr1=value1....attrn=valuen >


body code
</prefix:tagname>
JSP Custom Tag API
The javax.servlet.jsp.tagext package contains classes and
interfaces for JSP custom tag API.
JspTag is the root interface in the Custom Tag hierarchy.

Tag interface: is the


sub interface of JspTag
interface.
It provides methods to
perform action at the
start and end of the tag.
Fields of Tag interface
There are four fields defined in the Tag interface. They are:

Field Name Description


public static int It evaluates the body content.
EVAL_BODY_INCLUDE
public static int EVAL_PAGE it evaluates the JSP page content after
the custom tag.
public static int SKIP_BODY it skips the body content of the tag.

public static int SKIP_PAGE it skips the JSP page content after the
custom tag.
Methods of Tag interface
The methods of the Tag interface are as follows:

Method Name Description


public void setPageContext(PageContext pc) it sets the given PageContext object.

public void setParent(Tag t) it sets the parent of the tag handler.


public Tag getParent() it returns the parent tag handler object.
public int doStartTag()throws JspException it is invoked by the JSP page implementation object. The
JSP programmer should override this method and
define the business logic to be performed at the start of
the tag.
public int doEndTag()throws JspException it is invoked by the JSP page implementation object. The
JSP programmer should override this method and
define the business logic to be performed at the end of
the tag.
public void release() it is invoked by the JSP page implementation object to
release the state.
IterationTag interface
The IterationTag interface is the sub interface of the Tag interface.
It provides an additional method to reevaluate the body.
Field of IterationTag interface :
IterationTag interface.
•public static int EVAL_BODY_AGAIN
•it re-evaluates the body content.
Method of Tag interface
•public int doAfterBody()throws JspException
•it is invoked by the JSP page implementation object after the
evaluation of the body.
•If this method returns EVAL_BODY_INCLUDE, body content will
be reevaluated,
•if it returns SKIP_BODY, no more body cotent will be evaluated.
Example of JSP Custom Tag
In this example, we are going to create a custom tag that
prints the current date and time. We are performing
action at the start of tag.
For creating any custom tag, we need to follow following
steps:
1. Create the Tag handler class and perform action at
the start or at the end of the tag.
2. Create the Tag Library Descriptor (TLD) file and define
tags
3. Create the JSP file that uses the Custom tag defined
in the TLD file
Understanding flow of custom tag in jsp
1. Create the Tag handler class

•To create the Tag Handler, we are inheriting


the TagSupport class and overriding its
method doStartTag().To write data for the jsp,
we need to use the JspWriter class.

•The PageContext class provides getOut()


method that returns the instance of JspWriter
class. TagSupport class provides instance of
pageContext bydefault.
File: MyTagHandler.java
package com.javatpoint.mytag;
import java.util.Calendar;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class MyTagHandler extends TagSupport{


public int doStartTag() throws JspException {
JspWriter out=pageContext.getOut();
//returns the instance of JspWriter
try{
out.print(Calendar.getInstance().getTime());
//printing date and time using JspWriter
} catch(Exception e){System.out.println(e);}
return SKIP_BODY; // field of tag interface
//will not evaluate the body content of the tag
} }
2) Create the TLD file
Tag Library Descriptor (TLD) file contains information of tag and Tag Hander
classes. It must be contained inside the WEB-INF directory.
File: mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>

<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>http://tomcat.apache.org/example-taglib</uri>

<tag>
<name>today</name>
<tag-class>com.javatpoint. mytag.MyTagHandler</tag-class>
</tag>
</taglib>
3) Create the JSP file
Let's use the tag in our jsp file. Here, we are specifying
the path of tld file directly. But it is recommended to
use the uri name instead of full path of tld file. We will
learn about uri later.
It uses taglib directive to use the tags defined in the tld
file.
File: index.jsp
<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>
Current Date and Time is: <m:today/>
OUTPUT
Attributes in JSP Custom Tag
There can be defined too many attributes for any
custom tag. To define the attribute, you need to
perform two tasks:
Define the property in the TagHandler class with the
attribute name and define the setter method define the
attribute element inside the tag element in the TLD file
Let's understand the attribute by the tag given below:
<m:cube number="4"></m:cube>

Here m is the prefix, cube is the tag name and number is


the attribute.
Simple example of attribute in JSP Custom Tag
In this example, we are going to use the cube tag
which return the cube of any given number. Here,
we are defining the number attribute for the cube
tag. We are using the three file here:
•index.jsp
•CubeNumber.java
•mytags.tld
index.jsp
<%@ taglib uri="WEB-
INF/mytags.tld" prefix="m" %>
Cube of 4 is: <m:cube number="4"></m:cube>
CubeNumber.java
package com.javatpoint.taghandler;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class CubeNumber extends TagSupport{


private int number;

public void setNumber(int number) {


this.number = number;
}

public int doStartTag() throws JspException {


JspWriter out=pageContext.getOut();
try{
out.print(number*number*number);
}catch(Exception e){e.printStackTrace();}

return SKIP_BODY;
}
}
mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
index.jsp
<uri>http://tomcat.apache.org/example-taglib</uri>
<%@ taglib uri="W
<description>A simple tab library for the examples</description>
EB-
INF/mytags.tld" pre
<tag>
fix="m" %>
<name>cube</name>
Cube of 4 is: <m:cu
<tag-class>com.javatpoint.taghandler.CubeNumber</tag-class>
be number="4"></
<attribute>
m:cube>
<name>number</name>
<required>true</required>
</attribute>
</tag>
</taglib>
Iteration using JSP Custom Tag
We can iterate the body content of any tag using
the doAfterBody() method of IterationTag interface.
Here we are going to use the TagSupport class which
implements the IterationTag interface.
For iterating the body content, we need to use
the EVAL_BODY_AGAIN constant in the doAfterBody()
method.
Example of Iteration using JSP Custom Tag
In this example, we are going to use the attribute in the
custom tag, which returns the power of any given
number. We have created three files here
•index.jsp
•PowerNumber.java
•mytags.tld
index.jsp
<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>

3 ^ 5 = <m:power number="3" power="5">


body
</m:power>

729
PowerNumber.java
package com.javatpoint.taghandler;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class PowerNumber extends TagSupport{


private int number;
private int power;
private static int counter;
private static int result=1;

public void setPower(int power) {


this.power = power;
}
public void setNumber(int number) {
this.number = number;
}

public int doStartTag() throws JspException {


return EVAL_BODY_INCLUDE;
}
public int doAfterBody() {
counter++;
result *= number;
if (counter==power)
return SKIP_BODY;
else
return EVAL_BODY_AGAIN;
}

public int doEndTag() throws JspException {


JspWriter out=pageContext.getOut();
try{
out.print(result);
}catch(Exception e){e.printStackTrace();}
return EVAL_PAGE;
} }
mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name> <attribute>
<uri>http://tomcat.apache.org/example-taglib</uri> <name>number</name>
<description>A simple tab library for the examples <required>true</required>
</description> </attribute>

<tag> <attribute>
<name>power</name> <name>power</name>
<tag-class>com.javatpoint.taghandler.PowerNumber <required>true</required>
</tag-class> </attribute>

</tag>
</taglib>
Looping using Iteration Tag (creating tag for loop)
Let's create a loop tag that iterates the body content of this tag.

File: index.jsp
<!DOCTYPE html PUBLIC "-
//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Insert title here</title>
</head>
<body>

<%@taglib prefix="m" uri="sssuri" %>


<m:loop end="5" start="1">
<p>My Name is khan</p>  text to display
</m:loop>

</body>
</html>
File: mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-
//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<attribute>
<short-name>abc</short-name>
<name>start</name>
<required>true</required>
<uri>sssuri</uri>
</attribute>
<tag>
<name>loop</name>
<attribute>
<tag-class>com.javatpoint.customtag.Loop</tag-class>
<name>end</name>
<required>true</required>
</attribute>
</tag>

</taglib>
File: Loop.java
package com.javatpoint.customtag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class Loop extends TagSupport{


private int start=0;
private int end=0;
@Override
public void setStart(int start) { public int doAfterBody() throws JspException
this.start = start; {
} if(start<end){
public void setEnd(int end) { start++;
this.end = end; return EVAL_BODY_AGAIN;
} }else{
return SKIP_BODY;
@Override }
public int doStartTag() throws JspException {
return EVAL_BODY_INCLUDE; }
}

}
File: web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="h
ttp://java.sun.com/xml/ns/javaee/web-
app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/java
ee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd" id="WebApp_ID" version="3.0">

<jsp-config>
<taglib>
<taglib-uri>sssuri</taglib-uri>
<taglib-location>/WEB-INF/mytags.tld</taglib-location>
</taglib>
</jsp-config>

</web-app>
OUTPUT
Custom URI in JSP Custom Tag

We can use the custom URI, to tell the web container about the
tld file. In such case, we need to define the taglib element in the
web.xml. The web container gets the information about the tld
file from the web.xml file for the specified URI.

Example to use custom URI in JSP Custom Tag

In this example, we are going to use the custom uri in the JSP file.
For this application, we need to focus on 4 files.
1. index.jsp
2. web.xml
3. mytags.tld
4. PrintDate.java
index.jsp
1.<%@ taglib uri="mytags" prefix="m" %>
2.Today is: <m:today></m:today>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<jsp-config>
<taglib>
<taglib-uri>mytags</taglib-uri>
<taglib-location>/WEB-INF/mytags.tld</taglib-location>
</taglib>
</jsp-config>
</web-app> `
mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>mytags</uri>
<description>A simple tab library for the examples</description>

<tag>
<name>today</name>
<tag-class>com.javatpoint.taghandler.PrintDate</tag-class>
</tag>
</taglib>
PrintDate.java
package com.javatpoint.taghandler;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class PrintDate extends TagSupport{

public int doStartTag() throws JspException {


JspWriter out=pageContext.getOut();
try{
out.print(java.util.Calendar.getInstance().getTime());
}catch(Exception e){e.printStackTrace();}

return SKIP_BODY;
}
}

You might also like