What Is Javaserver Pages?: vs. Active Server Pages (Asp)
What Is Javaserver Pages?: vs. Active Server Pages (Asp)
What Is Javaserver Pages?: vs. Active Server Pages (Asp)
JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic content. This helps
developers insert java code in HTML pages by making use of special JSP tags, most of which start with <%
and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a user interface
for a Java web application. Web developers write JSPs as text files that combine HTML or XHTML code,
XML elements, and embedded JSP actions and commands.
Using JSP, you can collect input from users through Webpage forms, present records from a database or
another source, and create Webpages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering
user preferences, accessing JavaBeans components, passing control between pages, and sharing information
between requests, pages etc.
Performance is significantly better because JSP allows embedding Dynamic Elements in HTML
Pages itself instead of having separate CGI files.
JSP are always compiled before they are processed by the server unlike CGI/Perl which requires the
server to load an interpreter and the target script each time the page is requested.
JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all
the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.
JSP pages can be used in combination with servlets that handle the business logic, the model
supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications. This means
that JSP can play a part in the simplest applications to the most complex and demanding.
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.
This tutorial will guide you to setup your JSP development environment
which involves the following steps −
You can download SDK from Oracle's Java site − Java SE Downloads.
Once you download your Java implementation, follow the given instructions
to install and configure the setup. Finally set the PATH and
JAVA_HOMEenvironment variables to refer to the directory that
contains java and javac,
typically java_install_dir/bin and java_install_dir respectively.
If you are running Windows and install the SDK in C:\jdk1.5.0_20, you
need to add the following line in your C:\autoexec.bat file.
set PATH = C:\jdk1.5.0_20\bin;%PATH%
set JAVA_HOME = C:\jdk1.5.0_20
Once you downloaded the installation, unpack the binary distribution into a
convenient location. For example, in C:\apache-tomcat-5.5.29 on windows,
or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and
create CATALINA_HOME environment variable pointing to these locations.
%CATALINA_HOME%\bin\startup.bat
or
C:\apache-tomcat-5.5.29\bin\startup.bat
$CATALINA_HOME/bin/startup.sh
/usr/local/apache-tomcat-5.5.29/bin/startup.sh
%CATALINA_HOME%\bin\shutdown
or
C:\apache-tomcat-5.5.29\bin\shutdown
$CATALINA_HOME/bin/shutdown.sh
/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
Setting up CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must
identify the servlet classes to the compiler.
If you are running Windows, you need to put the following lines in
your C:\autoexec.bat file.
set CATALINA = C:\apache-tomcat-5.5.29
set CLASSPATH = %CATALINA%\common\lib\jsp-api.jar;%CLASSPATH%
On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put
the following lines into your .cshrc file.
setenv CATALINA = /usr/local/apache-tomcat-5.5.29
setenv CLASSPATH $CATALINA/common/lib/jsp-api.jar:$CLASSPATH
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.
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 −
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.
JSP - Lifecycle
In this chapter, we will discuss the lifecycle of JSP. The key to understanding
the low-level functionality of JSP is to understand the simple life cycle they
follow.
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.
Compilation
Initialization
Execution
Cleanup
The four major phases of a JSP life cycle are very similar to the Servlet Life
Cycle. The four phases have been described below −
7 Recreated from Original Source: https://www.tutorialspoint.com/, Students can directly
visit the original source (free online tutorial on JSP and other Programming Languages)
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.
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 −
// 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.
Whenever a browser requests a JSP and the page has been loaded and
initialized, the JSP engine invokes the _jspService() method in the JSP.
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.
JSP - Syntax
In this chapter, we will discuss Syntax in JSP. We will understand the basic use of simple syntax
(i.e, elements) involved with JSP development.
Elements of JSP
The elements of JSP have been described below −
The Scriptlet
You can write the XML equivalent of the above syntax as follows −
<jsp:scriptlet>
code fragment
</jsp:scriptlet>
Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the
simple and first example for JSP −
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
%>
</body>
</html>
Let us keep the above code in JSP file hello.jsp and put this file in C:\apache-
tomcat7.0.2\webapps\ROOT directory. Browse through the same using
URL http://localhost:8080/hello.jsp. The above code will generate the following result −
JSP Declarations
You can write the XML equivalent of the above syntax as follows −
<jsp:declaration>
code fragment
</jsp:declaration>
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.
You can write the XML equivalent of the above syntax as follows −
<jsp:expression>
expression
</jsp:expression>
<html>
<body>
</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.
<html>
<body>
<%-- This comment will not be visible in the page source --%>
</body>
</html>
A Test of Comments
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 −
%\>
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.
JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually has the following form −
JSP Actions
JSP 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.
Action elements are basically predefined functions. Following table lists out the available JSP
Actions −
1 jsp:include
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.
jsp:forward
5
Forwards the requester to a new page.
jsp:plugin
6
Generates browser-specific code that makes an OBJECT or EMBED tag for the
Java plugin.
jsp:element
7
Defines XML elements dynamically.
jsp:attribute
8
Defines dynamically-defined XML element's attribute.
9 jsp:body
jsp:text
10
Used to write template text in JSP pages and documents.
1 request
response
2
This is the HttpServletResponse object associated with the response to the
client.
out
3
This is the PrintWriter object used to send output to the client.
session
4
This is the HttpSession object associated with the request.
application
5
This is the ServletContext object associated with the application context.
config
6
This is the ServletConfig object associated with the page.
pageContext
7
This encapsulates use of server-specific features like higher
performance JspWriters.
Exception
9
The Exception object allows the exception data to be accessed by designated JSP.
Control-Flow Statements
You can use all the APIs and building blocks of Java in your JSP programming including decision-
making statements, loops, etc.
Decision-Making Statements
The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line with
HTML text included between the Scriptlet tags.
<html>
<head><title>IF...ELSE Example</title></head>
<body>
<% } %>
</body>
</html>
Now look at the following switch...case block which has been written a bit differentlty
using out.println() and inside Scriptletas −
<head><title>SWITCH...CASE Example</title></head>
<body>
<%
switch(day) {
case 0:
out.println("It\'s Sunday.");
break;
case 1:
out.println("It\'s Monday.");
break;
case 2:
out.println("It\'s Tuesday.");
break;
case 3:
out.println("It\'s Wednesday.");
break;
case 4:
out.println("It\'s Thursday.");
break;
case 5:
out.println("It\'s Friday.");
break;
default:
out.println("It's Saturday.");
%>
</body>
</html>
It's Wednesday.
Loop Statements
You can also use three basic types of looping blocks in Java: for, while, and do…while blocks in
your JSP programming.
<html>
<body>
JSP Tutorial
</font><br />
<%}%>
</body>
</html>
JSP Tutorial
JSP Tutorial
JSP Tutorial
<body>
JSP Tutorial
</font><br />
<%fontSize++;%>
<%}%>
</body>
</html>
JSP Tutorial
JSP Tutorial
JSP Tutorial
JSP Operators
JSP supports all the logical and arithmetic operators supported by Java. Following table lists out all
the operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom.
JSP Literals
The JSP expression language defines the following literals −
Integer − as in Java
String − with single and double quotes; " is escaped as \", ' is escaped as \', and \ is
escaped as \\.
Null − null
JSP - Directives
In this chapter, we will discuss Directives in JSP. These directives provide directions
and instructions to the container, telling it how to handle certain aspects of the JSP
processing.
A JSP directive affects the overall structure of the servlet class. It usually
has the following form −
<%@ directive attribute = "value" %>
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.
You can write the XML equivalent of the above syntax as follows −
<jsp:directive.page attribute = "value" />
Attributes
Following table lists out the attributes associated with the page directive −
1 buffer
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
5
Indicates if this JSP page is a URL specified by another JSP page's
errorPage attribute.
extends
6
Specifies a superclass that the generated servlet must extend.
7 import
Specifies a list of packages or classes for use in the JSP as the Java
info
8
Defines a string that can be accessed with the
servlet's getServletInfo() 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 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 −
<jsp:directive.taglib uri = "uri" prefix = "prefixOfTag" />
For more details related to the taglib directive, check the Taglib Directive.
JSP - Actions
In this chapter, we will discuss Actions in JSP. 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. The following table lists
out the available JSP actions −
1 jsp:include
jsp:setProperty
3
Sets the property of a JavaBean.
jsp:getProperty
4
Inserts the property of a JavaBean into the output.
jsp:forward
5
Forwards the requester to a new page.
jsp:plugin
6
Generates browser-specific code that makes an OBJECT or EMBED tag for
the Java 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
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 −
1 page
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 −
<head>
</head>
<body>
<center>
</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 −
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
2 Indicates the property you want to set. A value of "*" means that all
request parameters whose names match bean property names will be
passed to the appropriate setter methods.
value
param
4 The param attribute is the name of the request parameter whose value
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 −
...
property
2
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>
<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 −
page
1
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>
</body>
</html>
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 the gt 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>
Following table lists out the nine Implicit Objects that JSP supports −
1 request
response
2
This is the HttpServletResponse object associated with the response
to the client.
out
3
This is the PrintWriter object used to send output to the client.
session
4
This is the HttpSession object associated with the request.
application
5
This is the ServletContext object associated with the application
context.
config
6
This is the ServletConfig object associated with the page.
pageContext
7
This encapsulates use of server-specific features like higher
performance JspWriters.
8 page
Exception
9
The Exception object allows the exception data to be accessed by
designated JSP.
The request object provides methods to get the HTTP header information
including form data, cookies, HTTP methods etc.
We can cover a complete set of methods associated with the request object
in a subsequent chapter − JSP - Client Request.
The response object 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.
Following table lists out the important methods that we will use to
write boolean char, int, double, object, String, etc.
out.print(dataType dt)
1
Print a data type value
out.println(dataType dt)
2
Print a data type value then terminate the line with new line character.
out.flush()
3
Flush the stream.
The session object is used to track client session between client requests.
We will cover the complete usage of session object in a subsequent chapter
− JSP - Session Tracking.
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 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 page object is really a direct synonym for the this object.
Following table lists out the important header information which comes from the browser. This
information is frequently used in web programming −
Accept
1 This header specifies the MIME types that the browser or other clients can
handle. Values of image/png or image/jpeg are the two most common
possibilities.
Accept-Charset
2
This header specifies the character sets that the browser can use to display the
information. For example, ISO-8859-1.
3 Accept-Encoding
This header specifies the types of encodings that the browser knows how to
Accept-Language
4
This header specifies the client's preferred languages in case the servlet can
produce results in more than one language. For example en, en-us, ru, etc.
Authorization
5
This header is used by clients to identify themselves when accessing password-
protected webpages.
Connection
This header indicates whether the client can handle persistent HTTP connections.
6
Persistent connections permit the client or other browser to retrieve multiple files
with a single request. A value of Keep-Alive means that persistent connections
should be used.
Content-Length
7
This header is applicable only to POST requests and gives the size of the POST
data in bytes.
Cookie
8
This header returns cookies to servers that previously sent them to the browser.
Host
9
This header specifies the host and port as given in the original URL.
If-Modified-Since
10 This header indicates that the client wants the page only if it has been changed
after the specified date. The server sends a code, 304 which means Not
Modified header if no newer result is available.
If-Unmodified-Since
11
This header is the reverse of If-Modified-Since; it specifies that the operation
should succeed only if the document is older than the specified date.
12 This header indicates the URL of the referring webpages. For example, if you are
at Webpage 1 and click on a link to Webpage 2, the URL of Webpage 1 is
included in the Referer header when the browser requests Webpage 2.
User-Agent
13
This header identifies the browser or other client making the request and can be
used to return different content to different types of browsers.
The request object provides methods to get HTTP header information including form data,
cookies, HTTP methods, etc.
Following table lists out the important methods that can be used to read HTTP header in your
JSP program. These methods are available with HttpServletRequest object which represents
client request to webserver.
Cookie[] getCookies()
1
Returns an array containing all of the Cookie objects the client sent with this
request.
Enumeration getAttributeNames()
2
Returns an Enumeration containing the names of the attributes available to this
request.
Enumeration getHeaderNames()
3
Returns an enumeration of all the header names this request contains.
Enumeration getParameterNames()
4
Returns an enumeration of String objects containing the names of the parameters
contained in this request.
Locale getLocale()
7
Returns the preferred Locale that the client will accept content in, based on the
Accept-Language header.
ServletInputStream getInputStream()
9
Retrieves the body of the request as binary data using a ServletInputStream.
String getAuthType()
10
Returns the name of the authentication scheme used to protect the servlet, for
example, "BASIC" or "SSL," or null if the JSP was not protected.
String getCharacterEncoding()
11
Returns the name of the character encoding used in the body of this request.
String getContentType()
12
Returns the MIME type of the body of the request, or null if the type is not
known.
String getContextPath()
13
Returns the portion of the request URI that indicates the context of the request.
String getMethod()
15
Returns the name of the HTTP method with which this request was made, for
example, GET, POST, or PUT.
String getPathInfo()
17
Returns any extra path information associated with the URL the client sent when
it made this request.
String getProtocol()
18
Returns the name and version of the protocol the request uses.
String getQueryString()
19
Returns the query string that is contained in the request URL after the path.
String getRemoteAddr()
20
Returns the Internet Protocol (IP) address of the client that sent the request.
String getRemoteHost()
21
Returns the fully qualified name of the client that sent the request.
String getRemoteUser()
22
Returns the login of the user making this request, if the user has been
authenticated, or null if the user has not been authenticated.
23 String getRequestURI()
Returns the part of this request's URL from the protocol name up to the query
String getRequestedSessionId()
24
Returns the session ID specified by the client.
String getServletPath()
25
Returns the part of this request's URL that calls the JSP.
boolean isSecure()
27
Returns a boolean indicating whether this request was made using a secure
channel, such as HTTPS.
int getContentLength()
28
Returns the length, in bytes, of the request body and made available by the input
stream, or -1 if the length is not known.
int getServerPort()
30
Returns the port number on which this request was received.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner. We
will use the hasMoreElements() method to determine when to stop and
the nextElement() method to get the name of each parameter name.
<head>
</head>
<body>
<center>
<th>Header Name</th>
<th>Header Value(s)</th>
</tr>
<%
while(headerNames.hasMoreElements()) {
%>
</table>
</center>
</body>
</html>
Let us now put the above code in main.jsp and try to access it.
accept */*
accept-language en-us
host localhost:8080
connection Keep-Alive
cache-control no-cache
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!doctype ...>
<head>...</head>
<body>
...
</body>
</html>
The status line consists of the HTTP version (HTTP/1.1 in the example),
a status code (200 in the example), and a very short message
corresponding to the status code (OK in the example).
Allow
1
This header specifies the request methods (GET, POST, etc.) that the
server supports.
Cache-Control
Connection
4 Content-Disposition
Content-Encoding
5
This header specifies the way in which the page was encoded during
transmission.
Content-Language
6
This header signifies the language in which the document is written. For
example, en, en-us, ru, etc.
Content-Length
Content-Type
8
This header gives the MIME (Multipurpose Internet Mail Extension)
type of the response document.
Expires
9
This header specifies the time at which the content should be considered
out-of-date and thus no longer be cached.
Last-Modified
10 This header indicates when the document was last changed. The client
can then cache the document and supply a date by an If-Modified-
Since request header in later requests.
Location
This header should be included with all responses that have a status code
11
in the 300s. This notifies the browser of the document address. The
browser automatically reconnects to this location and retrieves the new
document.
12 This header specifies how soon the browser should ask for an updated
page. You can specify time in number of seconds after which a page
would be refreshed.
Retry-After
Set-Cookie
14
This header specifies a cookie associated with the page.
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 following methods can be used to set HTTP response header in your
servlet program. These methods are available with
the HttpServletResponseobject. This object represents the server response.
Encodes the specified URL by including the session ID in it, or, if encoding
boolean isCommitted()
4
Returns a boolean indicating if the response has been committed.
void flushBuffer()
9
Forces any content in the buffer to be written to the client.
void reset()
10
Clears any data that exists in the buffer as well as the status code and
headers.
void resetBuffer()
11
Clears the content of the underlying buffer in the response without
clearing headers or status code.
<html>
<head>
</head>
<body>
<center>
<%
response.setIntHeader("Refresh", 5);
String am_pm;
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
%>
</center>
</body>
</html>
Now put the above code in main.jsp and try to access it. This will display
the current system time after every 5 seconds as follows. Run the JSP. You
will receive the following output: −
You can try working out on the other methods in a similar way.
An initial status line + CRLF (Carriage Return + Line Feed ie. New Line)
HTTP/1.1 200 OK
Header2: ...
...
HeaderN: ...
(Blank Line)
<!doctype ...>
<html>
<head>...</head>
<body>
...
</body>
</html>
Following table lists out the HTTP status codes and associated messages
that might be returned from the Web Server −
204 No Content
402 Payment Required You can not use this code yet.
This method sets an arbitrary status code. The setStatus method takes
1
an int (the status code) as an argument. If your response includes a
special status code and a document, be sure to call setStatus before
actually returning any of the content with the PrintWriter.
3 This method sends a status code (usually 404) along with a short
message that is automatically formatted inside an HTML document and
sent to the client.
<html>
<head>
</head>
<body>
<%
%>
</body>
</html>
description The client must first authenticate itself with the proxy (Need authentication!!!).
Apache Tomcat/5.5.29
To become more comfortable with HTTP status codes, try to set different
status codes and their description.
GET method
The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ? character as follows −
http://www.test.com/hello?key1=value1&key2=value2
The GET method is the default method to pass information from the browser to the web server
and it produces a long string that appears in your browser's Location:box. It is recommended
that the GET method is better not used. if you have password or other sensitive information to
pass to the server.
The GET method has size limitation: only 1024 characters can be in a request string.
POST method
A generally more reliable method of passing information to a backend program is the POST
method.
This method packages the information in exactly the same way as the GET method, but instead
of sending it as a text string after a ? in the URL it sends it as a separate message. This message
comes to the backend program in the form of the standard input which you can parse and use for
your processing.
JSP handles this type of requests using getParameter() method to read simple parameters
and getInputStream() method to read binary data stream coming from the client.
getParameterValues() − Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.
getParameterNames() − Call this method if you want a complete list of all parameters
in the current request.
getInputStream() − Call this method to read binary data stream coming from the client.
http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI
Below is the main.jsp JSP program to handle input given by web browser. We are going to use
the getParameter() method which makes it very easy to access the passed information −
<html>
<head>
</head>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
<html>
<body>
<br />
</form>
</html>
First Name:
Last Name:
< p>Try to enter the First Name and the Last Name and then click the submit button to see the result on
your local machine where tomcat is running. Based on the input provided, it will generate similar result
as mentioned in the above example.
Infact there is no change in the above JSP because the only way of passing parameters is
changed and no binary data is being passed to the JSP program. File handling related concepts
will be explained in separate chapter where we need to read the binary data stream.
<html>
<head>
</head>
<body>
<center>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
<html>
<body>
<br />
</form>
</body>
</html>
First Name:
Last Name:
Try to enter the First and the Last Name and then click the submit button to see the result on
your local machine where tomcat is running.
Based on the input provided, you will receive similar results as in the above examples.
Following is an example HTML code, CheckBox.htm, for a form with two checkboxes.
<html>
<body>
</form>
</body>
</html>
Following is main.jsp JSP program to handle the input given by the web browser for the
checkbox button.
<html>
<head>
</head>
<body>
<ul>
<li><p><b>Maths Flag:</b>
<%= request.getParameter("maths")%>
</p></li>
<%= request.getParameter("physics")%>
</p></li>
<li><p><b>Chemistry Flag:</b>
<%= request.getParameter("chemistry")%>
</p></li>
</ul>
</body>
</html>
Chemistry Flag:: on
Once we have an Enumeration, we can loop down the Enumeration in the standard manner,
using the hasMoreElements() method to determine when to stop and using
the nextElement() method to get each parameter name.
<html>
<head>
</head>
<body>
<center>
<th>Param Name</th>
<th>Param Value(s)</th>
</tr>
<%
while(paramNames.hasMoreElements()) {
%>
</table>
</center>
</body>
</html>
<html>
<body>
</form>
</body>
</html>
maths on
chemistry on
You can try the above JSP to read any other form's data which is having other objects like text
box, radio button or dropdown, etc.
JSP - Filters
In this chapter, we will discuss Filters in JSP. Servlet and JSP Filters are Java classes that can be
used in Servlet and JSP Programming for the following purposes −
To intercept requests from a client before they access a resource at back end.
To manipulate responses from server before they are sent back to the client.
Authentication Filters
Encryption Filters
Tokenizing Filters
Filters are deployed in the deployment descriptor file web.xml and then map to either servlet or
JSP names or URL patterns in your application's deployment descriptor. The deployment descriptor
file web.xml can be found in <Tomcat-installation-directory>\conf directory.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
chain.doFilter(request,response);
Compile LogFilter.java in the usual way and put your LogFilter.class file in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/classes.
<filter>
<filter-name>LogFilter</filter-name>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The above filter will apply to all the servlets and JSP because we specified /*in our configuration.
You can specify a particular servlet or the JSP path if you want to apply filter on few servlets or JSP
only.
Now try to call any servlet or JSP and you will see generated log in you web server log. You can
use Log4J logger to log above log in a separate file.
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>LogFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter>
<filter-name>AuthenFilter</filter-name>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
For example, the above example will apply the LogFilter first and then it will apply AuthenFilter to
any servlet or JSP; the following example will reverse the order −
<filter-mapping>
<filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Server script sends a set of cookies to the browser. For example, name, age, or
identification number, etc.
Browser stores this information on the local machine for future use.
When the next time the browser sends any request to the web server then it
sends those cookies information to the server and server uses that information
to identify the user or may be for some other purpose as well.
This chapter will teach you how to set or reset cookies, how to access them
and how to delete them using JSP programs.
HTTP/1.1 200 OK
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a
GMT date, a path and a domain. The name and value will be URL
encoded. The expires field is an instruction to the browser to "forget" the
cookie after the given time and date.
Connection: Keep-Alive
Host: zink.demon.co.uk:1126
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
A JSP script will then have access to the cookies through the request
method request.getCookies() which returns an array of Cookie objects.
3 This method sets how much time (in seconds) should elapse before the
cookie expires. If you don't set this, the cookie will last only for the
current session.
8 This method sets the path to which this cookie applies. If you don't
specify a path, the cookie is returned for all URLs in the same directory as
the current page as well as all subdirectories.
Keep in mind, neither the name nor the value should contain white space or
any of the following characters −
[ ] ( ) = , " / ? @ : ;
Example
Let us modify our Form Example to set the cookies for the first and the last
name.
<%
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
response.addCookie( firstName );
response.addCookie( lastName );
%>
<html>
<head>
</head>
<body>
<center>
<h1>Setting Cookies</h1>
</center>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
Let us put the above code in main.jsp file and use it in the following HTML
page −
<html>
<body>
<br />
</form>
</body>
</html>
First Name:
Last Name:
Try to enter the First Name and the Last Name and then click the submit
button. This will display the first name and the last name on your screen
and will also set two cookies firstName and lastName. These cookies will
be passed back to the server when the next time you click the Submit
button.
In the next section, we will explain how you can access these cookies back
in your web application.
Example
Let us now read cookies that were set in the previous example −
<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
cookies = request.getCookies();
cookie = cookies[i];
} else {
%>
</body>
</html>
Let us now put the above code in main.jsp file and try to access it. If you
set the first_name cookie as "John" and the last_name cookie as
"Player" then running http://localhost:8080/main.jsp will display the
following result −
Set cookie age as zero using the setMaxAge() method to delete an existing
cookie.
Example
Following example will show you how to delete an existing cookie
named "first_name" and when you run main.jsp JSP next time, it will
return null value for first_name.
<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
cookies = request.getCookies();
cookie = cookies[i];
cookie.setMaxAge(0);
response.addCookie(cookie);
cookie.getName( ) + "<br/>");
} else {
out.println(
%>
</body>
</html>
Let us now put the above code in the main.jsp file and try to access it. It
will display the following result −
Cookies
A webserver can assign a unique session ID as a cookie to each web client and for subsequent
requests from the client they can be recognized using the received cookie.
This may not be an effective way as the browser at times does not support a cookie. It is not
recommended to use this procedure to maintain the sessions.
This entry means that, when the form is submitted, the specified name and value are
automatically included in the GET or the POST data. Each time the web browser sends the
request back, the session_id value can be used to keep the track of different web browsers.
This can be an effective way of keeping track of the session but clicking on a regular (<A
HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot
support general session tracking.
URL Rewriting
You can append some extra data at the end of each URL. This data identifies the session; the
server can associate that session identifier with the data it has stored about that session.
visit to a website or
By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for
each new client automatically. Disabling session tracking requires explicitly turning it off by
setting the page directive session attribute to false as follows −
<%@ page session = "false" %>
The JSP engine exposes the HttpSession object to the JSP author through the
implicit session object. Since session object is already provided to the JSP programmer, the
programmer can immediately begin storing and retrieving data from the object without any
initialization or getSession().
<%
if (session.isNew() ){
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
%>
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking</h1>
</center>
<th>Session info</th>
<th>Value</th>
</tr>
<tr>
<td>id</td>
</tr>
<tr>
<td>Creation Time</td>
</tr>
<tr>
</tr>
<tr>
<td>User ID</td>
</tr>
<tr>
<td>Number of visits</td>
</tr>
</table>
</body>
</html>
Now put the above code in main.jsp and try to access http://localhost:8080/main.jsp. Once you
run the URL, you will receive the following result −
id 0AE3EC93FF44E3C525B4351B77ABB2D5
User ID ABCD
Number of visits 0
Now try to run the same JSP for the second time, you will receive the following result.
id 0AE3EC93FF44E3C525B4351B77ABB2D5
User ID ABCD
Number of visits 1
Delete the whole session − You can call the public void invalidate() method to discard
an entire session.
Setting Session timeout − You can call the public void setMaxInactiveInterval(int
interval) method to set the timeout for a session individually.
Log the user out − The servers that support servlets 2.4, you can call logout to log the
client out of the Web server and invalidate all sessions belonging to all the users.
web.xml Configuration − If you are using Tomcat, apart from the above mentioned
methods, you can configure the session time out in web.xml file as follows.
<session-config>
<session-timeout>15</session-timeout>
</session-config>
The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in
Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session
in seconds. So if your session is configured in web.xml for 15
minutes, getMaxInactiveInterval( ) returns 900.
The form method attribute should be set to POST method and GET method can not be
used.
The form action attribute should be set to a JSP file which would handle file uploading
at backend server. Following example is using uploadFile.jsp program file to upload
file.
To upload a single file you should use a single <input .../> tag with attribute type =
"file". To allow multiple files uploading, include more than one input tag with different
<html>
<head>
</head>
<body>
<h3>File Upload:</h3>
enctype = "multipart/form-data">
<br />
</form>
</body>
</html>
This will display the following result. You can now select a file from the local PC and when the
user clicks "Upload File", the form gets submitted along with the selected file −
File Upload −
NOTE − Above form is just dummy form and would not work, you should try above
code at your machine to make it work.
<web-app>
....
<context-param>
<param-name>file-upload</param-name>
<param-value>
c:\apache-tomcat-5.5.29\webapps\data\
</param-value>
</context-param>
....
</web-app>
Following is the source code for UploadFile.jsp. This can handle uploading of multiple files at
a time. Let us now consider the following before proceeding with the uploading of files.
The following example depends on FileUpload; make sure you have the latest version
of commons-fileupload.x.x.jar file in your classpath. You can download it
from https://commons.apache.org/fileupload/.
FileUpload depends on Commons IO; make sure you have the latest version
of commons-io-x.x.jar file in your classpath. You can download it
from https://commons.apache.org/io/.
While testing the following example, you should upload a file which is of less size
than maxFileSize otherwise the file will not be uploaded.
<%
File file ;
factory.setSizeThreshold(maxMemSize);
factory.setRepository(new File("c:\\temp"));
upload.setSizeMax( maxFileSize );
try {
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () ) {
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () ) {
fileName.substring( fileName.lastIndexOf("\\"))) ;
} else {
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
fi.write( file ) ;
fileName + "<br>");
out.println("</body>");
out.println("</html>");
} catch(Exception ex) {
System.out.println(ex);
} else {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("</body>");
out.println("</html>");
%>
Now try to upload files using the HTML form which you created above. When you
try http://localhost:8080/UploadFile.htm, it will display the following result. This will help
you upload any file from your local machine.
File Upload −
If your JSP script works fine, your file should be uploaded in c:\apache-
tomcat5.5.29\webapps\data\ directory.
The Date class supports two constructors. The first constructor initializes the object with the
current date and time.
Date( )
The following constructor accepts one argument that equals the number of milliseconds that
have elapsed since midnight, January 1, 1970.
Date(long millisec)
Once you have a Date object available, you can call any of the following support methods to
play with dates −
4 Compares the value of the invoking object with that of date. Returns 0 if the
values are equal. Returns a negative value if the invoking object is earlier than
date. Returns a positive value if the invoking object is later than date.
long getTime( )
7
Returns the number of milliseconds that have elapsed since January 1, 1970.
int hashCode( )
8
Returns a hash code for the invoking object.
String toString( )
10
Converts the invoking Date object into a string and returns the result.
<html>
</head>
<body>
<center>
</center>
<%
%>
</body>
</html>
Let us now keep the code in CurrentDate.jsp and then call this JSP using the
URL http://localhost:8080/CurrentDate.jsp. You will receive the following result −
Date Comparison
As discussed in the previous sections, you can use all the available Java methods in your JSP
scripts. In case you need to compare two dates, consider the following methods −
You can use getTime( ) method to obtain the number of milliseconds that have elapsed
since midnight, January 1, 1970, for both objects and then compare these two values.
You can use the methods before( ), after( ), and equals( ) because the 12th of the month
comes before the 18th; for example, new Date(99, 2, 12).before(new Date (99, 2,
18)) returns true.
You can use the compareTo( ) method; this method is defined by the Comparable
interface and implemented by Date.
<html>
<head>
</head>
<body>
<center>
</center>
<%
SimpleDateFormat ft =
%>
</body>
</html>
Compile the above servlet once again and then call this servlet using the
URL http://localhost:8080/CurrentDate. You will receive the following result −
G Era designator AD
d Day in month 0
m Minute in hour 30
s Second in minute 55
S Millisecond 234
w Week in year 40
W Week in month
a A.M./P.M. marker PM
For a complete list of constant available methods to manipulate date, you can refer to the
standard Java documentation.
This method sends back the response to the browser along with the status
code and new page location. You can also use the setStatus() and
the setHeader() methods together to achieve the same redirection
example −
....
String site = "http://www.newpage.com" ;
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
....
Example
This example shows how a JSP performs page redirection to an another
location −
<head>
<title>Page Redirection</title>
</head>
<body>
<center>
<h1>Page Redirection</h1>
</center>
<%
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
%>
</body>
</html>
Let us now put the above code in PageRedirect.jsp and call this JSP using
the URL http://localhost:8080/PageRedirect.jsp. This would take you
to the given URL http://www.photofuntoos.com.
To implement a hit counter you can make use of the Application Implicit
object and associated methods getAttribute() and setAttribute().
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.
Every time a user accesses your page, you can read the current value of the
hit counter and increase it by one and again set it for future use.
Example
This example shows how you can use JSP to count the total number of hits
on a particular page. If you want to count the total number of hits of your
website then you will have to include the same code in all the JSP pages.
<html>
<head>
</head>
<body>
<%
/* First visit */
out.println("Welcome to my website!");
hitsCount = 1;
} else {
/* return visit */
hitsCount += 1;
application.setAttribute("hitCounter", hitsCount);
%>
</center>
</body>
</html>
Let us now put the above code in main.jsp and call this JSP using the
URL http://localhost:8080/main.jsp. This will display the hit counter
value which increases as and when you refresh the page. You can try
accessing the page using different browsers and you will find that the hit
counter will keep increasing with every hit and you will receive the result as
follows −
Define a database table with a single count, let us say hitcount. Assign a zero
value to it.
With every hit, read the table to get the value of hitcount.
Increase the value of hitcount by one and update the table with new value.
If you want to count hits for all the pages, implement above logic for all the
pages.
This method sends back the header "Refresh" to the browser along with an
integer value which indicates time interval in seconds.
<html>
<head>
</head>
<body>
<center>
<%
response.setIntHeader("Refresh", 5);
String am_pm;
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
am_pm = "PM";
%>
</center>
</body>
</html>
Now put the above code in main.jsp and try to access it. This will display
the current system time after every 5 seconds as follows. Just run the JSP
and wait to see the result −
SP - Sending Email
In this chapter, we will discuss how to send emails using JSP. To send an email
using a JSP, you should have the JavaMail API and the Java Activation
Framework (JAF) installed on your machine.
You can download the latest version of JavaMail (Version 1.2) from the Java's
standard website.
You can download the latest version of JavaBeans Activation Framework JAF
(Version 1.0.2) from the Java's standard website.
<%
String result;
String to = "[email protected]";
properties.setProperty("mail.smtp.host", host);
try {
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
Transport.send(message);
mex.printStackTrace();
%>
<html>
<head>
</head>
<body>
<center>
</center>
<%
%>
</p>
</body>
</html>
Let us now put the above code in SendEmail.jsp file and call this JSP using
the URL http://localhost:8080/SendEmail.jsp. This will help send an
email to the given email ID [email protected]. You will receive the
following response −
If you want to send an email to multiple recipients, then use the following
methods to specify multiple email IDs −
throws MessagingException
type − This would be set to TO, CC or BCC. Here CC represents Carbon Copy
and BCC represents Black Carbon Copy. Example Message.RecipientType.TO
addresses − This is the array of email ID. You would need to use the
InternetAddress() method while specifying email IDs
This example is very similar to the previous one, except that here we are
using the setContent() method to set content whose second argument
is "text/html" to specify that the HTML content is included in the
message.
Using this example, you can send as big an HTML content as you require.
<%
String result;
String to = "[email protected]";
properties.setProperty("mail.smtp.host", host);
try {
message.setFrom(new InternetAddress(from));
// Send message
Transport.send(message);
mex.printStackTrace();
%>
<html>
<head>
<body>
<center>
</center>
<%
%>
</p>
</body>
</html>
Let us now use the above JSP to send HTML message on a given email ID.
<%
String result;
String to = "[email protected]";
try {
message.setFrom(new InternetAddress(from));
multipart.addBodyPart(messageBodyPart);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart );
// Send message
mex.printStackTrace();
%>
<html>
<head>
</head>
<body>
<center>
</center>
</p>
</body>
</html>
Let us now run the above JSP to send a file as an attachment along with a
message on a given email ID.
String to = request.getParameter("to");
Once you have all the information, you can use the above mentioned
programs to send email.
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 the existing custom tags with the JSTL tags.
Step 1 − Download the binary distribution from Apache Standard Tagliband unpack the
compressed file.
Step 2 − To use the Standard Taglib from its Jakarta Taglibs distribution, simply copy the
JAR files in the distribution's 'lib' directory to your application's webapps\ROOT\WEB-
INF\lib directory.
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
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 −
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<c:out>
1
<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>
6
Simple conditional tag that establishes a context for mutually exclusive
conditional operations, marked by <when> and <otherwise>.
<c:when>
7
Subtag of <choose> that includes its body if its condition evalutes to 'true'.
8 <c:otherwise >
<c:import>
9
Retrieves an absolute or relative URL and exposes its contents to either the page,
a String in 'var', or a Reader in 'varReader'.
<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 −
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
1 <fmt:formatNumber>
<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:setDataSource>
1
<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.
<sql:dateParam>
5
Sets a parameter in an SQL statement to the specified java.util.Date value.
<sql:transaction >
6
Provides nested database action elements with a shared 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 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
<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 >
4
Evaluates a test XPath expression and if it is true, it processes its body. If the test
condition is false, the body is ignored.
<x:forEach>
5
To loop over nodes in an XML document.
<x:choose>
6
Simple conditional tag that establishes a context for mutually exclusive
conditional operations, marked by <when> and <otherwise> tags.
<x:when >
7
Subtag of <choose> that includes its body if its expression evalutes to 'true'.
8 <x:otherwise >
<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 −
<%@ taglib prefix = "fn"
uri = "http://java.sun.com/jsp/jstl/functions" %>
fn:contains()
1
fn:containsIgnoreCase()
2
Tests if an input string contains the specified substring in a case insensitive way.
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()
5
Returns the index withing a string of the first occurrence of a specified substring.
6 fn:join()
fn:length()
7
Returns the number of items in a collection, or the number of characters in a
string.
fn:replace()
8
Returns a string resulting from replacing in an input string all occurrences with a
given string.
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.
fn:substringBefore()
13
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.
For more detail on how to access database using JDBC and its environment
setup you can go through our JDBC Tutorial.
To start with basic concept, let us create a table and create a few records in
that table as follows −
Create Table
To create the Employees table in the EMP database, use the following
steps −
Step 1
Open a Command Prompt and change to the installation directory as
follows −
C:\>
C:\Program Files\MySQL\bin>
Step 2
Login to the database as follows −
mysql>
Step 3
Create the Employee table in the TEST database as follows − −
);
mysql>
mysql>
SELECT Operation
Following example shows how we can execute the SQL SELECT statement
using JTSL in JSP programming −
<html>
<head>
<title>SELECT Operation</title>
</head>
url = "jdbc:mysql://localhost/TEST"
</sql:query>
<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<tr>
</tr>
</c:forEach>
</table>
</body>
</html>
INSERT Operation
Following example shows how we can execute the SQL INSERT statement
using JTSL in JSP programming −
<html>
<head>
<title>JINSERT Operation</title>
</head>
<body>
url = "jdbc:mysql://localhost/TEST"
</sql:update>
</sql:query>
<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<tr>
</tr>
</c:forEach>
</table>
</body>
</html>
<html>
<head>
<title>DELETE Operation</title>
</head>
<body>
url = "jdbc:mysql://localhost/TEST"
</sql:update>
</sql:query>
<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr>
</tr>
</c:forEach>
</table>
</body>
</html>
01 Mahnaz Fatma 25
UPDATE Operation
Following example shows how we can execute the SQL UPDATE statement
using JTSL in JSP programming −
<head>
<title>DELETE Operation</title>
</head>
<body>
url = "jdbc:mysql://localhost/TEST"
</sql:update>
</sql:query>
<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<tr>
</tr>
</c:forEach>
</table>
</body>
</html>
SP - JavaBeans
It may have a number of "getter" and "setter" methods for the properties.
JavaBeans Properties
A JavaBean property is a named attribute that can be accessed by the user
of the object. The attribute can be of any Java data type, including the
classes that you define.
getPropertyName()
1
For example, if property name is firstName, your method name would
be getFirstName() to read that property. This method is called accessor.
setPropertyName()
2
For example, if property name is firstName, your method name would
be setFirstName() to write that property. This method is called mutator.
JavaBeans Example
Consider a student class with few properties −
package com.tutorialspoint;
public StudentsBean() {
return firstName;
return lastName;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
Accessing JavaBeans
The useBean action declares a JavaBean for use in a JSP. Once declared,
the bean becomes a scripting variable that can be accessed by both
scripting elements and other custom tags used in the JSP. The full syntax
for the useBean tag is as follows −
<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>
<html>
<head>
<title>useBean Example</title>
</head>
<body>
</body>
value = "value"/>
...........
</jsp:useBean>
Following example shows how to access the data using the above syntax −
<html>
<head>
</head>
<body>
</jsp:useBean>
</p>
<p>Student Age:
</p>
</body>
</html>
Student Age: 10
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 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 −
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
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
Let us compile the above class and copy it in a directory available in the
environment variable CLASSPATH. Finally, create the following tag library
file: <Tomcat-Installation-Directory>webapps\ROOT\WEB-
INF\custom.tld.
<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 −
<html>
<head>
</head>
<body>
<ex:Hello/>
</body>
</html>
Call the above JSP and this should produce the following result −
Hello Custom Tag!
<ex:Hello>
</ex:Hello>
Let us make the following changes in the above tag code to process the
body of the tag −
package com.tutorialspoint;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
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>
<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 −
<html>
<head>
</head>
<body>
<ex:Hello>
</ex:Hello>
</body>
</html>
package com.tutorialspoint;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
this.message = msg;
if (message != null) {
out.println( message );
} else {
getJspBody().invoke(sw);
getJspContext().getOut().println(sw.toString());
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<tag>
<name>Hello</name>
<tag-class>com.tutorialspoint.HelloTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>message</name>
</attribute>
</tag>
</taglib>
<html>
<head>
</head>
<body>
</body>
</html>
name
1
The name element defines the name of an attribute. Each attribute name
must be unique for a particular tag.
required
2
This specifies if this attribute is required or is an optional one. It would be
false for optional.
rtexprvalue
3
Declares if a runtime expression value for a tag attribute is valid
type
4
Defines the Java class-type of this attribute. By default it is assumed
as String
description
5
Informational description can be provided.
fragment
6
Declares if this attribute value should be treated as a JspFragment.
.....
<attribute>
<name>attribute_name</name>
<required>false</required>
<type>java.util.Date</type>
<fragment>false</fragment>
</attribute>
.....
.....
<attribute>
<name>attribute_name1</name>
<required>false</required>
<type>java.util.Boolean</type>
<fragment>false</fragment>
</attribute>
<attribute>
<name>attribute_name2</name>
<required>true</required>
<type>java.util.Date</type>
</attribute>
.....
Checked exceptions
A checked exception is an exception that is typically a user error or a
problem that cannot be foreseen by the programmer. For example, if a file
is to be opened, but the file cannot be found, an exception occurs. These
exceptions cannot simply be ignored at the time of compilation.
Runtime exceptions
A runtime exception is an exception that probably could have been avoided
by the programmer. As opposed to the checked exceptions, runtime
exceptions are ignored at the time of compliation.
Errors
JSP gives you an option to specify Error Page for each JSP. Whenever the
page throws an exception, the JSP container automatically invokes the error
page.
<html>
<head>
</head>
<body>
<%
int x = 1;
if (x == 1) {
%>
</body>
</html>
We will now write one Error Handling JSP ShowError.jsp, which is given
below. Notice that the error-handling page includes the directive <%@
page isErrorPage = "true" %>. This directive causes the JSP compiler to
generate the exception instance variable.
<head>
</head>
<body>
<h1>Opps...</h1>
</body>
</html>
Access the main.jsp, you will receive an output somewhat like the
following −
java.lang.RuntimeException: Error condition!!!
......
Opps...
Sorry, an error occurred.
<html>
<head>
</head>
<body>
<h1>Opps...</h1>
<td>${pageContext.exception}</td>
</tr>
<td><b>URI:</b></td>
<td>${pageContext.errorData.requestURI}</td>
</tr>
<td><b>Status code:</b></td>
<td>${pageContext.errorData.statusCode}</td>
</tr>
<td><b>Stack trace:</b></td>
<td>
items = "${pageContext.exception.stackTrace}">
<p>${trace}</p>
</c:forEach>
</td>
</tr>
</table>
</body>
</html>
URI: /main.jsp
org.apache.jsp.main_jsp._jspService(main_jsp.java:65)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:68)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Following is a simple example which shows how to use the try...catch block.
Let us put the following code in main.jsp −
<html>
<head>
<title>Try...Catch Example</title>
</head>
<body>
<%
try {
int i = 1;
i = i / 0;
catch (Exception e) {
%>
</body>
</html>