You are on page 1of 73

• JSP: Overview, lifecycle, Architecture.

JSP
Elements: Directives, Scripting, Action tags,
Implicit Objects, Comments. Custom Tags,
Scope: page, request, session, JSP Exception
handling.
JSP - Lifecycle
• A JSP life cycle is defined as the process from its creation till the destruction.
• This is similar to a servlet life cycle with an additional step which is required to
compile a JSP into servlet.
Paths Followed By JSP
Compilation
Initialization
Execution
Cleanup
• JSP Compilation
• When a browser asks for a JSP, the JSP engine first checks
to see whether it needs to compile the page.
• If the page has never been compiled, or if the JSP has
been modified since it was last compiled,
the JSP engine compiles the page.
• The compilation process involves three steps −
• Parsing the JSP.
• Turning the JSP into a servlet.
• Compiling the servlet.
JSP Initialization
• When a container loads a JSP it invokes
the jspInit() method before servicing any
requests. If you need to perform JSP-specific
initialization, override the jspInit() method −
public void jspInit()
{ // Initialization code... }
• Typically, initialization is performed only once and
as with the servlet init() method, you generally
initialize database connections, open files, and
create lookup tables in the jspInit () method.
JSP Execution
• This phase of the JSP life cycle represents all interactions with
requests until the JSP is destroyed.
• Whenever a browser requests a JSP and the page has been
loaded and initialized, the JSP engine invokes
the _jspService() method in the JSP.
• The _jspService() method takes an HttpServletRequest and
an HttpServletResponse as its parameters as follows −
void jspService(HttpServletRequest request,
HttpServletResponse response) { // Service handling code... }
• The _jspService() method of a JSP is invoked on request basis.
This is responsible for generating the response for that request
and this method is also responsible for generating responses
to all seven of the HTTP methods, i.e, GET, POST, DELETE, etc.
JSP Cleanup
• The destruction phase of the JSP life cycle
represents when a JSP is being removed from use
by a container.
• The jspDestroy() method is the JSP equivalent of
the destroy method for servlets. Override
jspDestroy when you need to perform any
cleanup, such as releasing database connections
or closing open files.
• The jspDestroy() method has the following form −
public void jspDestroy() { // Your cleanup code
goes here. }
JSP – Syntax-Elements of JSP
The elements of JSP have been described below −
• The Scriptlet
• A scriptlet can contain any number of JAVA language statements, variable or
method declarations, or expressions that are valid in the page scripting
language.
• Following is the syntax of Scriptlet −
• <% code fragment %> You can write the XML equivalent of the above syntax as
follows −

Following is the simple

<html>
<head>
<title>Hello World</title>
</head>
<body> Hello World!<br/>
<% out.println("Your IP address is " + request.getRemoteAddr()); %>
</body> </html>
Index.html
<html>  
<body>  
<form action="welcome.jsp">  
<input type="text" name="uname"> welcome.jsp
  
<html>  
<input type="submit" value="go">
<body>  
<br/>  
<%  
</form>  
String name=request.getParameter("u
</body>   name");  
</html> out.print("welcome "+name);  
%>  
</form>  
</body>  
</html>  
JSP Declarations
• A declaration declares one or more variables or methods
that you can use in Java code later in the JSP file. You must
declare the variable or method before you use it in the JSP
file.
• Following is the syntax for JSP Declarations −
<%! declaration; [ declaration; ]+ ... %>
You can write the XML equivalent of the above syntax as follows −
<jsp:declaration> code fragment </jsp:declaration>
• Following is an example for JSP Declarations −
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
JSP Expression

• A JSP expression element contains a scripting language


expression that is evaluated, converted to a String, and inserted
where the expression appears in the JSP file.
• Because the value of an expression is converted to a String, you
can use an expression within a line of text, whether or not it is
tagged with HTML, in a JSP file.
• The expression element can contain any expression that is valid
according to the Java Language Specification but you cannot use
a semicolon to end an expression.
• Following is the syntax of JSP Expression −
<%= expression %>
• You can write the XML equivalent of the above syntax as follows

<jsp:expression> expression </jsp:expression>
Following example shows a JSP Expression −
<html>
<head>
<title>A Comment Test</title>
</head>
<body>
<p>Today's date:
<%= (new java.util.Date()).toLocaleString()%>
</p>
</body>
</html>

The above code will generate the following result −


Today's date: 11-Sep-2010 21:24:25
<html>  
<body>  
<%! int data=50; %>  
<%= "Value of the variable is:"+data %>  
</body>  
</html>  
Defining the methods
Index.jsp
<html>  
<body>  
<%!   
int cube(int n) {  
return n*n*n*;  
}  
%>  
<%= "Cube of 3 is:"+cube(3) %>  
</body>  
</html>  
JSP Comments
• JSP comment marks text or statements that the JSP container should
ignore. A JSP comment is useful when you want to hide or
"comment out", a part of your JSP page.
• Following is the syntax of the JSP comments −
<%-- This is JSP comment --%>

Following example shows the JSP Comments −


<html>
<head>
<title>A Comment Test</title>
</head>
<body> <h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body> </html>
There are a small number of special constructs you can use in various cases to insert
comments or characters that would otherwise be treated specially. Here's a summary −

S.No. Syntax & Purpose

<%-- comment --%>


1 A JSP comment. Ignored by the JSP engine.

<!-- comment -->


2 An HTML comment. Ignored by the browser.

<\%
3 Represents static <% literal.

%\>
4 Represents static %> literal.

\'
5 A single quote in an attribute that uses single quotes.

\"
6 A double quote in an attribute that uses double quotes.
Implicit Objects.
There are 9 jsp implicit objects. These objects are created by the
web container that are available to all the jsp pages.
Object Type

out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
1) JSP out implicit object
For writing any data to the buffer, JSP provides an implicit object named out.
It is the object of JspWriter.
In case of servlet you need to write:
PrintWriter out=response.getWriter();  
But in JSP, you don't need to write this code.

Example of out implicit object


In this example we are simply displaying date and time.

index.jsp

<html>  
<body>  

<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>  
</body>  
</html>  
JSP request implicit object

• The JSP request is an implicit object of type


HttpServletRequest i.e. created for each jsp
request by the web container.
• It can be used to get request information such
as parameter, header information, remote
address, server name, server port, content
type, character encoding etc.
• It can also be used to set, get and remove
attributes from the jsp request scope.
index.html welcome.jsp
<form action="welcome.jsp">   <%   
<input type="text" name String name=request.getParamet
="uname">   er("uname");  
<input type="submit" value="go out.print("welcome "+name);  
"><br/>   %>  
</form>  
JSP response implicit object
• In JSP, response is an implicit object of type HttpServletResponse. The instance of
HttpServletResponse is created by the web container for each jsp request.
• It can be used to add or manipulate response such as redirect response to another
resource, send error etc.
• Let's see the example of response implicit object where we are redirecting the
response to the Google.
• Example of response implicit object
• index.html
• <form action="welcome.jsp">  
• <input type="text" name="uname">  
• <input type="submit" value="go"><br/>  
• </form>  
• welcome.jsp
• <%   
• response.sendRedirect("http://www.google.com");  
• %>  
JSP config implicit object
• In JSP, config is an implicit object of type ServletConfig. This
object can be used to get initialization parameter for a
particular JSP page. The config object is created by the web
container for each jsp page.
• Generally, it is used to get initialization parameter from the
web.xml file.

welcome.jsp
index.html
<%   
<form action="welcome">  
out.print("Welcome "+request.getParameter("u
<input type="text" name="uname">  
name"));  
<input type="submit" value="go"><br/>  
  
</form>  
String driver=config.getInitParameter("dname"); 
 
out.print("driver name is="+driver);  
%>  
web.xml file

<web-app>  
  <servlet>  
<servlet-name>sonoojaiswal</servlet-name>  
<jsp-file>/welcome.jsp</jsp-file>  
  <init-param>  
<param-name>dname</param-name>  
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
</init-param>  
  </servlet>  
  <servlet-mapping>  
<servlet-name>sonoojaiswal</servlet-name>  
<url-pattern>/welcome</url-pattern>  
</servlet-mapping>  
  </web-app>  
JSP application implicit object
• In JSP, application is an implicit object of type ServletContext.
• The instance of ServletContext is created only once by the web container
when application or project is deployed on the server.
• This object can be used to get initialization parameter from configuaration
file (web.xml). It can also be used to get, set or remove attribute from the
application scope.
• This initialization parameter can be used by all jsp pages.
welcome.jsp
index.html <%   
<form action="welcome">     
<input type="text"  out.print("Welcome "+request.getParameter("uname"));  
name="uname">     
<input type="submit"  String driver=application.getInitParameter("dname");  
out.print("driver name is="+driver);  
value="go"><br/>  
  
</form>  
%>  
<web-app>  
  
<servlet>  
<servlet-name>sonoojaiswal</servlet-name>  
<jsp-file>/welcome.jsp</jsp-file>  
</servlet>  
  
<servlet-mapping>  
<servlet-name>sonoojaiswal</servlet-name>  
<url-pattern>/welcome</url-pattern>  
</servlet-mapping>  
  
<context-param>  
<param-name>dname</param-name>  
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
</context-param>  
  
</web-app>  
pageContext implicit object
• In JSP, pageContext is an implicit object of type PageContext
class.The pageContext object can be used to set,get or remove
attribute from one of the following scopes:
• page
• request
• session
• Application
• In JSP, page scope is the default scope.
index.html
<html>  
<body>  
<form action="welcome.jsp">  
<input type="text" name="uname">  
<input type="submit" value="go"><br/>  
</form>  
</body>  
</html>  
welcome.jsp
<html>  
<body>  
<%   
  String name=request.getParameter("uname");  
out.print("Welcome "+name);  
  
pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE)
;  
 <a href="second.jsp">second jsp page</a>  
  
%>  
</body>  
</html>  
second.jsp
<html>  
<body>  
<%   
  
String name=(String)pageContext.getAttribute("user",PageCo
ntext.SESSION_SCOPE);  
out.print("Hello "+name);  
  
%>  
</body>  
</html>  
page implicit object:

In JSP, page is an implicit object of type Object class. This object is


assigned to the reference of auto generated servlet class.

It is written as:

Object page=this;

For using this object it must be cast to Servlet type.For example:

<% (HttpServlet)page.log("message"); %>

Since, it is of type Object it is less used because you can use this object
directly in jsp. For example:

<% this.log("message"); %>


exception implicit object

• In JSP, exception is an implicit object of type


java.lang.Throwable class. This object can be used to print the
exception. But it can only be used in error pages. It is better to
learn it after page directive.

error.jsp
<%@ page isErrorPage="true" %>  
<html>  
<body>  
  
Sorry following exception occured:<%= exception %>  
  
</body>  
</html>  
JSP directives
• The jsp directives are messages that tells the
web container how to translate a JSP page into
the corresponding servlet.
• There are three types of directives:
– page directive
– include directive
– taglib directive
• Syntax of JSP Directive
<%@ directive attribute="value" %>  
JSP Directives

S.No. Directive & Description

<%@ page ... %>


Defines page-dependent attributes, such as scripting language, error page,
1 and buffering requirements.

<%@ include ... %>


2 Includes a file during the translation phase.

<%@ taglib ... %>


3 Declares a tag library, containing custom actions, used in the page
JSP page directive
– The page directive defines attributes that apply to
an entire JSP page.
– Syntax of JSP page directive
– <%@ page attribute="value" %>  
Attributes of JSP page directive
• import
• contentType
• extends
• info
• buffer
• language
• isELIgnored
• isThreadSafe
• autoFlush
• session
• pageEncoding
• errorPage
• isErrorPage
1)import
The import attribute is used to import class,interface or all the
members of a package.It is similar to import keyword in java
class or interface.
<html>  
<body>  
  
<%@ page import="java.util.Date" %>  
Today is: <%= new Date() %>  
  
</body>  
</html>  
contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail
Extension) type of the HTTP response.The default value is
"text/html;charset=ISO-8859-1".

<html>  
<body>  
<%@ page contentType=application/msword %>  Today is: <
%= new java.util.Date() %>  
</body>  
</html> 
extends
The extends attribute specifies a superclass that the
generated servlet must extend.
<%@ page extends = "somePackage.SomeClass" %>

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

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


buffer

The buffer attribute sets the buffer size in kilobytes to handle output
generated by the JSP page.The default size of the buffer is 8Kb.

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

language
• The language attribute indicates the programming language used
in scripting the JSP page.
• For example, because you usually use Java as the scripting
language, your language option looks like this −

<%@ page language = "java" %>


isELIgnored
We can ignore the Expression Language (EL) in jsp by the
isELIgnored attribute. By default its value is false i.e. Expression
Language is enabled by default. We see Expression Language later.

<%@ page isELIgnored="true" %>//Now EL will be ignored

isThreadSafe
The isThreadSafe option marks a page as being thread-safe. By default, all JSPs
are considered thread-safe. If you set the isThreadSafe option to false, the JSP
engine makes sure that only one thread at a time is executing your JSP.
The following page directive sets the isThreadSafe option to false −
<%@ page isThreadSafe = "false" %>
The autoFlush Attribute
• The autoFlush attribute specifies whether buffered output should be
flushed automatically when the buffer is filled, or whether an exception
should be raised to indicate the buffer overflow.
• A value of true (default) indicates automatic buffer flushing and a value of
false throws an exception.
• The following directive causes the servlet to throw an exception when the
servlet's output buffer is full −
<%@ page autoFlush = "false" %>
• Usually, the buffer and the autoFlush attributes are coded on a single page
directive as follows −
<%@ page buffer = "16kb" autoflush = "true" %>
The session Attribute

• The session attribute indicates whether or not the JSP page uses


HTTP sessions. A value of true means that the JSP page has access
to a builtin session object and a value of false means that the JSP
page cannot access the builtin session object.
• Following directive allows the JSP page to use any of the builtin
object session methods such
as session.getCreationTime() or session.getLastAccessTime() −

<%@ page session = "true" %>


Jsp Include Directive
• The include directive is used to include the contents of any resource it may
be jsp file, html file or text file. The include directive includes the original
content of the included resource at page translation time (the jsp page is
translated only once so it will be better to include static resource).
• Advantage of Include directive
Code Reusability

<html>  
<body>  
  
<%@ include file="header.html" %>  
  
Today is: <%= java.util.Calendar.getInstance().getTime() %>  
  
</body>  
</html>  
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" %>

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


JSP – Action tags or elements.
• The action tags are used to control the flow between pages
and to use Java Bean. The Jsp action tags are given below.
• These actions use constructs in XML syntax to control the
behavior of the servlet engine. You can dynamically insert a
file, reuse JavaBeans components, forward the user to
another page, or generate HTML for the Java plugin.
• There is only one syntax for the Action element, as it
conforms to the XML standard −
– <jsp:action_name attribute = "value" />
• Action elements are basically predefined functions.
JSP Action Tags Description
jsp:forward forwards the request and response to another resource.
Forwards the requester to a new page.
jsp:include includes another resource.
Includes a file at the time the page is requested.
jsp:useBean creates or locates bean object. Finds or instantiates a
JavaBean.
jsp:setProperty sets the value of property in bean object.
jsp:getProperty prints the value of property of the bean.
Inserts the property of a JavaBean into the output.
jsp:plugin embeds another components such as applet.
Generates browser-specific code that makes an OBJECT or
EMBED tag for the Java plugin.
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:element
Defines XML elements dynamically.

jsp:attribute
Defines dynamically-defined XML element's attribute.
jsp:body
Defines dynamically-defined XML element's body.
jsp:text
Used to write template text in JSP pages and documents.
Common Attributes
There are two attributes that are common to all Action elements:
the id attribute and the scope attribute.
Id attribute
The id attribute uniquely identifies the Action element, and allows
the action to be referenced inside the JSP page. If the Action
creates an instance of an object, the id value can be used to
reference it through the implicit object PageContext.
Scope attribute
This attribute identifies the lifecycle of the Action element. The id
attribute and the scope attribute are directly related, as the scope
attribute determines the lifespan of the object associated with the
id. The scope attribute has four possible values:
 (a) page, (b)request, (c)session, and (d) application.
The <jsp:include> Action
• This action lets you insert files into the page being generated.
Unlike the include directive, which inserts the file at the time the
JSP page is translated into a servlet, this action inserts the file at the
time the page is requested, so it is better for dynamic
pages because there might be changes in future.
• The jsp:include tag can be used to include static as well as dynamic
pages.
Following table lists out the attributes associated with the
include action −

S.No. Attribute & Description


1 Page The relative URL of the page to be included.
Flush The boolean attribute determines whether the included resource has its
2
buffer flushed before it is included.
• Syntax of jsp:include action tag without
parameter

– <jsp:include page="relativeURL | <
%= expression %>" />  
• Syntax of jsp:include action tag with parameter

<jsp:include page="relativeURL | <%= expression %>">  
<jsp:param name="parametername" value="parameter
value | <%=expression%>" />  
</jsp:include>  
Example
date.jsp
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
main.jsp
<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:include page = "date.jsp" flush = "true" />
</center>
</body>
</html> The include action Example

Output
Today's date: 12-Sep-2010 14:54:22
Difference between jsp include directive and include action

JSP include directive JSP include action

includes resource at translation includes resource at request time.


time.
better for static pages. better for dynamic pages.
includes the original content in calls the include method.
the generated servlet.
The <jsp:forward> Action
• The forward action terminates the action of the current page and forwards
the request to another resource such as a static page, another JSP page, or a
Java Servlet.
• Following is the syntax of the forward action −

jsp:forward page = "Relative URL" />

Following table lists out the required attributes associated with the forward action −

S.No. Attribute & Description


page
1 Should consist of a relative URL of another resource such as a static page,
another JSP page, or a Java Servlet.
Following is the content of the date.jsp file −
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>

Following is the content of the main.jsp file −


<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center> <h2>The include action Example</h2>
<jsp:forward page = "date.jsp" />
</center>
</body>
</html>
The <jsp:plugin> Action

• The plugin action is used to insert Java components into


a JSP page.
• It determines the type of browser and inserts
the <object> or <embed> tags as needed.
• If the needed plugin is not present, it downloads the
plugin and then executes the Java component.
• The Java component can be either an Applet or a
JavaBean.
• The plugin action has several attributes that correspond
to common HTML tags used to format Java components.
• The <param> element can also be used to send
parameters to the Applet or Bean.
 Typical syntax of using the plugin action

<jsp:plugin type = "applet" codebase = "dirname" code =


"MyApplet.class" width = "60" height = "80">
<jsp:param name = "fontcolor" value = "red" />
<jsp:param name = "background" value = "black" />
<jsp:fallback>
Unable to initialize Java Plugin </jsp:fallback>
</jsp:plugin>
The <jsp:useBean> Action

• The useBean action is quite versatile. It first searches for an


existing object utilizing the id and scope variables. If an object is
not found, it then tries to create the specified object.
The simplest way to load a bean is as follows −
<jsp:useBean id = "name" class = "package.class" />

Once a bean class is loaded, you can


use jsp:setProperty and jsp:getProperty actions to modify and retrieve the bean
properties.


Following table lists out the attributes associated with the useBean action

Attribute & Description


class
Designates the full package name of the bean.
type
Specifies the type of the variable that will refer to the object.
beanName
Gives the name of the bean as specified by the instantiate () method of the
java.beans.Beans class.
 In computing based on the Java Platform,
JavaBeans are classes that encapsulate many
objects into a single object (the bean).
They are serializable, have a zero-argument
constructor, and allow access to properties using
getter and setter methods
The <jsp:setProperty> Action

The setProperty action sets the properties of a Bean. The Bean


must have been previously defined before this action.
There are two basic ways to use the setProperty action −
You can use jsp:setProperty after, but outside of
a jsp:useBean element, as given below −

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


...

<jsp:setProperty name = "myName" property =


"someProperty" .../>
• Following table lists out the attributes associated with
the setProperty action 
S.No. Attribute & Description

name
1 Designates the bean the property of which will be set. The Bean must have been
previously defined.
property
Indicates the property you want to set. A value of "*" means that all request
2 parameters whose names match bean property names will be passed to the
appropriate setter methods.

value
The value that is to be assigned to the given property. The the parameter's value is null,
3 or the parameter does not exist, the setProperty action is ignored.

param
The param attribute is the name of the request parameter whose value the property is
4 to receive. You can't use both value and param, but it is permissible to use neither.
The <jsp:getProperty> Action

• The getProperty action is used to retrieve the value of a given


property and converts it to a string, and finally inserts it into the
output.
• The getProperty action has only two attributes, both of which
are required. The syntax of the getProperty action is as follows −
<jsp:useBean id = "myName" ... /> ... <jsp:getProperty name =
"myName" property = "someProperty" .../>
Following table lists out the required attributes associated with the getProperty action −

Attribute & Description

name
The name of the Bean that has a property to be retrieved. The Bean must have
been previously defined.

property
The property attribute is the name of the Bean property to be retrieved.
Custom Tags in JSP
• 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:
Eliminates the need of scriptlet tag The custom tags eliminates
the need of scriptlet tag which is considered bad programming
approach in JSP.
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.
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>  
• When a JSP page containing a custom tag is
translated into a servlet, the tag is converted
to operations on an object called a tag handler.
The Web container then invokes those
operations when the JSP page's servlet is
executed.
• JSP tag extensions lets you create new tags
that you can insert directly into a JavaServer
Page. 
Create "Hello" Tag
To write a custom tag, you can simply extend SimpleTagSupport class and override
the doTag() method, where you can place your code to generate content for the tag.

Consider you want to define a custom tag named <ex:Hello> and you want to use it
in the following fashion without a body −
<ex:Hello />
To create a custom JSP tag, you must first create a Java class that acts as a tag handler.
Let us now create the HelloTag class as follows −
package com.tutorialspoint;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class HelloTag extends SimpleTagSupport {
public void doTag() throws JspException, IOException
{
JspWriter out = getJspContext().getOut();
out.println("Hello Custom Tag!");
}}
The above code has simple coding where the doTag() method takes the
current JspContext object using the getJspContext() method and uses it to
send "Hello Custom Tag!" to the current JspWriter object
Finally, create the following tag library file: 

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD</short-name>
<tag>
<name>Hello</name>
<tag-class>com.tutorialspoint.HelloTag</tag-class> <body-
content>empty</body-content>
</tag>
</taglib>
Let us now use the above defined custom tag Hello in our JSP
program as follows −
<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%>
<html>
<head>
<title>A sample custom tag</title>
</head> <body> <ex:Hello/> </body> </html>
>
Accessing the Tag Body

You can include a message in the body of the tag as you have seen with standard tags.
Consider you want to define a custom tag named <ex:Hello>and you want to use it in
the following fashion with a body −
<ex:Hello>
This is message body
</ex:Hello

package com.tutorialspoint;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class HelloTag extends SimpleTagSupport {
StringWriter sw = new StringWriter();
public void doTag() throws JspException, IOException
{ getJspBody().invoke(sw);
getJspContext().getOut().println(sw.toString());
}}

Here, the output resulting from the invocation is first captured into
a StringWriter before being written to the JspWriter associated with the tag
We need to change TLD file as follows
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD with Body</short-name>
<tag> <name>Hello</name>
<tag-class>com.tutorialspoint.HelloTag</tag-class>
<body-content>scriptless</body-content>
</tag>
</taglib>
Let us now call the above tag with proper body as follows −
<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%>
<html>
<head>
<title>A sample custom tag</title>
</head>
<body>
<ex:Hello> This is message body </ex:Hello>
</body>
</html>
Custom Tag Attributes
JSP Custom Tag API

The javax.servlet.jsp.tagext package contains classes and interfaces for JSP


custom tag API. The JspTag is the root interface in the Custom Tag
hierarchy.

You might also like