JSP Notes
JSP Notes
1. Servlet use println statements for printing an HTML document which is usually very
difficult to use. JSP has no such tedious task to maintain.
2. JSP needs no compilation, CLASSPATH setting and packaging.
3. In a JSP page visual content and logic are seperated, which is not possible in a servlet.
4. There is automatic deployment of a JSP; recompilation is done automatically when
changes are made to JSP pages.
5. Usually with JSP, Java Beans and custom tags web application is simplified.
1. Active Server Pages (ASP) : ASP is a Microsoft technology. The dynamic part of JSP is
written in Java, so it is more powerful and easier to use. Secondly, JSP is platform
independent whereas ASP is not.
2. Pure Servlets : It is more convenient to write regular HTML than to have println
statements that generate HTML. Allows separation of look from the content. In a JSP
web designer can design web page separately and servlet programmers can insert the
dynamic content separately.
3. Server-Side Includes (SSI) : SSI is widely supported technology for including
externally defined pieces into a static web page. JSP is better because it lets you use
servlets instead of a separate program to generate that dynamic part. Besides, SSI is really
only intended for simple inclusions, not for real programs that use form data, make
database connection.
4. JavaScript: JavaScript can generate HTML dynamically on the client. However, it can
only access client environment. JavaScript can't access server-side resources like
databases, catalogs, pricing information etc.
5. Static HTML: Regular HTML cannot contain dynamic information. JSP is easy and
convenient. It is quite feasible to insert small amounts of dynamic data.
SP Implicit Objects are the Java objects that the JSP Container makes available to developers in
each page and developer can call them directly without being explicitly declared. JSP Implicit
Objects are also called pre-defined variables.
Object Description
request This is the HttpServletRequest object associated with the
request.
response This is the HttpServletResponse object associated with the
response to the client.
out This is the PrintWriter object used to send output to the client.
session This is the HttpSession object associated with the request.
application This is the ServletContext object associated with application
context.
config This is the ServletConfig object associated with the page.
pageContext This encapsulates use of server-specific features like higher
performance JspWriters.
page This is simply a synonym for this, and is used to call the methods
defined by the translated servlet class.
Exception The Exception object allows the exception data to be accessed by
designated JSP.
The request object provides methods to get HTTP header information including form
data, cookies, HTTP methods etc.
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.
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 are the important methods which we would use to write boolean char, int,
double, object, String etc.
Method Description
out.print(dataType dt) Print a data type value
Print a data type value then terminate the line with new
out.println(dataType dt)
line character.
out.flush() Flush the stream.
The session object is used to track client session between client requests.
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.
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
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.
One of the important methods is removeAttribute, which 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);
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 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.
JSP tags are an important syntax element of Java Server Pages which start with "<%" and end
with "%>" just like HTML tags. JSP tags normally have a "start tag", a "tag body" and an "end
tag". JSP tags can either be predefined tags or loaded from an external tag library.
Fundamental tags used in Java Server Pages are classified into the following categories:-
• Declaration tag
• Expression tag
• Directive tag
• Scriptlet tag
• Comments
Declaration tag
The declaration tag is used within a Java Server page to declare a variable or method that can be
referenced by other declarations, scriptlets, or expressions in a java server page. A declaration
tag does not generate any output on its own and is usually used in association with Expression or
Scriplet Tags.
Declaration tag starts with "<%!" and ends with "%>" surrounding the declaration.
Expression tag
An expression tag is used within a Java Server page to evaluate a java expression at request time.
The expression enclosed between "<%=" and "%>" tag elements is first converted into a string
and sent inline to the output stream of the response.
Directive tag
Directive tag is used within a Java Server page to specify directives to the application server .
The directives are special messages which may use name-value pair attributes in the form
attr="value".
3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined
our own tags).
Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>
Scriptlet tag
A Scriptlet tag is used within a Java Server page to execute a java source code scriplet which is
enclosed between "<%" and "%>" tag elements. The output of the java source code scriplet
specified within the Scriptlet tag is executed at the server end and is inserted in sequence with
rest of the web document for the client to access through web browser.
Comments
Comments tag is used within a Java Server page for documentation of Java server page code.
Comments surrounded with "<%/*" and "*/%" tag elements are not processed by JSP engine and
therefore do not appear on the client side web document but can be viewed through the web
browser’s "view source" option.
The JSP action tag is used to transfer the control between pages and is also used to enable the use
of server side JavaBeans. It is not good idea to write the java code inside JSP page, to come over
JSP comes with predefined actions tags which can be used to either link to a Java Bean set its
properties, or get its properties.
The JSP actions provide an abstraction that can be used to easily encapsulate common tasks. The
JSP actions are specific tags that affect the runtime of the JSP and the response sent back to the
client. The JSP actions normally create or act on objects.
• <jsp:include>
• <jsp:forward>
• <jsp:param>
• <jsp:useBean>
• <jsp:setProperty>
• <jsp:getProperty>
The JSP include action tag used to include a static file or send a request to a dynamic file.
The JSP forward action used to forward a client request to an HTML file, JSP file, or servlet for
processing.
The JSP param action used to pass the request parameter to destination page, while including or
forwarding using include or forward action tag.
The JSP useBean used to instantiates a java bean with a specific name and scope.
The JSP action setProperty action use to sets a property value or values in a bean.
The JSP getProperty action use to get the value of a bean property so that you can display it in a
result page.
JSTL
The Java Server Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which
encapsulates core functionality common to many JSP applications.
JSTL has support for common, structural tasks such as iteration and conditionals, tags for
manipulating XML documents, internationalization tags, and SQL tags. It also provides a
framework for integrating existing custom tags with JSTL tags.
The JSTL tags can be classified, according to their functions, into following JSTL tag library
groups that can be used when creating a JSP page:
• Core Tags
• Formatting tags
• SQL tags
• XML tags
Core Tags
The core group of tags are the most frequently used JSTL tags. Following is the syntax to include
JSTL Core library in your JSP:
• General-Purpose tags
• Control and looping tags
• Network tags
General-purpose tags
c: out
The <c:out> tag displays the result of an expression, similar to the way <%= %> works with a
difference that <c:out> tag lets you use the simpler "." notation to access properties. For
example, to access customer.address.street just use tag is <c:out
value="customer.address.street"/>.
The <c:out> tag can automatically escape XML tags so they aren't evaluated as actual tags.
Attribute:
Example:
sample
c: set
The <c:set> tag is JSTL-friendly version of the setProperty action. The tag is helpful because it
evaluates an expression and uses the results to set a value of a JavaBean or a java.util.Map
object.
Attribute:
Example:
4000
c: catch
The <c:catch> tag catches any Throwable that occurs in its body and optionally exposes it.
Simply it is used for error handling and to deal more gracefully with the problem.
Attribute:
Example:
</body>
</html>
c: remove
The <c:remove> tag removes a variable from either a specified scope or the first scope where the
variable is found (if no scope is specified). This action is not normally particularly helpful, but it
can aid in ensuring that a JSP cleans up any scoped resources it is responsible for.
Example:
c: if
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<head><title>Using the Core JSTL tags</title></head>
<body>
<h2>Here are the available Time Zone IDs on your system</h2>
<jsp:useBean id="zone" class="ZoneWrapper" />
<jsp:useBean id="date" class="java.util.Date" />
<c:out value="Phew, time has not stopped yet...<br /><br />" escapeXml="f
alse" />
</c:if>
</c:forEach>
</body>
</html>
import java.util.TimeZone;
public ZoneWrapper() {
}
return TimeZone.getAvailableIDs();
c: choose
The <c:choose> works like a Java switch statement in that it lets you choose between a number
of alternatives. Where the switch statement has case statements, the <c:choose> tag has
<c:when> tags. A a switch statement has default clause to specify a default action and similar
way <c:choose> has <c:otherwise> as default clause.
Attribute:
Example:
c: forEach
These tags exist as a good alternative to embedding a Java for, while, or do-while loop via a
scriptlet. The <c:forEach> tag is the more commonly used tag because it iterates over a
collection of objects. The <c:forTokens> tag is used to break a string into tokens and iterate
through each of the tokens.
Attribute:
The <c:forTokens> tag has similar attributes as <c:forEach> except one additional attribute
delims which specifies sharacters to use as delimiters.
Item 1
Item 2
Item 3
Item 4
Item 5
c: forTokens
Zara
nuha
roshy
Network tags
c: import
The <c:import> tag provides all of the functionality of the <include> action but also allows for
inclusion of absolute URLs.
For example, using the import tag allows for inclusion of content from a different Web site or an
FTP server.
Attribute:
Example:
Above example would fetch complete content from tutorialspoint.com/index.htm and would
store in variable data which will be printed eventually.
c: redirect
The <c:redirect> tag redirects the browser to an alternate URL by providing automatically URL
rewriting, it supports context-relative URLs, and it supports the <c:param> tag.
Attribute:
Example:
If you need to pass parameters to a <c:import> tag, use the <c:url> tag to create the URL first as
shown below:
c: url
The <c:url> tag formats a URL into a string and stores it into a variable. This tag automatically
performs URL rewriting when necessary. The var attribute specifies the variable that will contain
the formatted URL.
The JSTL url tag is just an alternative method of writing the call to the response.encodeURL()
method. The only real advantage the url tag provides is proper URL encoding, including any
parameters specified by children param tag.
Attribute:
Example:
TEST
Formatting tags
The JSTL formatting tags are used to format and display text, the date, the time, and numbers for
internationalized Web sites. Following is the syntax to include Formatting library in your JSP:
Tag Description
<fmt:formatNumber> To render numerical value with specific precision or format.
Parses the string representation of a number, currency, or
<fmt:parseNumber>
percentage.
<fmt:formatDate> Formats a date and/or time using the supplied styles and pattern
<fmt:parseDate> Parses the string representation of a date and/or time
<fmt:bundle> Loads a resource bundle to be used by its tag body.
<fmt:setLocale> Stores the given locale in the locale configuration variable.
Loads a resource bundle and stores it in the named scoped variable
<fmt:setBundle>
or the bundle configuration variable.
Specifies the time zone for any time formatting or parsing actions
<fmt:timeZone>
nested in its body.
<fmt:setTimeZone> Stores the given time zone in the time zone configuration variable
<fmt:message> To display an internationalized message.
<fmt:requestEncoding> Sets the request character encoding
SQL tags
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs)
such as Oracle, mySQL, or Microsoft SQL Server.
Tag Description
<sql:setDataSource> Creates a simple DataSource suitable only for prototyping
Executes the SQL query defined in its body or through the sql
<sql:query>
attribute.
Executes the SQL update defined in its body or through the sql
<sql:update>
attribute.
<sql:param> Sets a parameter in an SQL statement to the specified value.
Sets a parameter in an SQL statement to the specified java.util.Date
<sql:dateParam>
value.
Provides nested database action elements with a shared
<sql:transaction >
Connection, set up to execute all statements as one transaction.
XML tags
The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents.
Following is the syntax to include JSTL XML library in your JSP.
The JSTL XML tag library has custom tags for interacting with XML data. This includes parsing
XML, transforming XML data, and flow control based on XPath expressions.
Tag Description
<x:out> Like <%= ... >, but for XPath expressions.
Use to parse XML data specified either via an attribute or in the tag
<x:parse>
body.
<x:set > Sets a variable to the value of an XPath expression.
Evaluates a test XPath expression and if it is true, it processes its
<x:if >
body. If the test condition is false, the body is ignored.
<x:forEach> To loop over nodes in an XML document.
Simple conditional tag that establishes a context for mutually
<x:choose> exclusive conditional operations, marked by <when> and
<otherwise>
Subtag of <choose> that includes its body if its expression evalutes
<x:when >
to 'true'
Subtag of <choose> that follows <when> tags and runs only if all
<x:otherwise >
of the prior conditions evaluated to 'false'
<x:transform > Applies an XSL transformation on a XML document
Use along with the transform tag to set a parameter in the XSLT
<x:param >
stylesheet
JSP tag extensions let you create new tags that you can insert directly into a JavaServer Page just
as you would the built-in tags you learned about in earlier chapter. The JSP 2.0 specification
introduced Simple Tag Handlers for writing these custom tags.
To write a customer tab 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:rnsit> and you want to use it in the
following fashion without a body:
<ex:rnsit />
To create a custom JSP tag, you must first create a Java class that acts as a tag handler. So let us
create CollegeTag class as follows:
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
Above code has simple coding where doTag() method takes the current JspContext object using
getJspContext() method and uses it to send " RNS Institute of Technology " to the current
JspWriter object.
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD</short-name>
<tag>
<name>rnsit</name>
<tag-class> CollegeTag </tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
Now it's time to use above defined custom tag <rnsit/> in our JSP program as follows:
Try to call above JSP and this should produce following result:
<ex:Hello>
This is message body
</ex:Hello>
Let us make following changes in above our tag code to process the body of the tag:
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
In this case, the output resulting from the invocation is first captured into a StringWriter before
being written to the JspWriter associated with the tag. Now accordingly 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> HelloTag</tag-class>
<body-content>scriptless</body-content>
</tag>
</taglib>
Property Purpose
The name element defines the name of an attribute. Each attribute
name
name must be unique for a particular tag.
This specifies if this attribute is required or optional. It would be
required
false for optional.
rtexprvalue Declares if a runtime expression value for a tag attribute is valid
Defines the Java class-type of this attribute. By default it is
type
assumed as String
description Informational description can be provided.
fragment Declares if this attribute value should be treated as a JspFragment.
To accept an attribute value, a custom tag class needs to implement setter methods, identical to
JavaBean setter methods as shown below:
package jsp;
import java.io.IOException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
}
return SKIP_BODY;
}
}
return SKIP_PAGE;
}
}
new_lib.tld
<taglib >
<tlib-version>1.0</tlib-version>
<short-name>new_lib</short-name>
<uri>/WEB-INF/tlds/new_lib</uri>
<tag>
<name>enumber</name>
<tag-class>jsp.lab11</tag-class>
<attribute>
<name>msg</name>
<required>true</required>
</attribute>
<attribute>
<name>start</name>
<required>true</required>
</attribute>
<attribute>
<name>end</name>
<required>true</required>
</attribute>
</tag>
</taglib>
index.jsp
<!DOCTYPE html>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
</body>
</html>
Output
Nested Tags
JSP program to implement nested tags using TagSupport class
ParentTagHandler.java
package tag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
return EVAL_BODY_INCLUDE;
return sports;
this.sports = sport;
ChildTagHandler.java
package tag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
if (getSports( ).equals(parentTag.getSports()))
return EVAL_BODY_INCLUDE;
return SKIP_BODY;
this.parent = parent;
return sports;
this.sports = sports;
nested.tld
<taglib >
<tlib-version>1.0</tlib-version>
<short-name>nested</short-name>
<uri>/WEB-INF/tlds/nested</uri>
<tag>
<name>parent</name>
<tagclass>tag.ParentTagHandler</tagclass>
<bodycontent>scriptless</bodycontent>
<attribute>
<name>sports</name>
<required>true</required>
</attribute>
</tag>
<tag>
<name>child</name>
<tagclass>tag.ChildTagHandler</tagclass>
<bodycontent>scriptless</bodycontent>
<attribute>
<name>sports</name>
<required>true</required>
</attribute>
</tag>
</taglib>
index.jsp
<!DOCTYPE html>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<custom:parent sports="Cricket">
</custom:parent >
</body>
</html>
Output:
JSP program to get student information through a html and create a java bean class,
populate bean and display the same information through another jsp.
student.html
<html>
<head>
<title>Student Info</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<center><br/><br/>
<form action="index.jsp" method="post">
Enter Name: <input type="text" name="sname"/><br/>
Enter USN : <input type="text" name="usnno"/><br/>
Enter Branch: <input type="text" name="branch"/><br/><br/>
<input type="submit" value="submit"/>
</form>
</center>
</body>
</html>
index.jsp
<!DOCTYPE html>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
</body>
</html>
view.jsp
<!DOCTYPE html>
<html>
<head>
<title>Student Page</title>
</head>
<body>
Branch: <%out.print(stu.getbranch());%>
</center>
</body>
</html>
Student.java
package jsp;
sname=s;
return sname;
usnno=u;
return usnno;
branch=b;
return branch;
Input:
Output: