[go: up one dir, main page]

0% found this document useful (0 votes)
125 views29 pages

JSP Architecture

The document discusses the architecture and processing of JSP pages. A JSP container within the web server processes JSP requests and converts JSP pages into servlets. This conversion occurs on the first request or if the JSP is modified. The servlet is then executed to generate the HTML response. The key elements of JSP pages include scriptlets, declarations, expressions, comments, directives, and actions.

Uploaded by

Bhasker Jha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
125 views29 pages

JSP Architecture

The document discusses the architecture and processing of JSP pages. A JSP container within the web server processes JSP requests and converts JSP pages into servlets. This conversion occurs on the first request or if the JSP is modified. The servlet is then executed to generate the HTML response. The key elements of JSP pages include scriptlets, declarations, expressions, comments, directives, and actions.

Uploaded by

Bhasker Jha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

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.

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.

Paths Followed By JSP

The following are the paths followed by a JSP

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.

The compilation process involves three steps

Parsing the JSP.


Turning the JSP into a servlet.
Compiling the servlet.

JSP Execution

This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.

Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes
the _jspService() method in the JSP.

The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters


as follows

void _jspService(HttpServletRequest request, HttpServletResponse


response) {
// Service handling code...
}
The _jspService() method of a JSP is invoked on request basis. This is responsible for generating the
response for that request and this method is also responsible for generating responses to all seven of the
HTTP methods, i.e, GET, POST, DELETE, etc.

JSP Cleanup

The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a
container.

The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy
when you need to perform any cleanup, such as releasing database connections or closing open files.

The jspDestroy() method has the following form

public void jspDestroy() {


// Your cleanup code goes here.
}

Syntax

Elements of JSP

The elements of JSP have been described below

The Scriptlet

A scriptlet can contain any number of JAVA language statements, variable or method declarations, or
expressions that are valid in the page scripting language.

Following is the syntax of Scriptlet

<% code fragment %>

You can write the XML equivalent of the above syntax as follows

<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.

Following is the syntax for JSP Declarations

<%! declaration; [ declaration; ]+ ... %>

You can write the XML equivalent of the above syntax as follows

<jsp:declaration>
code fragment
</jsp:declaration>

Following is an example for JSP Declarations

<%! int i = 0; %>


<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
JSP Expression

A JSP expression element contains a scripting language expression that is evaluated, converted to a
String, and inserted where the expression appears in the JSP file.
Because the value of an expression is converted to a String, you can use an expression within a line of
text, whether or not it is tagged with HTML, in a JSP file.

The expression element can contain any expression that is valid according to the Java Language
Specification but you cannot use a semicolon to end an expression.

Following is the syntax of JSP Expression

<%= expression %>

You can write the XML equivalent of the above syntax as follows

<jsp:expression>
expression
</jsp:expression>

Following example shows a JSP Expression

<html>
<head><title>A Comment Test</title></head>

<body>
<p>Today's date: <%= (new
java.util.Date()).toLocaleString()%></p>
</body>
</html>

The above code will generate the following result

Today's date: 11-Sep-2010 21:24:25

JSP Comments

JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful
when you want to hide or "comment out", a part of your JSP page.

Following is the syntax of the JSP comments

<%-- This is JSP comment --%>

Following example shows the JSP Comments

<html>
<head><title>A Comment Test</title></head>

<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body>
</html>

The above code will generate the following result

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

<%@ directive attribute="value" %>

There are three types of directive tag

S.No. Directive & Description

<%@ page ... %>


1
Defines page-dependent attributes, such as scripting language, error page, and buffering
requirements.
<%@ include ... %>
2
Includes a file during the translation phase.
<%@ taglib ... %>
3
Declares a tag library, containing custom actions, used in the page

We would explain the JSP directive in a separate chapter JSP - Directives

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

<jsp:action_name attribute="value" />

Action elements are basically predefined functions. Following table lists out the available JSP Actions

S.No. Syntax & Purpose


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.

We would explain JSP actions in a separate chapter JSP - Actions

JSP Implicit Objects

JSP supports nine automatically defined variables, which are also called implicit objects. These variables
are

S.No. Object & Description

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.

<%! int day = 3; %>


<html>
<head><title>IF...ELSE Example</title></head>

<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

Today is not weekend

Now look at the following switch...case block which has been written a bit differentlty using
out.println() and inside Scriptletas

<%! int day = 3; %>


<html>
<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>

The above code will generate the following result

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.

Category Operator Associativity

Postfix () [] . (dot operator) Left to right

Unary ++ - - ! ~ Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift >> >>> << Left to right

Relational > >= < <= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Comma , Left to right

JSP Literals

The JSP expression language defines the following literals

Boolean true and false


Integer as in Java
Floating point as in Java
String with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\.
Null null
JSP DERIVATIVE

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.

There are three types of directive tag

S.No. Directive & Description

<%@ page ... %>


1
Defines page-dependent attributes, such as scripting language, error page, and buffering requirements.
<%@ include ... %>
2
Includes a file during the translation phase.
<%@ taglib ... %>
3
Declares a tag library, containing custom actions, used in the page

JSP - The page Directive

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.

Following is the basic syntax of the page directive

<%@ page attribute = "value" %>

You can write the XML equivalent of the above syntax as follows

<jsp:directive.page attribute = "value" />

The include Directive

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.

The general usage form of this directive is as follows

<%@ include file = "relative url" >


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

<jsp:directive.include file = "relative url" />

For more details related to include directive, check the Include Directive.

The taglib Directive

The JavaServer Pages API allow you to define custom JSP tags that look like HTML or XML tags and a tag library
is a set of user-defined tags that implement custom behavior.

The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and
provides means for identifying the custom tags in your JSP page.

The taglib directive follows the syntax given below

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

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:directive.taglib uri = "uri" prefix = "prefixOfTag" />

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

<jsp:action_name attribute = "value" />

Action elements are basically predefined functions. The following table lists out the available JSP actions

S.No. Syntax & Purpose

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.

The <jsp:include> Action

This action lets you insert files into the page being generated. The syntax looks like this

<jsp:include page = "relative URL" flush = "true" />

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

Following is the content of the date.jsp file

<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>

Following is the content of the main.jsp file

<html>
<head>
<title>The include Action Example</title>
</head>

<body>
<center>
<h2>The include action Example</h2>
<jsp: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 include action Example

Today's date: 12-Sep-2010 14:54:22

The <jsp:useBean> Action

The useBean action is quite versatile. It first searches for an existing object utilizing the id and scope variables. If an
object is not found, it then tries to create the specified object.

The simplest way to load a bean is as follows

<jsp:useBean id = "name" class = "package.class" />


Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to modify and retrieve the
bean properties.

Following table lists out the attributes associated with the useBean action

S.No. Attribute & Description

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 <jsp:getProperty> Action

The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts
it into the output.

The getProperty action has only two attributes, both of which are required. The syntax of the getProperty action is as
follows

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


...
<jsp:getProperty name = "myName" property = "someProperty" .../>

Following table lists out the required attributes associated with the getProperty action

S.No. Attribute & Description

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";

public String getMessage() {


return(message);
}
public void setMessage(String 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 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

Using JavaBeans in JSP

Got message....
Hello JSP...

The <jsp:forward> Action

The forward action terminates the action of the current page and forwards the request to another resource such as a
static page, another JSP page, or a Java Servlet.

Following is the syntax of the forward action


<jsp:forward page = "Relative URL" />

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

S.No. Attribute & Description

page
1
Should consist of a relative URL of another resource such as a static page, another JSP page, or a Java
Servlet.
Example

Let us reuse the following two files (a) date.jsp and (b) main.jsp as follows

Following is the content of the date.jsp file

<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>

Following is the content of the main.jsp file

<html>
<head>
<title>The include Action Example</title>
</head>

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

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.

Today's date: 12-Sep-2010 14:54:22

The <jsp:plugin> Action

The plugin action is used to insert Java components into a JSP page. It determines the type of browser and inserts
the <object> or <embed> tags as needed.

If the needed plugin is not present, it downloads the plugin and then executes the Java component. The Java
component can be either an Applet or a JavaBean.

The plugin action has several attributes that correspond to common HTML tags used to format Java components.
The <param> element can also be used to send parameters to the Applet or Bean.
Following is the typical syntax of using the plugin action

<jsp:plugin type = "applet" codebase = "dirname" code = "MyApplet.class"


width = "60" height = "80">
<jsp:param name = "fontcolor" value = "red" />
<jsp:param name = "background" value = "black" />

<jsp:fallback>
Unable to initialize Java Plugin
</jsp:fallback>

</jsp:plugin>

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> Action

The <jsp:attribute> Action

The <jsp:body> Action

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.

Following is a simple example to define XML elements dynamically

<%@page language = "java" contentType = "text/html"%>


<html xmlns = "http://www.w3c.org/1999/xhtml"
xmlns:jsp = "http://java.sun.com/JSP/Page">

<head><title>Generate XML Element</title></head>

<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

<html xmlns = "http://www.w3c.org/1999/xhtml" xmlns:jsp =


"http://java.sun.com/JSP/Page">
<head><title>Generate XML Element</title></head>

<body>
<xmlElement xmlElementAttr = "Value for the attribute">
Body for XML element
</xmlElement>
</body>
</html>

The response Object

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

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

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

public void response.sendRedirect(String location)


throws IOException

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

<%@ page import = "java.io.*,java.util.*" %>

<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.

Following is the syntax to set a variable at application level

application.setAttribute(String Key, Object Value);

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.

<%@ page import = "java.io.*,java.util.*" %>

<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

Welcome back to my website!

Total number of visits: 12

Auto Page Refresh Example

In the following example, we will use the setIntHeader() method to set Refresh header. This will help simulate a
digital clock

<%@ page import = "java.io.*,java.util.*" %>

<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);

// Get current time


Calendar calendar = new GregorianCalendar();
String am_pm;

int hour = calendar.get(Calendar.HOUR);


int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);

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.

Send a Simple Email


Here is an example to send a simple 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.

<%@ page import = "java.io.*,java.util.*,javax.mail.*"%>


<%@ page import = "javax.mail.internet.*,javax.activation.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>

<%
String result;

// Recipient's email ID needs to be mentioned.


String to = "abcd@gmail.com";

// Sender's email ID needs to be mentioned


String from = "mcmohd@gmail.com";

// Assuming you are sending email from localhost


String host = "localhost";

// Get system properties object


Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);

// Get the default Session object.


Session mailSession = Session.getDefaultInstance(properties);

try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(mailSession);

// Set From: header field of the header.


message.setFrom(new InternetAddress(from));

// Set To: header field of the header.


message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");

// Now set the actual message


message.setText("This is actual message");

// 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>

<p align = "center">


<%
out.println("Result: " + result + "\n");
%>
</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 abcd@gmail.com. You
will receive the following response

Send Email using JSP


Result: Sent message successfully....

If you want to send an email to multiple recipients, then use the following methods to specify multiple email IDs

void addRecipients(Message.RecipientType type, Address[] addresses)


throws MessagingException

Here is the description of the parameters

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

Send an HTML Email

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.

<%@ page import = "java.io.*,java.util.*,javax.mail.*"%>


<%@ page import = "javax.mail.internet.*,javax.activation.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>

<%
String result;

// Recipient's email ID needs to be mentioned.


String to = "abcd@gmail.com";

// Sender's email ID needs to be mentioned


String from = "mcmohd@gmail.com";

// Assuming you are sending email from localhost


String host = "localhost";

// Get system properties object


Properties properties = System.getProperties();

// Setup mail server


properties.setProperty("mail.smtp.host", host);

// Get the default Session object.


Session mailSession = Session.getDefaultInstance(properties);

try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(mailSession);

// Set From: header field of the header.


message.setFrom(new InternetAddress(from));

// Set To: header field of the header.


message.addRecipient(Message.RecipientType.TO, new
InternetAddress(to));

// Set Subject: header field


message.setSubject("This is the Subject Line!");

// Send the actual HTML message, as big as you like


message.setContent("<h1>This is actual message</h1>", "text/html" );

// 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>

<p align = "center">


<%
out.println("Result: " + result + "\n");
%>
</p>
</body>
</html>

Let us now use the above JSP to send HTML message on a given email ID.

Send Attachment in Email

Following is an example to send an email with attachment from your machine

<%@ page import = "java.io.*,java.util.*,javax.mail.*"%>


<%@ page import = "javax.mail.internet.*,javax.activation.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>

<%
String result;

// Recipient's email ID needs to be mentioned.


String to = "abcd@gmail.com";

// Sender's email ID needs to be mentioned


String from = "mcmohd@gmail.com";

// Assuming you are sending email from localhost


String host = "localhost";

// Get system properties object


Properties properties = System.getProperties();

// Setup mail server


properties.setProperty("mail.smtp.host", host);

// Get the default Session object.


Session mailSession = Session.getDefaultInstance(properties);

try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(mailSession);

// Set From: header field of the header.


message.setFrom(new InternetAddress(from));

// Set To: header field of the header.


message.addRecipient(Message.RecipientType.TO, new
InternetAddress(to));

// Set Subject: header field


message.setSubject("This is the Subject Line!");

// Create the message part


BodyPart messageBodyPart = new MimeBodyPart();

// Fill the message


messageBodyPart.setText("This is message body");

// Create a multipart message


Multipart multipart = new MimeMultipart();

// Set text message part


multipart.addBodyPart(messageBodyPart);

// Part two is attachment


messageBodyPart = new MimeBodyPart();

String filename = "file.txt";


DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);

// Send the complete message parts


message.setContent(multipart );

// 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>

<p align = "center">


<%out.println("Result: " + result + "\n");%>
</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.

Using Forms to Send Email

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.

You might also like