What Is Javaserver Pages?: vs. Active Server Pages (Asp)
What Is Javaserver Pages?: vs. Active Server Pages (Asp)
Using JSP, you can collect input from users through Webpage forms,
present records from a database or another source, and create Webpages
dynamically.
Advantages of JSP
Following table lists out the other advantages of using JSP over other
technologies −
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 Architecture:
The web server needs a JSP engine, i.e, a container to process JSP pages.
The JSP container is responsible for intercepting requests for JSP pages.
This tutorial makes use of Apache which has built-in JSP container to
support JSP pages development.
A JSP container works with the Web server to provide the runtime
environment and other services a JSP needs. It knows how to understand
the special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a
Web application.
JSP Processing
The following steps explain how the web server creates the Webpage using
JSP −
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards
it to a JSP engine. This is done by using the URL or JSP page which ends
with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet
content. This conversion is very simple in which all template text is converted to
println( ) statements and all JSP elements are converted to Java code. This code
implements the corresponding dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the
original request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and
executes it. During execution, the servlet produces an output in HTML format.
The output is furthur passed on to the web server by the servlet engine inside
an HTTP response.
The web server forwards the HTTP response to your browser in terms of static
HTML content.
Finally, the web browser handles the dynamically-generated HTML page inside
the HTTP response exactly as if it were a static page.
All the above mentioned steps can be seen in the following diagram −
Typically, the JSP engine checks to see whether a servlet for a JSP file
already exists and whether the modification date on the JSP is older than
the servlet. If the JSP is older than its generated servlet, the JSP container
assumes that the JSP hasn't changed and that the generated servlet still
matches the JSP's contents. This makes the process more efficient than
with the other scripting languages (such as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without
having to be a Java programming wiz. Except for the translation phase, a
JSP page is handled exactly like a regular servlet.
There is only one syntax for the Action element, as it conforms to the XML
standard −
Action elements are basically predefined functions. The following table lists
out the available JSP actions −
jsp:include
1
Includes a file at the time the page is requested.
jsp:useBean
2
Finds or instantiates a JavaBean.
jsp:setProperty
3
Sets the property of a JavaBean.
jsp:getProperty
4
Inserts the property of a JavaBean into the output.
5 jsp:forward
Forwards the requester to a new page.
jsp:plugin
jsp:element
7
Defines XML elements dynamically.
jsp:attribute
8
Defines dynamically-defined XML element's attribute.
jsp:body
9
Defines dynamically-defined XML element's body.
jsp:text
10
Used to write template text in JSP pages and documents.
Common Attributes
There are two attributes that are common to all Action elements:
the idattribute 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.
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.
Following table lists out the attributes associated with the include action −
page
1
The relative URL of the page to be included.
flush
2 The boolean attribute determines whether the included resource has its
buffer flushed before it is included.
Example
Let us define the following two files (a)date.jsp and (b) main.jsp as
follows −
<html>
<head>
</head>
<body>
<center>
</body>
</html>
Let us now keep all these files in the root directory and try to
access main.jsp. You will receive the following output −
Following table lists out the attributes associated with the useBean action −
class
1
Designates the full package name of the bean.
type
2
Specifies the type of the variable that will refer to the object.
beanName
3
Gives the name of the bean as specified by the instantiate () method of
the java.beans.Beans class.
...
</jsp:useBean>
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
2
request parameters whose names match bean property names will be
passed to the appropriate setter methods.
value
param
The param attribute is the name of the request parameter whose value
4
the property is to receive. You can't use both value and param, but it is
permissible to use neither.
The getProperty action has only two attributes, both of which are required.
The syntax of the getProperty action is as follows −
...
name
1
The name of the Bean that has a property to be retrieved. The Bean
must have been previously defined.
2 property
The property attribute is the name of the Bean property to be retrieved.
Example
Let us define a test bean that will further be used in our example −
/* File: TestBean.java */
package action;
return(message);
this.message = message;
Compile the above code to the generated TestBean.class file and make
sure that you copied the TestBean.class in C:\apache-tomcat-
7.0.2\webapps\WEB-INF\classes\action folder and
the CLASSPATHvariable should also be set to this folder −
Now use the following code in main.jsp file. This loads the bean and
sets/gets a simple String parameter −
<html>
<head>
</head>
<body>
<center>
<p>Got message....</p>
</center>
</body>
</html>
Let us now try to access main.jsp, it would display the following result −
Got message....
Hello JSP...
Following table lists out the required attributes associated with the forward
action −
1 page
Should consist of a relative URL of another resource such as a static
page, another JSP page, or a Java Servlet.
Example
Let us reuse the following two files (a) date.jsp and (b) main.jsp as
follows −
<html>
<head>
</head>
<body>
<center>
</center>
</body>
</html>
Let us now keep all these files in the root directory and try to
access main.jsp. This would display result something like as below.
Here it discarded the content from the main page and displayed the content
from forwarded page only.
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.
<jsp:fallback>
</jsp:fallback>
</jsp:plugin>
You can try this action using some applet if you are interested. A new
element, the <fallback> element, can be used to specify an error string to
be sent to the user in case the component fails.
xmlns:jsp = "http://java.sun.com/JSP/Page">
<body>
</jsp:attribute>
<jsp:body>
</jsp:body>
</jsp:element>
</body>
</html>
<body>
<xmlElement xmlElementAttr = "Value for the attribute">
</xmlElement>
</body>
</html>
<jsp:text>Template data</jsp:text>
The body of the template cannot contain other elements; it can only contain
text and EL expressions (Note − EL expressions are explained in a
subsequent chapter). Note that in XML files, you cannot use expressions
such as${whatever > 0}, because the greater than signs are illegal.
Instead, use thegt form, such as ${whatever gt 0} or an alternative is to
embed the value in a CDATA section.
<jsp:text><![CDATA[<br>]]></jsp:text>
If you need to include a DOCTYPE declaration, for instance for XHTML, you
must also use the <jsp:text> element as follows −
"DTD/xhtml1-strict.dtd">]]></jsp:text>
<head><title>jsp:text action</title></head>
<body>
<books><book><jsp:text>
</jsp:text></book></books>
</body>
</html>
A JSP directive affects the overall structure of the servlet class. It usually
has the following form −
Directives can have a number of attributes which you can list down as key-
value pairs and separated by commas.
The blanks between the @ symbol and the directive name, and between the
last attribute and the closing %>, are optional.
Attributes
Following table lists out the attributes associated with the page directive −
buffer
1
Specifies a buffering model for the output stream.
autoFlush
2
Controls the behavior of the servlet output buffer.
contentType
3
Defines the character encoding scheme.
errorPage
4 Defines the URL of another JSP that reports on Java unchecked runtime
exceptions.
isErrorPage
extends
6
Specifies a superclass that the generated servlet must extend.
import
7 Specifies a list of packages or classes for use in the JSP as the Java
import statement does for Java classes.
info
8
Defines a string that can be accessed with the
servlet'sgetServletInfo() method.
isThreadSafe
9
Defines the threading model for the generated servlet.
language
10
Defines the programming language used in the JSP page.
session
11
Specifies whether or not the JSP page participates in HTTP sessions
isELIgnored
12 Specifies whether or not the EL expression within the JSP page will be
ignored.
isScriptingEnabled
13
Determines if the scripting elements are allowed for use.
Check for more details related to all the above attributes at Page Directive.
The filename in the include directive is actually a relative URL. If you just
specify a filename with no associated path, the JSP compiler assumes that
the file is in the same directory as your JSP.
You can write the XML equivalent of the above syntax as follows −
For more details related to include directive, check the Include Directive.
The taglib Directive
The JavaServer Pages API allow you to define custom JSP tags that look like
HTML or XML tags and a tag library is a set of user-defined tags that
implement custom behavior.
The taglib directive declares that your JSP page uses a set of custom tags,
identifies the location of the library, and provides means for identifying the
custom tags in your JSP page.
You can write the XML equivalent of the above syntax as follows −
For more details related to the taglib directive, check the Taglib Directive
Custom tag :
In this chapter, we will discuss the Custom Tags in JSP. A custom tag is a
user-defined JSP language element. 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. The JSP 2.0 specification introduced the Simple Tag
Handlers for writing these custom tags.
To use any of the libraries, you must include a <taglib> directive at the top
of each JSP that uses the library.
Core Tags
Formatting tags
SQL tags
XML tags
JSTL Functions
Core Tags
The core group of tags are the most commonly used JSTL tags. Following is
the syntax to include the JSTL Core library in your JSP −
<c:set >
2 Sets the result of an expression evaluation in a 'scope'
<c:remove >
3
Removes a scoped variable (from a particular scope, if specified).
<c:catch>
4 Catches any Throwable that occurs in its body and optionally exposes
it.
<c:if>
5 Simple conditional tag which evalutes its body if the supplied condition
is true.
<c:choose>
<c:when>
<c:otherwise >
8 Subtag of <choose> that follows the <when> tags and runs only if all
of the prior conditions evaluated to 'false'.
<c:import>
<c:forEach >
10 The basic iteration tag, accepting many different collection types and
supporting subsetting and other functionality .
<c:forTokens>
11
Iterates over tokens, separated by the supplied delimeters.
<c:param>
12
Adds a parameter to a containing 'import' tag's URL.
<c:redirect >
13 Redirects to a new URL.
<c:url>
14
Creates a URL with optional query parameters
Formatting Tags
The JSTL formatting tags are used to format and display text, the date, the
time, and numbers for internationalized Websites. Following is the syntax to
include Formatting library in your JSP −
<fmt:formatNumber>
1
To render numerical value with specific precision or format.
<fmt:parseNumber>
2
Parses the string representation of a number, currency, or percentage.
<fmt:formatDate>
3
Formats a date and/or time using the supplied styles and pattern.
<fmt:parseDate>
4 Parses the string representation of a date and/or time
<fmt:bundle>
5
Loads a resource bundle to be used by its tag body.
<fmt:setLocale>
6
Stores the given locale in the locale configuration variable.
<fmt:setBundle>
7
Loads a resource bundle and stores it in the named scoped variable or
the bundle configuration variable.
<fmt:timeZone>
8 Specifies the time zone for any time formatting or parsing actions
nested in its body.
<fmt:setTimeZone>
9 Stores the given time zone in the time zone configuration variable
<fmt:message>
10 Displays an internationalized message.
<fmt:requestEncoding>
11
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.
<sql:setDataSource>
1
Creates a simple DataSource suitable only for prototyping
<sql:query>
2 Executes the SQL query defined in its body or through the sql attribute.
<sql:update>
3
Executes the SQL update defined in its body or through the sql attribute.
<sql:param>
4
Sets a parameter in an SQL statement to the specified value.
5 <sql:dateParam>
Sets a parameter in an SQL statement to the specified java.util.Date
value.
<sql:transaction >
XML tags
The JSTL XML tags provide a JSP-centric way of creating and manipulating
the XML documents. Following is the syntax to include the JSTL XML library
in your JSP.
The JSTL XML tag library has custom tags for interacting with the XML data.
This includes parsing the XML, transforming the XML data, and the flow
control based on the XPath expressions.
Before you proceed with the examples, you will need to copy the following
two XML and XPath related libraries into your <Tomcat Installation
Directory>\lib−
<x:out>
1
Like <%= ... >, but for XPath expressions.
<x:parse>
2 Used to parse the XML data specified either via an attribute or in the tag
body.
<x:set >
3 Sets a variable to the value of an XPath expression.
<x:if >
<x:forEach>
5 To loop over nodes in an XML document.
<x:choose>
<x:when >
<x:otherwise >
8 Subtag of <choose> that follows the <when> tags and runs only if all
of the prior conditions evaluates to 'false'.
<x:transform >
9
Applies an XSL transformation on a XML document
<x:param >
10 Used along with the transform tag to set a parameter in the XSLT
stylesheet
JSTL Functions
JSTL includes a number of standard functions, most of which are common
string manipulation functions. Following is the syntax to include JSTL
Functions library in your JSP −
1 fn:contains()
Tests if an input string contains the specified substring.
fn:containsIgnoreCase()
fn:endsWith()
3 Tests if an input string ends with the specified suffix.
fn:escapeXml()
4 Escapes characters that can be interpreted as XML markup.
fn:indexOf()
fn:join()
6 Joins all elements of an array into a string.
fn:length()
fn:replace()
fn:split()
9 Splits a string into an array of substrings.
fn:startsWith()
10
Tests if an input string starts with the specified prefix.
fn:substring()
11 Returns a subset of a string.
fn:substringAfter()
12
Returns a subset of a string following a specific substring.
13 fn:substringBefore()
Returns a subset of a string before a specific substring.
fn:toLowerCase()
14
Converts all of the characters of a string to lower case.
fn:toUpperCase()
15 Converts all of the characters of a string to upper case.
fn:trim()
16 Removes white spaces from both ends of a string.
JspTag interface
The JspTag is the root interface for all the interfaces and classes used in custom tag. It is a
marker interface.
Tag interface
The 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:
public static int EVAL_PAGE it evaluates the JSP page content after the custom
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.
public int doStartTag()throws it is invoked by the JSP page implementation object. The JSP
JspException programmer should override this method and define the busi
to be performed at the start of the tag.
public int doEndTag()throws it is invoked by the JSP page implementation object. The JSP
JspException programmer should override this method and define the busi
to be performed at the end of the tag.
public void release() it is invoked by the JSP page implementation object to releas
state.
IterationTag interface
The IterationTag interface is the sub interface of the Tag interface. It provides an additional
method to reevaluate the body.
Example:
In the below example we are creating a custom tag MyMsg which will display the
message “This is my own custom tag” when used in a JSP page.
package beginnersbook.com;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class Details extends SimpleTagSupport {
public void doTag() throws JspException, IOException {
/*This is just to display a message, when
* we will use our custom tag. This message
* would be displayed
*/
JspWriter out = getJspContext().getOut();
out.println("This is my own custom tag");
}
}
TLD File
This file should present at the location: Project Name/WebContent/WEB-INF/ and it
should have a.tld extension.
Note:
<name> tag: custom tag name. In this example we have given it as MyMsg
<tag-class> tag: Fully qualified class name. Our tag handler class Details.java is in
packagebeginnersbook.com so we have given the value as beginnersbook.com.Details.
message.tld
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>My Custom Tag</short-name>
<tag>
<name>MyMsg</name>
<tag-class>beginnersbook.com.Details</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
Output: