JSP Architecture
JSP Architecture
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.
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.
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
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 Execution
This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes
the _jspService() method in the JSP.
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.
Syntax
Elements of JSP
The Scriptlet
A scriptlet can contain any number of JAVA language statements, variable or method declarations, or
expressions that are valid in the page scripting language.
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/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>
NOTE Assuming that Apache Tomcat is installed in C:\apache-tomcat-7.0.2 and your environment is
setup as per environment setup tutorial.
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
A declaration declares one or more variables or methods that you can use in Java code later in the JSP
file. You must declare the variable or method before you use it in the JSP file.
You can write the XML equivalent of the above syntax as follows
<jsp:declaration>
code fragment
</jsp:declaration>
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>
<head><title>A Comment Test</title></head>
<body>
<p>Today's date: <%= (new
java.util.Date()).toLocaleString()%></p>
</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>
<head><title>A Comment Test</title></head>
<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body>
</html>
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
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.
There is only one syntax for the Action element, as it conforms to the XML standard
Action elements are basically predefined functions. Following table lists out the available JSP Actions
JSP supports nine automatically defined variables, which are also called implicit objects. These variables
are
request
1
This is the HttpServletRequest object associated with the 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.
page
8
This is simply a synonym for this, and is used to call the methods defined by the translated
servlet class.
Exception
9
The Exception object allows the exception data to be accessed by designated JSP.
We would explain JSP Implicit Objects in a separate chapter JSP - Implicit Objects.
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.
<body>
<% if (day == 1 | day == 7) { %>
<p> Today is weekend</p>
<% } else { %>
<p> Today is not weekend</p>
<% } %>
</body>
</html>
The above code will generate the following result
Now look at the following switch...case block which has been written a bit differentlty using
out.println() and inside Scriptletas
<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.
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.
Within an expression, higher precedence operators will be evaluated first.
JSP Literals
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.
The page directive is used to provide instructions to the container. These instructions pertain to the current JSP
page. You may code page directives anywhere in your JSP page. By convention, page directives are coded at the top
of the JSP page.
You can write the XML equivalent of the above syntax as follows
The include directive is used to include a file during the translation phase. This directive tells the container to merge
the content of other external files with the current JSP during the translation phase. You may code the include
directives anywhere in your JSP page.
You can write the XML equivalent of the above syntax as follows
For more details related to include directive, check the Include 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.
Here, the uri attribute value resolves to a location the container understands and the prefix attribute informs a
container what bits of markup are custom actions.
You can write the XML equivalent of the above syntax as follows
JSP ACTIONS
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
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.
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 id attribute and the scope attribute.
Id attribute
The id attribute uniquely identifies the Action element, and allows the action to be referenced inside the JSP page. If
the Action creates an instance of an object, the id value can be used to reference it through the implicit object
PageContext.
Scope attribute
This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute are directly
related, as the scope attribute determines the lifespan of the object associated with the id. The scope attribute has
four possible values: (a) page, (b)request, (c)session, and (d) application.
This action lets you insert files into the page being generated. The syntax looks like this
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
S.No. Attribute & Description
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>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:include page = "date.jsp" flush = "true" />
</center>
</body>
</html>
Let us now keep all these files in the root directory and try to access main.jsp. You will receive the following output
The useBean action is quite versatile. It first searches for an existing object utilizing the id and scope variables. If an
object is not found, it then tries to create the specified object.
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.
Let us now discuss the jsp:setProperty and the jsp:getProperty actions before giving a valid example related to
these actions.
The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts
it into the output.
The getProperty action has only two attributes, both of which are required. The syntax of the getProperty action is as
follows
Following table lists out the required attributes associated with the getProperty action
name
1
The name of the Bean that has a property to be retrieved. The Bean must have been previously
defined.
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;
public class TestBean {
private String message = "No message specified";
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 CLASSPATH variable 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>
<title>Using JavaBeans in JSP</title>
</head>
<body>
<center>
<h2>Using JavaBeans in JSP</h2>
<jsp:useBean id = "test" class = "action.TestBean" />
<jsp:setProperty name = "test" property = "message"
value = "Hello JSP..." />
<p>Got message....</p>
<jsp:getProperty name = "test" property = "message" />
</center>
</body>
</html>
Let us now try to access main.jsp, it would display the following result
Got message....
Hello JSP...
The forward action terminates the action of the current page and forwards the request to another resource such as a
static page, another JSP page, or a Java Servlet.
Following 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>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:forward page = "date.jsp" />
</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.
The plugin action is used to insert Java components into a JSP page. It determines the type of browser and inserts
the <object> or <embed> tags as needed.
If the needed plugin is not present, it downloads the plugin and then executes the Java component. The Java
component can be either an Applet or a JavaBean.
The plugin action has several attributes that correspond to common HTML tags used to format Java components.
The <param> element can also be used to send parameters to the Applet or Bean.
Following is the typical syntax of using the plugin action
<jsp:fallback>
Unable to initialize Java Plugin
</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.
The <jsp:element>, <jsp:attribute> and <jsp:body> actions are used to define XML elements dynamically. The
word dynamically is important, because it means that the XML elements can be generated at request time rather than
statically at compile time.
<body>
<jsp:element name = "xmlElement">
<jsp:attribute name = "xmlElementAttr">
Value for the attribute
</jsp:attribute>
<jsp:body>
Body for XML element
</jsp:body>
</jsp:element>
</body>
</html>
This would produce the following HTML code at run time
<body>
<xmlElement xmlElementAttr = "Value for the attribute">
Body for XML element
</xmlElement>
</body>
</html>
The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the server creates
the request object, it also creates an object to represent the response to the client.
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.
We will cover a complete set of methods associated with the response object in a subsequent chapter JSP - Server
Response.
The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same way that session
objects behave under Java Servlets.
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.
The application object is direct wrapper around the ServletContext object for the generated Servlet and in reality an
instance of a javax.servlet.ServletContext object.
This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page
is initialized and will be removed when the JSP page is removed by the jspDestroy() method.
By adding an attribute to application, you can ensure that all JSP files that make up your web application have
access to it.
We will check the use of Application Object in JSP - Hits Counter chapter.
PAGE REDIRECT
In this chapter, we will discuss page redirecting with JSP. Page redirection is generally used when a document
moves to a new location and we need to send the client to this new location. This can be because of load balancing,
or for simple randomization.
The simplest way of redirecting a request to another page is by using sendRedirect() method of response object.
Following is the signature of this method
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
<html>
<head>
<title>Page Redirection</title>
</head>
<body>
<center>
<h1>Page Redirection</h1>
</center>
<%
// New location to be redirected
String site = new String("http://www.photofuntoos.com");
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.
HITS COUNTER
In this chapter, we will discuss Hits Counter in JSP. A hit counter tells you about the number of visits on a particular
page of your web site. Usually you attach a hit counter with your index.jsp page assuming people first land on your
home page.
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.
You can use the above method to set a hit counter variable and to reset the same variable. Following is the method to
read the variable set by the previous method
application.getAttribute(String Key);
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>
<title>Application object in JSP</title>
</head>
<body>
<%
Integer hitsCount = (Integer)application.getAttribute("hitCounter");
if( hitsCount ==null || hitsCount == 0 ) {
/* First visit */
out.println("Welcome to my website!");
hitsCount = 1;
} else {
/* return visit */
out.println("Welcome back to my website!");
hitsCount += 1;
}
application.setAttribute("hitCounter", hitsCount);
%>
<center>
<p>Total number of visits: <%= hitsCount%></p>
</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
In the following example, we will use the setIntHeader() method to set Refresh header. This will help simulate a
digital clock
<html>
<head>
<title>Auto Refresh Header Example</title>
</head>
<body>
<center>
<h2>Auto Refresh Header Example</h2>
<%
// Set refresh, autoload time as 5 seconds
response.setIntHeader("Refresh", 5);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
out.println("Crrent Time: " + CT + "\n");
%>
</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
SEND 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.
Download and unzip these files, in the newly-created top-level directories. You will find a
number of jar files for both the applications. You need to add the mail.jar and the activation.jar
files in your CLASSPATH.
<%
String result;
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(mailSession);
// Send message
Transport.send(message);
result = "Sent message successfully....";
} catch (MessagingException mex) {
mex.printStackTrace();
result = "Error: unable to send message....";
}
%>
<html>
<head>
<title>Send Email using JSP</title>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
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 abcd@gmail.com. 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
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
Here is an example to send an HTML email from your machine. It is assumed that your localhost is connected to the
Internet and that it is capable enough to send an email. Make sure all the jar files from the Java Email API package
and the JAF package are available in CLASSPATH.
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;
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(mailSession);
// Send message
Transport.send(message);
result = "Sent message successfully....";
} catch (MessagingException mex) {
mex.printStackTrace();
result = "Error: unable to send message....";
}
%>
<html>
<head>
<title>Send HTML Email using JSP</title>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
Let us now use the above JSP to send HTML message on a given email ID.
<%
String result;
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(mailSession);
// Send message
Transport.send(message);
String title = "Send Email";
result = "Sent message successfully....";
} catch (MessagingException mex) {
mex.printStackTrace();
result = "Error: unable to send message....";
}
%>
<html>
<head>
<title>Send Attachment Email using JSP</title>
</head>
<body>
<center>
<h1>Send Attachment Email using JSP</h1>
</center>
Let us now run the above JSP to send a file as an attachment along with a message on a given email ID.
You can use HTML form to accept email parameters and then you can use the request object to get all the
information as follows
String to = request.getParameter("to");
String from = request.getParameter("from");
String subject = request.getParameter("subject");
String messageText = request.getParameter("body");
Once you have all the information, you can use the above mentioned programs to send email.