Java Server Pages Tutorial
Java Server Pages Tutorial
Tutorial
tutorialspoint
.com
JSP Tutorial
Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platformindependent method for building Web-based applications. JSP have access to the entire family of Java APIs,
including the JDBC API to access enterprise databases.
This tutorial will teach you how to use Java Server Pages to develop your web applications in simple and easy
steps.
Audience
This tutorial has been prepared for the beginners to help them understand basic functionality of Java Server
Pages (JSP) to develop your web applications. After completing this tutorial you will find yourself at a moderate
level of expertise in using JSP from where you can take yourself to next levels.
Prerequisites
We assume you have little knowledge how web application work over HTTP, what is web server and what is web
browsers. It will be great if you have some knowledge of web application development using any programming
language.
TUTORIALS POINT
Simply Easy Learning
Table of Content
JSP Tutorial................................................................................2
Audience....................................................................................2
Prerequisites..............................................................................2
Copyright & Disclaimer Notice...................................................2
JSP Overview............................................................................9
Why Use JSP?................................................................................9
Advantages of JSP:......................................................................10
JSP Architecture......................................................................15
JSP Processing:............................................................................15
Compilation:..........................................................................18
Initialization:..........................................................................18
Execution:.............................................................................18
Cleanup:................................................................................19
JSP Syntax..............................................................................20
The Scriptlet:...............................................................................20
JSP Declarations:.........................................................................21
JSP Expression:............................................................................21
JSP Comments:............................................................................22
A Test of Comments................................................................................22
JSP Directives:.............................................................................23
JSP Actions:.................................................................................23
JSP Implicit Objects:....................................................................24
Control-Flow Statements:............................................................24
Decision-Making Statements:.....................................................24
Loop Statements:........................................................................25
JSP Operators:.............................................................................26
JSP Literals:.................................................................................27
JSP Directives.........................................................................28
The page Directive:.....................................................................28
Attributes:...................................................................................29
The include Directive:.................................................................29
The taglib Directive:....................................................................30
TUTORIALS POINT
Simply Easy Learning
JSP Actions..............................................................................31
Common Attributes:....................................................................31
The <jsp:include> Action............................................................32
Example:.....................................................................................32
The include action Example...................................................................33
The <jsp:useBean> Action.........................................................33
The <jsp:setProperty> Action.....................................................33
The <jsp:getProperty> Action.....................................................34
Example:.....................................................................................34
Using JavaBeans in JSP.........................................................................35
The <jsp:forward> Action...........................................................35
Example:.....................................................................................35
The <jsp:plugin> Action.............................................................36
The <jsp:element> Action..........................................................37
The <jsp:attribute> Action.........................................................37
The <jsp:body> Action...............................................................37
The <jsp:text> Action.................................................................37
request Object:.....................................................................39
response Object:..................................................................40
out Object:...........................................................................40
session Object:.....................................................................40
application Object:...............................................................40
config Object:.......................................................................40
pageContext Object:............................................................41
page Object:.........................................................................41
exception Object:.................................................................41
GET method:...............................................................................54
POST method:.............................................................................54
Reading Form Data using JSP......................................................54
GET Method Example Using URL:................................................55
Welcome to my website........................................................73
Session Infomation.................................................................................73
JSP JSTL..............................................................................95
Install JSTL Library:......................................................................95
Core Tags:...................................................................................95
Formatting tags:..........................................................................96
SQL tags:.....................................................................................97
XML tags:....................................................................................97
JSTL Functions:............................................................................98
INSERT Operation:.....................................................................102
DELETE Operation:....................................................................103
UPDATE Operation:....................................................................104
JSP JavaBeans..................................................................110
JavaBeans Properties:................................................................110
JavaBeans Example:..................................................................110
Accessing JavaBeans:................................................................111
Accessing JavaBeans Properties:...............................................112
Opps.....................................................................................127
Using Try
.............Catch Block:.................................................................127
JSP Debugging...................................................................128
Using System.out.println():........................................................128
Using the JDB Logger:................................................................129
Debugging Tools:.......................................................................130
Using JDB Debugger:.................................................................130
Using Comments:......................................................................131
Client and Server Headers:........................................................131
Important Debugging Tips:........................................................131
TUTORIALS POINT
Simply Easy Learning
JSP Security.......................................................................132
Role Based Authentication:....................................................... 132
Form Based Authentication:......................................................133
Programmatic Security in a Servlet/JSP:....................................135
JSP Internationalization......................................................136
Detecting Locale:.......................................................................136
Example:...................................................................................137
Languages Setting:....................................................................137
Locale Specific Dates:................................................................138
Locale Specific Currency............................................................138
Locale Specific Percentage........................................................139
TUTORIALS POINT
Simply Easy Learning
CHAPTER
JSP Overview
ava Server Pages (JSP) is a technology for developing web pages that support dynamic content which
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 web page forms, present records from a database or another
source, and create web pages 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.
TUTORIALS POINT
Simply Easy Learning
Advantages of JSP:
Following is the list of other advantages of using JSP over other technologies:
vs. Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part is written in
Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use. Second, it
is portable to other operating systems and non-Microsoft Web servers.
vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.
vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for "real" programs
that use form data, make database connections, and the like.
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.
vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
development environment is where you would develop your JSP programs, test them and finally run
them.
This chapter will guide you to setup your JSP development environment which involves following steps:
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Further information about configuring and running Tomcat can be found in the documentation included here, as
well as on the Tomcat web site: http://tomcat.apache.org
Tomcat can be stopped by executing the following commands on windows machine:
%CATALINA_HOME%\bin\shutdown
or
C:\apache-tomcat-5.5.29\bin\shutdown
Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine:
$CATALINA_HOME/bin/shutdown.sh
or
/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%
TUTORIALS POINT
Simply Easy Learning
Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then
Advanced, then Environment Variables. Then, you would update the CLASSPATH value and press the OK button.
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
NOTE: Assuming that your development directory is C:\JSPDev (Windows) or /usr/JSPDev (Unix) then you would
need to add these directories as well in CLASSPATH in similar way as you have added above.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
JSP Architecture
he web server needs a JSP engine ie. container to process JSP pages. The JSP container is responsible
for intercepting requests for JSP pages. This tutorial makes use of Apache which has built-in JSP container to
support JSP pages development.
A JSP container works with the Web server to provide the runtime environment and other services a JSP needs. It
knows how to understand the special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web Application.
JSP Processing:
The following steps explain how the web server creates the web page 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 that implements the corresponding dynamic behavior of the page.
TUTORIALS POINT
Simply Easy Learning
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, which the servlet engine passes to the web server inside an
HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML content.
Finally 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 shown below 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 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
TUTORIALS POINT
CHAPTER
his chapter will explain how to install Hibernate and other associated packages to prepare a develop
environment for the Hibernate applications. We will work with MySQL database to experiment with Hibernate
examples, so make sure you already have setup for MySQL database. For a more detail on MySQL you can
check our MySQL Tutorial.
The key to understanding the low-level functionality of JSP is to understand the simple life cycle they follow.
A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a
servlet life cycle with an additional step which is required to compile a JSP into servlet.
The following are the paths followed by a JSP
Compilation
Initialization
Execution
Cleanup
The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows:
TUTORIALS POINT
Simply Easy Learning
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 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:
public void jspInit(){
// 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.
JSP Execution:
This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
TUTORIALS POINT
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)
}
The _jspService() method of a JSP is invoked once per a request and 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 ie.
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.
}
TUTORIALS POINT
Simply Easy Learning
CHAPTER
JSP Syntax
his chapter will give basic idea on simple syntax (ie. elements) involved with JSP development:
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 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 above code in JSP file hello.jsp and put this file in C:\apache-tomcat-7.0.2\webapps\ROOTdirectory
and try to browse it by giving URL http://localhost:8080/hello.jsp. This would generate following result:
TUTORIALS POINT
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 of JSP Declarations:
<%! declaration; [ declaration; ]+ ... %>
You can write XML equivalent of the above syntax as follows:
<jsp:declaration>
code fragment
</jsp:declaration>
Following is the simple 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 XML equivalent of the above syntax as follows:
TUTORIALS POINT
<jsp:expression>
expression
</jsp:expression>
Following is the simple example for JSP Expression:
<html>
<head><title>A Comment Test</title></head>
<body>
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body>
</html>
This would generate following result:
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" part of your JSP page.
Following is the syntax of JSP comments:
<%-- This is JSP comment --%>
Following is the simple example for 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>
This would generate 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:
Syntax
Purpose
TUTORIALS POINT
Simply Easy Learning
<\%
%\>
\'
\"
JSP Directives:
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:
Directive
Description
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 and there are following JSP actions available:
Syntax
Purpose
jsp:include
jsp:include
jsp:useBean
jsp:setProperty
jsp:getProperty
jsp:forward
jsp:plugin
Generates browser-specific code that makes an OBJECT or EMBED tag for the
Java plugin
jsp:element
TUTORIALS POINT
Simply Easy Learning
jsp:attribute
jsp:body
jsp:text
Description
request
response
This is the HttpServletResponse object associated with the response to the client.
out
session
application
config
pageContext
page
This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.
Exception
The Exception object allows the exception data to be accessed by designated JSP.
We would explain JSP Implicit Objects in separate chapter JSP - Implicit Objects.
Control-Flow Statements:
JSP provides full power of Java to be embedded in your web application. 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 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>
TUTORIALS POINT
Simply Easy Learning
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>
This would produce following result:
It's Wednesday.
Loop Statements:
You can also use three basic types of looping blocks in Java: for, while,and dowhile blocks in your JSP
programming.
Let us look at the following for loop example:
<%! int fontSize; %>
<html>
<head><title>FOR LOOP Example</title></head>
<body>
<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>
TUTORIALS POINT
Simply Easy Learning
JSP Tutorial
JSP Tutorial
</body>
</html>
JSP Tutorial
JSP Tutorial
JSP Operators:
JSP supports all the logical and arithmetic operators supported by Java. Following table give a list of 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
TUTORIALS POINT
Simply Easy Learning
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
I will consider XML formatted file hibernate.cfg.xml to specify required Hibernate properties in my examples.
Most of the properties take their default values and it is not required to specify them in the property file unless it is
really required. This file is kept in the root directory of your application's classpath.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
JSP Directives
SP directives provide directions and instructions to the container, telling it how to handle certain aspects of
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.
There are three types of directive tag:
Directive
Description
TUTORIALS POINT
Simply Easy Learning
Attributes:
Following is the list of attributes associated with page directive:
Attribute
Purpose
buffer
autoFlush
contentType
errorPage
Defines the URL of another JSP that reports on Java unchecked runtime exceptions.
isErrorPage
Indicates if this JSP page is a URL specified by another JSP page's errorPage
attribute.
extends
import
Specifies a list of packages or classes for use in the JSP as the Java import
statement does for Java classes.
info
Defines a string that can be accessed with the servlet's getServletInfo() method.
isThreadSafe
language
session
isELIgnored
Specifies whether or not EL expression within the JSP page will be ignored.
isScriptingEnabled
Check more detail related to all the above attributes at Page Directive.
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
JSP Actions
SP 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 and there are following JSP actions available:
Syntax
Purpose
jsp:include
jsp:include
jsp:useBean
jsp:setProperty
jsp:getProperty
jsp:forward
jsp:plugin
Generates browser-specific code that makes an OBJECT or EMBED tag for the
Java plugin
jsp:element
jsp:attribute
jsp:body
jsp:text
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
TUTORIALS POINT
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.
Description
page
flush
The boolean attribute determines whether the included resource has its buffer
flushed before it is included.
Example:
Let us define following two files (a)date.jps and (b) main.jsp as follows:
Following is the content of date.jsp file:
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
Here is the content of 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>
Now let us keep all these files in root directory and try to access main.jsp. This would display result something like
this:
TUTORIALS POINT
Simply Easy Learning
Description
class
type
Specifies the type of the variable that will refer to the object.
beanName
Gives the name of the bean as specified by the instantiate () method of the
java.beans.Beans class.
Let us discuss about jsp:setProperty and jsp:getProperty actions before giving a valid example related to these
actions.
TUTORIALS POINT
Description
name
Designates the bean whose property will be set. The Bean must have been
previously defined.
property
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
The value that is to be assigned to the given property. The the parameter's value is
null, or the parameter does not exist, the setProperty action is ignored.
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.
Description
name
The name of the Bean that has a property to be retrieved. The Bean must have been
previously defined.
property
Example:
Let us define a test bean which we will use 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;
}
}
TUTORIALS POINT
Simply Easy Learning
Compile above code to generated TestBean.class file and make sure that you copied TestBean.class in
C:\apache-tomcat-7.0.2\webapps\WEB-INF\classes\action folder and CLASSPATH variable should also be set to
this folder:
Now use the following code in main.jsp file which 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>
Now try to access main.jsp, it would display following result:
Description
page
Should consist of a relative URL of another resource such as a static page, another
JSP page, or a Java Servlet.
Example:
Let us reuse following two files (a) date.jps and (b) main.jsp as follows:
Following is the content of date.jsp file:
TUTORIALS POINT
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
Here is the content of 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>
Now let us keep all these files in root directory and try to access main.jsp. This would display result something like
as below. Here it discarded content from main page and displayed content from forwarded page only.
Today's date: 12-Sep-2010 14:54:22
<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.
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
<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:
<jsp:text><![CDATA[<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN" "DTD/xhtml1-strict.dtd">]]>
</jsp:text>
<head><title>jsp:text
action</title></head> <body>
<books><book><jsp:text> Welcome
to JSP Programming
</jsp:text></book></books>
</body>
</html>
TUTORIALS POINT
Simply Easy Learning
CHAPTER
SP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page
and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called predefined variables.
JSP supports nine Implicit Objects which are listed below:
Object
Description
request
response
This is the HttpServletResponse object associated with the response to the client.
out
session
application
config
pageContext
page
This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.
Exception
TUTORIALS POINT
Simply Easy Learning
Description
out.print(dataType dt)
out.println(dataType dt)
Print a data type value then terminate the line with new line character.
out.flush()
TUTORIALS POINT
This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the
paths or file locations etc.
The following config method is the only one you might ever use, and its usage is trivial:
config.getServletName();
This returns the servlet name, which is the string contained in the <servlet-name> element defined in the WEBINF\web.xml file
pageContext.removeAttribute("attrName", PAGE_SCOPE);
You can check a very good usage of pageContext in coming chapter: JSP - File Uploading.
TUTORIALS POINT
Simply Easy Learning
CHAPTER .
9
JSP Client Request
hen a browser requests for a web page, it sends lot of information to the web server which can not
be read directly because this information travel as a part of header of HTTP request. You can check HTTP
Protocol for more information on this.
Following is the important header information which comes from browser side and you would use very frequently
in web programming:
Header
Description
Accept
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
This header specifies the character sets the browser can use to display the
information. For example ISO-8859-1.
Accept-Encoding
This header specifies the types of encodings that the browser knows how to
handle. Values of gzip or compress are the two most common possibilities.
Accept-Language
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
This header is used by clients to identify themselves when accessing passwordprotected Web pages.
Connection
This header indicates whether the client can handle persistent HTTP connections.
Persistent connections permit the client or other browser to retrieve multiple files
with a single request. A value ofKeep-Alive means that persistent connections
should be used
Content-Length
This header is applicable only to POST requests and gives the size of the POST
data in bytes.
Cookie
This header returns cookies to servers that previously sent them to the browser.
Host
This header specifies the host and port as given in the original URL.
If-Modified-Since
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
This header is the reverse of If-Modified-Since; it specifies that the operation should
TUTORIALS POINT
This header identifies the browser or other client making the request and can be
used to return different content to different types of browsers.
Enumeration getParameterNames()
Returns an Enumeration of String objects containing the names of the parameters contained in this
request.
HttpSession getSession()
Returns the current session associated with this request, or if the request does not have a session, creates
one.
HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request or, if if there is no current session and create
is true, returns a new session.
Locale getLocale()
Returns the preferred Locale that the client will accept content in, based on the Accept-Language header
Object getAttribute(String name)
Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.
ServletInputStream getInputStream()
Retrieves the body of the request as binary data using a ServletInputStream.
10
11
12
String getAuthType()
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()
Returns the name of the character encoding used in the body of this request.
String getContentType()
Returns the MIME type of the body of the request, or null if the type is not known.
TUTORIALS POINT
Simply Easy Learning
13
14
String getContextPath()
Returns the portion of the request URI that indicates the context of the request.
String getHeader(String name)
Returns the value of the specified request header as a String.
15
16
17
18
19
20
21
22
23
String getMethod()
Returns the name of the HTTP method with which this request was made, for example, GET, POST, or
PUT.
String getParameter(String name)
Returns the value of a request parameter as a String, or null if the parameter does not exist.
String getPathInfo()
Returns any extra path information associated with the URL the client sent when it made this request.
String getProtocol()
Returns the name and version of the protocol the request.
String getQueryString()
Returns the query string that is contained in the request URL after the path.
String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client that sent the request.
String getRemoteHost()
Returns the fully qualified name of the client that sent the request.
String getRemoteUser()
Returns the login of the user making this request, if the user has been authenticated, or null if the user has
not been authenticated.
String getRequestURI()
24
Returns the part of this request's URL from the protocol name up to the query string in the first line of the
HTTP request.
String getRequestedSessionId()
25
26
27
Returns an array of String objects containing all of the values the given request parameter has, or null if
the parameter does not exist.
boolean isSecure()
Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.
29
int getContentLength()
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 getIntHeader(String name)
30
28
TUTORIALS POINT
Simply Easy Learning
while(headerNames.hasMoreElements()) {
String paramName = (String)headerNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
%>
</table>
</center>
</body>
</html>
Now put the above code in main.jsp and try to access it. This would produce result something as follows:
Header Value(s)
accept
*/*
accept-language
en-us
user-agent
accept-encoding
gzip, deflate
host
localhost:8080
connection
Keep-Alive
cache-control
no-cache
To become more comfortable with other methods you can try few more above listed methods in the same fashion.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
10
JSP Server Response
hen a Web server responds to a HTTP request to the browser, the response typically consists of a
status line, some response headers, a blank line, and the document. A typical response looks like this:
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!doctype ...>
<html>
<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).
Following is a summary of the most useful HTTP 1.1 response headers which go back to the browser from web
server side and you would use them very frequently in web programming:
Header
Description
Allow
This header specifies the request methods (GET, POST, etc.) that the server
supports.
Cache-Control
This header specifies the circumstances in which the response document can safely
be cached. It can have values public, private orno-cache etc. Public means
document is cacheable, Private means document is for a single user and can only
be stored in private (nonshared) caches and no-cache means document should
never be cached.
Connection
This header instructs the browser whether to use persistent in HTTP connections or
not. A value of close instructs the browser not to use persistent HTTP connections
and keep-alive means using persistent connections.
Content-Disposition
This header lets you request that the browser ask the user to save the response to
TUTORIALS POINT
Simply Easy Learning
This header specifies the way in which the page was encoded during transmission.
Content-Language
This header signifies the language in which the document is written. For example en,
en-us, ru, etc.
Content-Length
This header indicates the number of bytes in the response. This information is
needed only if the browser is using a persistent (keep-alive) HTTP connection.
Content-Type
This header gives the MIME (Multipurpose Internet Mail Extension) type of the
response document.
Expires
This header specifies the time at which the content should be considered out-of-date
and thus no longer be cached.
Last-Modified
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 in the
300s. This notifies the browser of the document address. The browser automatically
reconnects to this location and retrieves the new document.
Refresh
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
This header can be used in conjunction with a 503 (Service Unavailable) response
to tell the client how soon it can repeat its request.
Set-Cookie
Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the
URL unchanged.
String encodeURL(String url)
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL
unchanged.
boolean containsHeader(String name)
Returns a boolean indicating whether the named response header has already been set.
boolean isCommitted()
Returns a boolean indicating if the response has been committed.
void addCookie(Cookie cookie)
Adds the specified cookie to the response.
TUTORIALS POINT
Simply Easy Learning
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP ContentLength header.
void setContentType(String type)
Sets the content type of the response being sent to the client, if the response has not been committed yet.
void setDateHeader(String name, long date)
Sets a response header with the given name and date-value.
void setHeader(String name, String value)
Sets a response header with the given name and value.
void setIntHeader(String name, int value)
Sets a response header with the given name and integer value.
void setLocale(Locale loc)
Sets the locale of the response, if the response has not been committed yet.
void setStatus(int sc)
Sets the status code for this response.
TUTORIALS POINT
Simply Easy Learning
</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("Current Time is: " + CT + "\n");
%>
</center>
</body>
</html>
Now put the above code in main.jsp and try to access it. This would display current system time after every 5
seconds as follows. Just run the JSP and wait to see the result:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
11
HTTP Status Codes
he format of the HTTP request and HTTP response messages are similar and will have following
structure:
An initial status line + CRLF ( Carriage Return + Line Feed ie. New Line )
Zero or more header lines + CRLF
A blank line ie. a CRLF
An optional message body like file, query data or query output.
For example, a server response header looks as follows:
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!doctype ...>
<html>
<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).
Following is a list of HTTP status codes and associated messages that might be returned from the Web Server:
Code: Message:
Description:
100
Continue
Only a part of the request has been received by the server, but as long as
it has not been rejected, the client should continue with the request
101
Switching Protocols
TUTORIALS POINT
200
OK
The request is OK
201
Created
202
Accepted
The request is accepted for processing, but the processing is not complete.
203
Non-authoritative
Information
204
No Content
205
Reset Content
206
Partial Content
300
Multiple Choices
A link list. The user can select a link and go to that location. Maximum five
addresses
301
Moved Permanently
302
Found
303
See Other
304
Not Modified
305
Use Proxy
306
Unused
This code was used in a previous version. It is no longer used, but the
code is reserved.
307
Temporary Redirect
400
Bad Request
401
Unauthorized
402
Payment Required
403
Forbidden
404
Not Found
405
406
Not Acceptable
The server can only generate a response that is not accepted by the client.
407
Proxy Authentication
Required
You must authenticate with a proxy server before this request can be
served.
408
Request Timeout
The request took longer than the server was prepared to wait.
409
Conflict
410
Gone
411
Length Required
The "Content-Length" is not defined. The server will not accept the request
without it.
412
Precondition Failed
413
The server will not accept the request, because the request entity is too
large.
414
The server will not accept the request, because the url is too long. Occurs
TUTORIALS POINT
Simply Easy Learning
when you convert a "post" request to a "get" request with a long query
information.
415
417
Expectation Failed
500
The request was not completed. The server met an unexpected condition
501
Not Implemented
The request was not completed. The server did not support the
functionality required.
502
Bad Gateway
The request was not completed. The server received an invalid response
from the upstream server
503
The server will not accept the request, because the media type is not
supported.
Service Unavailable
504
Gateway Timeout
505
1
2
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.
TUTORIALS POINT
Simply Easy Learning
APACHE TOMCAT/5.5.29
To become more comfortable with HTTP status codes, try to set different status codes and their description.
TUTORIALS POINT
CHAPTER
12
JSP Form Processing
ou must have come across many situations when you need to pass some information from your browser
to web server and ultimately to your backend program. The browser uses two methods to pass this information to
web server. These methods are GET Method and POST Method.
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 browser to web server and it produces a long
string that appears in your browser's Location:box. Never use the GET method 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.
This information is passed using QUERY_STRING header and will be accessible through QUERY_STRING
environment variable which can be handled using getQueryString() and getParameter() methods of request
object.
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 GET methods, 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.
TUTORIALS POINT
Simply Easy Learning
getParameter(): You call request.getParameter() method to get the value of a form parameter.
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.
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
Now type http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI in your browser's Location:box. This
would generate following result:
TUTORIALS POINT
Keep this HTML in a file Hello.htm and put it in <Tomcat-installation-directory>/webapps/ROOT directory. When
you would access http://localhost:8080/Hello.htm, here is the actual output of the above form.
First Name:
Last Name:
Try to enter First Name and Last Name and then click 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.
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
Following is the content of Hello.htm file:
<html>
<body>
<form action="main.jsp" method="POST">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Now let us keep main.jsp and hello.htm in <Tomcat-installation-directory>/webapps/ROOT directory. When you
would access http://localhost:8080/Hello.htm, below is the actual output of the above form.
TUTORIALS POINT
Simply Easy Learning
First Name:
Last Name:
Try to enter First and Last Name and then click submit button to see the result on your local machine where
tomcat is running.
Based on the input provided, it would generate similar result as mentioned in the above examples.
Physics
Chemistry
Below is main.jsp JSP program to handle input given by web browser for checkbox button.
<html>
<head>
<title>Reading Checkbox
Data</title> </head>
<body>
<center>
<h1>Reading Checkbox Data</h1>
<ul>
<li><p><b>Maths Flag:</b>
<%= request.getParameter("maths")%>
</p></li>
<li><p><b>Physics Flag:</b>
<%= request.getParameter("physics")%>
</p></li>
<li><p><b>Chemistry Flag:</b>
<%= request.getParameter("chemistry")%>
</p></li>
</ul>
</body>
</html>
TUTORIALS POINT
Simply Easy Learning
%>
</table>
</center>
</body>
</html>
Following is the content of Hello.htm:
<html>
<body>
<form action="main.jsp" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics" /> Physics
<input type="checkbox" name="chemistry" checked="checked" /> Chem
<input type="submit" value="Select Subject" />
</form>
</body>
</html>
TUTORIALS POINT
Simply Easy Learning
Now try calling JSP using above Hello.htm, this would generate a result something like as below based on the
provided input:
Param Value(s)
maths
on
chemistry
on
You can try above JSP to read any other form's data which is having other objects like text box, radio button or
drop down box etc.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
13
JSP Filters
ervlet 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.
There are various types of filters suggested by the specifications:
Authentication Filters.
Data compression Filters
Encryption Filters .
Filters that trigger resource access events.
Image Conversion Filters .
Logging and Auditing Filters.
MIME-TYPE Chain Filters.
Tokenizing Filters .
XSL/T Filters That Transform XML Content.
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.
When the JSP container starts up your web application, it creates an instance of each filter that you have declared
in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.
TUTORIALS POINT
Simply Easy Learning
This method is called by the web container to indicate to a filter that it is being placed into service.
public void destroy()
This method is called by the web container to indicate to a filter that it is being taken out of service.
java
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
/
Implements Filter class
public class LogFilter implements Filter {
public void init(FilterConfig config)
throws ServletException{
// Get init parameter
String testParam = config.getInitParameter("test-param");
//Print the init parameter
System.out.println("Test Param: " + testParam);
}
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws java.io.IOException, ServletException {
/ Get the IP address of client machine.
String ipAddress = request.getRemoteAddr();
/ Log the IP address and current timestamp.
System.out.println("IP "+ ipAddress + ", Time "
+ new Date().toString());
/
Pass request back down the filter chain
chain.doFilter(request,response);
}
public void destroy( ){
/* Called before the Filter instance is removed
from service by the web container*/
}
TUTORIALS POINT
Simply Easy Learning
}
Compile LogFilter.java in usual way and put your LogFilter.class class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes.
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The above filter would apply to all the servlets and JSP because we specified /* in our configuration. You can
specify a particular servlet or JSP path if you want to apply filter on few servlets or JSP only.
Now try to call any servlet or JSP in usual way and you would see generated log in you web server log. You can
use Log4J logger to log above log in a separate file.
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
14
JSP Cookies Handling
ookies are text files stored on the client computer and they are kept for various information tracking
purpose. JSP transparently supports HTTP cookies using underlying servlet technology.
There are three steps involved in identifying returning users:
Server script sends a set of cookies to the browser. For example name, age, or identification number etc.
Browser stores this information on local machine for future use.
When next time browser sends any request to 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.
TUTORIALS POINT
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A JSP script will then have access to the cookies through the request method request.getCookies()which returns
an array of Cookie objects.
4
5
8
9
10
This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e.
SSL) connections.
public void setComment(String purpose)
11
This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser
presents the cookie to the user.
public String getComment()
This method returns the comment describing the purpose of this cookie, or null if the cookie has no
12
TUTORIALS POINT
Simply Easy Learning
comment.
Example:
Let us modify our Form Example to set the cookies for first and last name.
<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name",
request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name",
request.getParameter("last_name"));
/
Set expiry date after 24 Hrs for both the
cookies. firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
%>
/
Add both the cookies in the response header.
response.addCookie( firstName );
response.addCookie( lastName );
<html>
<head>
<title>Setting Cookies</title>
</head>
<body>
<center>
<h1>Setting Cookies</h1>
</center>
<ul>
<li><p><b>First Name:</b>
TUTORIALS POINT
Simply Easy Learning
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
Let us put above code in main.jsp file and use it in the following HTML page:
<html>
<body>
<form action="main.jsp" method="GET">
First Name: <input type="text" name="first_name">
<br />
</form>
</body>
</html>
Keep above HTML content in a file hello.jsp and put hello.jsp and main.jsp in <Tomcat-installationdirectory>/webapps/ROOT directory. When you would access http://localhost:8080/hello.jsp, here is the actual
output of the above form.
First Name:
Last Name:
Try to enter First Name and Last Name and then click submit button. This would display first name and last name
on your screen and same time it would set two cookies firstName and lastName which would be passed back to
the server when next time you would press Submit button.
Next section would explain you how you would access these cookies back in your web application.
Example:
Let us read cookies which we have set in previous example:
<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
TUTORIALS POINT
</center>
<%
%>
}
}else{
out.println("<h2>No cookies founds</h2>");
}
</body>
</html>
Now let us put above code in main.jsp file and try to access it. If you would have set first_name cookie as "John"
and last_name cookie as "Player" then running http://localhost:8080/main.jsp would display the following result:
Example:
Following example would delete and existing cookie named "first_name" and when you would run main.jsp JSP
next time it would return null value for first_name.
<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
TUTORIALS POINT
Simply Easy Learning
response.addCookie(cookie);
out.print("Deleted cookie: " +
cookie.getName( ) + "<br/>");
}
}else{
out.println(
"<h2>No cookies founds</h2>");
}
%>
</body>
</html>
Now let us put above code in main.jsp file and try to access it. It would display the following result:
TUTORIALS POINT
CHAPTER
15
JSP Session Tracking
TTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a
separate connection to the Web server and the server automatically does not keep any record of previous client
request.
Still there are following three ways to maintain session between web client and web server:
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 because many time browser does not support a cookie, so I would not
recommend to use this procedure to maintain the sessions.
URL Rewriting:
You can append some extra data on the end of each URL that identifies the session, and the server can associate
that session identifier with data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as
sessionid=12345 which can be accessed at the web server to identify the client.
TUTORIALS POINT
URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies
but here drawback is that you would have generate every URL dynamically to assign a session ID though page is
simple static HTML page.
This method returns the time when this session was created, measured in milliseconds since midnight
January 1, 1970 GMT.
public String getId()
This method returns a string containing the unique identifier assigned to this session.
This method returns true if the client does not yet know about the session or if the client chooses not to join
the session.
public void removeAttribute(String name)
This method removes the object bound with the specified name from this session.
public void setAttribute(String name, Object value)
This method binds an object to this session, using the name specified.
10
TUTORIALS POINT
11
%>
<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>
<td><% out.print( session.getId());
%></td> </tr>
<tr>
<td>Creation Time</td>
<td><% out.print(createTime); %></td>
</tr>
<tr>
<td>Time of Last Access</td>
<td><% out.print(lastAccessTime); %></td>
</tr>
TUTORIALS POINT
Simply Easy Learning
<tr>
<td>User ID</td>
<td><% out.print(userID);
%></td> </tr>
<tr>
<td>Number of visits</td>
<td><% out.print(visitCount); %></td>
</tr>
</table>
</body>
</html>
Now put above code in main.jsp and try to access http://localhost:8080/main.jsp. It would display the following
result when you would run for the first time:
Welcome to my website
Session Infomation
Session info
value
id
0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time
User ID
ABCD
Number of visits
Now try to run the same JSP for second time, it would display following result.
Session Infomation
info type
value
id
0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time
User ID
ABCD
Number of visits
TUTORIALS POINT
web.xml Configuration: If you are using Tomcat, apart from the above mentioned methods, you can
configure session time out in web.xml file as follows.
<session-config> <sessiontimeout>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
TUTORIALS POINT
Simply Easy Learning
CHAPTER
16
JSP File Uploading
JSP can be used with an HTML form tag to allow users to upload files to the server. An uploaded file
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
File Upload:
TUTORIALS POINT
Simply Easy Learning
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>
<description>Location to store uploaded
file</description> <param-name>file-upload</param-name>
<param-value> c:\apache-tomcat5.5.29\webapps\data\
</param-value>
</context-param>
....
</web-app>
Following is the source code for UploadFile.jsp which can handle multiple file uploading at a time. Before
proceeding you have make sure the followings:
Following example depends on FileUpload, so make sure you have the latest version ofcommonsfileupload.x.x.jar file in your classpath. You can download it fromhttp://commons.apache.org/fileupload/.
FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-x.x.jar file in
your classpath. You can download it from http://commons.apache.org/io/.
While testing following example, you should upload a file which has less size than maxFileSizeotherwise file
would not be uploaded.
Make sure you have created directories c:\temp and c:\apache-tomcat-5.5.29\webapps\data well in advance.
<%@ page import="java.io.*,java.util.*, javax.servlet.*" %> <
%@ page import="javax.servlet.http.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %> <%@
page import="org.apache.commons.fileupload.servlet.*" %> <%@
page import="org.apache.commons.io.output.*" %>
<%
File file ;
TUTORIALS POINT
Simply Easy Learning
out.println("<html>");
out.println("<head>");
out.println("<title>JSP File
upload</title>"); out.println("</head>");
out.println("<body>");
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
+ fileName + "<br>");
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
}else{
out.println("<html>");
TUTORIALS POINT
Simply Easy Learning
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
%>
Now try to upload files using the HTML form which you created above. When you would try
http://localhost:8080/UploadFile.htm, it would display following result which would help you uploading any file from
your local machine.
File Upload:
Select a file to upload: < >
TUTORIALS POINT
Simply Easy Learning
CHAPTER
17
JSP Handling Dates
ne of the most important advantages of using JSP is that you can use all the methods available in core
Java. This tutorial would take you through Java provided Date class which is available in java.util package, this
class encapsulates the current date and time.
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:
SN Methods with Description
boolean after(Date date)
1
Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise,
it returns false.
Object clone( )
Duplicates the invoking Date object.
int compareTo(Date date)
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.
Returns true if the invoking Date object contains the same time and date as the one specified by date,
otherwise, it returns false.
TUTORIALS POINT
9
10
long getTime( )
Returns the number of milliseconds that have elapsed since January 1, 1970.
int hashCode( )
Returns a hash code for the invoking object.
void setTime(long time)
Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight,
January 1, 1970
String toString( )
Converts the invoking Date object into a string and returns the result.
Date Comparison:
As I mentioned above you can use all the available Java methods in your JSP scripts. In case you need to
compare two dates, following are the methods:
You can use getTime( ) 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.
TUTORIALS POINT
Simply Easy Learning
You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by
Date.
Description
Example
Era designator
AD
2001
Month in year
July or 07
Day in month
10
12
22
Minute in hour
30
TUTORIALS POINT
Simply Easy Learning
Second in minute
55
Millisecond
234
Day in week
Tuesday
Day in year
360
Week in year
40
Week in month
A.M./P.M. marker
PM
24
10
Time zone
'
Delimiter
"
Single quote
For a complete list of constant available methods to manipulate date, you can refer to standard Java
documentation.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
18
JSP Page Redirection
age redirection is generally used when a document moves to a new location and we need to send the
client to this new location or may be because of load balancing, or for simple randomization.
The simplest way of redirecting a request to another page is using method sendRedirect() 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 setStatus() and setHeader() methods together to achieve the same redirection:
....
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>
<%
%>
</body>
</html>
TUTORIALS POINT
Simply Easy Learning
Now let us put above code in PageRedirect.jsp and call this JSP using URL
TUTORIALS POINT
Simply Easy Learning
CHAPTER
19
JSP Hit Counter
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 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 above method to set a hit counter variable and to reset the same variable. Following is the method to
read the variable set by previous method:
application.getAttribute(String Key);
Every time a use access your page, you can read current value of 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 total number of hits on a particular page. If you want to count
total number of hits of your website then you would have to include same code in all the JSP pages.
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Applcation object in JSP</title>
</head>
<body>
<%
Integer hitsCount =
(Integer)application.getAttribute("hitCounter");
if( hitsCount ==null || hitsCount == 0 )
{ /* First visit */
TUTORIALS POINT
Simply Easy Learning
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>
Now let us put above code in main.jsp and call this JSP using URL http://localhost:8080/main.jsp. This would
display hit counter value which would increase every time when you refresh the page. You can try to access the
page using different browsers and you will find that hit counter will keep increasing with every hit and would
display result something as follows:
TUTORIALS POINT
CHAPTER
20
JSP Auto Refresh
onsider a webpage which is displaying live game score or stock market status or currency exchange
ration. For all such type of pages, you would need to refresh your web page regularly using refresh or reload
button with your browser.
JSP makes this job easy by providing you a mechanism where you can make a webpage in such a way that it
would refresh automatically after a given interval.
The simplest way of refreshing a web page is using method setIntHeader() of response object. Following is the
signature of this method:
public void setIntHeader(String header, int headerValue)
This method sends back header "Refresh" to the browser along with an integer value which indicates time interval
in seconds.
am_pm = "AM";
else
am_pm = "PM";
TUTORIALS POINT
Simply Easy Learning
%>
</center>
</body>
</html>
Now put the above code in main.jsp and try to access it. This would display current system time after every 5
seconds as follows. Just run the JSP and wait to see the result:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
21
JSP Sending Email
o send an email using a JSP is simple enough but to start with you should have
JavaMail API
andJava
<%
String result;
/
Recipient's email ID needs to be mentioned.
String to = "[email protected]";
/
Sender's email ID needs to be mentioned
String from = "[email protected]";
/
Assuming
you
are
sending
email
localhost String host = "localhost";
from
TUTORIALS POINT
Simply Easy Learning
%>
<html>
<head>
<title>Send Email using JSP</title>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
<p
align="center"> <%
%>
</p>
</body>
</html>
Now let us put above code in SendEmail.jsp file and call this JSP using URL http://localhost:8080/SendEmail.jsp
which would send an email to given email ID [email protected] would display following response:
If you want to send an email to multiple recipients then following methods would be used 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 InternetAddress() method while specifying
email IDs
TUTORIALS POINT
Simply Easy Learning
<%
String result;
/
Recipient's email ID needs to be mentioned.
String to = "[email protected]";
/
Sender's email ID needs to be mentioned
String from = "[email protected]";
/
Assuming
you
are
sending
email
localhost String host = "localhost";
from
<html>
<head>
<title>Send HTML Email using JSP</title>
TUTORIALS POINT
Simply Easy Learning
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
<p
align="center"> <%
%>
</p>
</body>
</html>
Now try to use above JSP to send HTML message on a given email ID.
<%
String result;
/
Recipient's email ID needs to be mentioned.
String to = "[email protected]";
/
Sender's email ID needs to be mentioned
String from = "[email protected]";
/
Assuming
you
are
sending
email
localhost String host = "localhost";
from
TUTORIALS POINT
Simply Easy Learning
%>
// 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 Attachement Email using JSP</title>
</head>
<body>
<center>
<h1>Send Attachement Email using JSP</h1>
</center>
<p
align="center"> <%
%>
</p>
</body>
</html>
Now try to run above JSP to send a file as an attachment along with a message on a given email ID.
TUTORIALS POINT
Simply Easy Learning
String
String
String
String
to = request.getParameter("to");
from = request.getParameter("from");
subject = request.getParameter("subject");
messageText = request.getParameter("body");
Once you have all the information, you can use above mentioned programs to send email.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
22
JSP JSTL
he JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which encapsulates
Core Tags:
The core group of tags are the most frequently used JSTL tags. Following is the syntax to include JSTL Core
library in your JSP:
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
There are following Core JSTL Tags:
TUTORIALS POINT
Simply Easy Learning
Tag
Description
<c:out >
<c:set >
<c:remove >
<c:catch>
Catches any Throwable that occurs in its body and optionally exposes it.
<c:if>
Simple conditional tag which evalutes its body if the supplied condition is true.
<c:choose>
Simple conditional tag that establishes a context for mutually exclusive conditional
operations, marked by <when> and <otherwise>
<c:when>
Subtag of <choose> that includes its body if its condition evalutes to 'true'.
<c:otherwise >
Subtag of <choose> that follows <when> tags and runs only if all of the prior
conditions evaluated to 'false'.
<c:import>
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 >
The basic iteration tag, accepting many different collection types and supporting
subsetting and other functionality .
<c:forTokens>
<c:param>
<c:redirect >
<c:url>
Formatting tags:
The JSTL formatting tags are used to format and display text, the date, the time, and numbers for internationalized
Web sites. Following is the syntax to include Formatting library in your JSP:
<%@ taglib prefix="fmt"
uri="http://java.sun.com/jsp/jstl/fmt" %>
Following is the list of Formatting JSTL Tags:
Tag
Description
<fmt:formatNumber>
<fmt:parseNumber>
<fmt:formatDate>
Formats a date and/or time using the supplied styles and pattern
<fmt:parseDate>
<fmt:bundle>
<fmt:setLocale>
<fmt:setBundle>
Loads a resource bundle and stores it in the named scoped variable or the bundle
configuration variable.
TUTORIALS POINT
Simply Easy Learning
<fmt:timeZone>
Specifies the time zone for any time formatting or parsing actions nested in its body.
<fmt:setTimeZone>
Stores the given time zone in the time zone configuration variable
<fmt:message>
<fmt:requestEncoding>
SQL tags:
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as Oracle,
mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP:
<%@ taglib prefix="sql"
uri="http://java.sun.com/jsp/jstl/sql" %>
Following is the list of SQL JSTL Tags:
Tag
Description
<sql:setDataSource>
<sql:query>
Executes the SQL query defined in its body or through the sql attribute.
<sql:update>
Executes the SQL update defined in its body or through the sql attribute.
<sql:param>
<sql:dateParam>
<sql:transaction >
XML tags:
The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents. Following is the
syntax to include JSTL XML library in your JSP.
The JSTL XML tag library has custom tags for interacting with XML data. This includes parsing XML, transforming
XML data, and flow control based on XPath expressions.
<%@ taglib prefix="x"
uri="http://java.sun.com/jsp/jstl/xml" %>
Before you proceed with the examples, you would need to copy following two XML and XPath related libraries into
your <Tomcat Installation Directory>\lib:
XercesImpl.jar: Download it from http://www.apache.org/dist/xerces/j/
xalan.jar: Download it from http://xml.apache.org/xalan-j/index.html
Description
TUTORIALS POINT
Simply Easy Learning
<x:out>
<x:parse>
Use to parse XML data specified either via an attribute or in the tag body.
<x:set >
<x:if >
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>
<x:choose>
Simple conditional tag that establishes a context for mutually exclusive conditional
operations, marked by <when> and <otherwise>
<x:when >
Subtag of <choose> that includes its body if its expression evalutes to 'true'
<x:otherwise >
Subtag of <choose> that follows <when> tags and runs only if all of the prior
conditions evaluated to 'false'
<x:transform >
<x:param >
Use 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" %>
Following is the list of JSTL Functions:
Function
Description
fn:contains()
fn:containsIgnoreCase()
Tests if an input string contains the specified substring in a case insensitive way.
fn:endsWith()
fn:escapeXml()
fn:indexOf()
Returns the index withing a string of the first occurrence of a specified substring.
fn:join()
fn:length()
fn:replace()
Returns a string resulting from replacing in an input string all occurrences with a
given string.
fn:split()
fn:startsWith()
fn:substring()
fn:substringAfter()
TUTORIALS POINT
Simply Easy Learning
fn:substringBefore()
fn:toLowerCase()
fn:toUpperCase()
fn:trim()
TUTORIALS POINT
Simply Easy Learning
CHAPTER
22
JSP Database Access
his chapter assumes you have good understanding on how JDBC application works. Before starting with
database access through a JSP, make sure you have proper JDBC environment setup along with a database.
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 simple table and create few records in that table as follows:
Create Table
To create the Employees table in EMP database, use the following steps:
Step 1:
TUTORIALS POINT
Simply Easy Learning
SELECT Operation:
Following example shows how we can execute SQL SELECT statement using JTSL in JSP programming:
<%@
<%@
<%@
<%@
page import="java.io.*,java.util.*,java.sql.*"%>
page import="javax.servlet.http.*,javax.servlet.*" %>
taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<head>
<title>SELECT Operation</title>
</head>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST"
user="root" password="pass123"/>
</sql:query>
<table border="1"
width="100%"> <tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var="row" items="$
{result.rows}"> <tr>
<td><c:out
<td><c:out
<td><c:out
<td><c:out
</tr>
value="${row.id}"/></td>
value="${row.first}"/></td>
value="${row.last}"/></td>
value="${row.age}"/></td>
TUTORIALS POINT
Simply Easy Learning
</c:forEach>
</table>
</body>
</html>
Now try to access above JSP, which should display the following result:
Emp ID
First Name
Last Name
Age
100
Zara
Ali
18
101
Mahnaz
Fatma
25
102
Zaid
Khan
30
103
Sumit
Mittal
28
INSERT Operation:
Following example shows how we can execute SQL INSERT statement using JTSL in JSP programming:
<%@
<%@
<%@
<%@
page import="java.io.*,java.util.*,java.sql.*"%>
page import="javax.servlet.http.*,javax.servlet.*" %>
taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<head>
<title>JINSERT Operation</title>
</head>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST"
user="root" password="pass123"/>
</sql:update>
<sql:query dataSource="${snapshot}" var="result">
SELECT * from Employees;
</sql:query>
<table border="1"
width="100%"> <tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var="row" items="$
{result.rows}"> <tr>
<td><c:out value="${row.id}"/></td>
TUTORIALS POINT
Simply Easy Learning
<td><c:out
value="${row.first}"/></td>
<td><c:out
value="${row.last}"/></td>
<td><c:out value="${row.age}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
Now try to access above JSP, which should display the following result:
Emp ID
First Name
Last Name
Age
100
Zara
Ali
18
101
Mahnaz
Fatma
25
102
Zaid
Khan
30
103
Sumit
Mittal
28
104
Nuha
Ali
DELETE Operation:
Following example shows how we can execute SQL DELETE statement using JTSL in JSP programming:
<%@
<%@
<%@
<%@
page import="java.io.*,java.util.*,java.sql.*"%>
page import="javax.servlet.http.*,javax.servlet.*" %>
taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<head>
<title>DELETE Operation</title>
</head>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST"
user="root" password="pass123"/>
</sql:update>
<sql:query dataSource="${snapshot}" var="result">
SELECT * from Employees;
</sql:query>
<table border="1"
width="100%"> <tr>
TUTORIALS POINT
Simply Easy Learning
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var="row" items="$
{result.rows}"> <tr>
<td><c:out
<td><c:out
<td><c:out
<td><c:out
</tr>
</c:forEach>
</table>
value="${row.id}"/></td>
value="${row.first}"/></td>
value="${row.last}"/></td>
value="${row.age}"/></td>
</body>
</html>
Now try to access above JSP, which should display the following result:
Emp ID
First Name
Last Name
Age
100
Zara
Ali
18
101
Mahnaz
Fatma
25
102
Zaid
Khan
30
UPDATE Operation:
Following example shows how we can execute SQL UPDATE statement using JTSL in JSP programming:
<%@
<%@
<%@
<%@
page import="java.io.*,java.util.*,java.sql.*"%>
page import="javax.servlet.http.*,javax.servlet.*" %>
taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<head>
<title>DELETE Operation</title>
</head>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST"
user="root" password="pass123"/>
</sql:update>
<sql:query dataSource="${snapshot}" var="result">
TUTORIALS POINT
Simply Easy Learning
</sql:query>
<table border="1"
width="100%"> <tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var="row" items="$
{result.rows}"> <tr>
<td><c:out
<td><c:out
<td><c:out
<td><c:out
</tr>
</c:forEach>
</table>
value="${row.id}"/></td>
value="${row.first}"/></td>
value="${row.last}"/></td>
value="${row.age}"/></td>
</body>
</html>
Now try to access above JSP, which should display the following result:
Emp ID
First Name
Last Name
Age
100
Zara
Ali
18
101
Mahnaz
Fatma
25
102
Zaid
Ali
30
TUTORIALS POINT
Simply Easy Learning
CHAPTER
23
JSP XML Data
hen you send XML data via HTTP, it makes sense to use JSP to handle incoming and outgoing
XML documents for example RSS documents. As an XML document is merely a bunch of text, creating one
through a JSP is no more difficult than creating an HTML document.
TUTORIALS POINT
Simply Easy Learning
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
<book>
<name>Great Mistry</name>
<author>NUHA</author>
<price>2000</price>
</book>
</books>
BOOKS INFO:
The title of the first book is:Padam History
The price of the second book: 2000
"http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" indent="yes"/>
<xsl:template match="/">
<html>
<body> <xsl:applytemplates/>
</body>
TUTORIALS POINT
Simply Easy Learning
</html>
</xsl:template>
<xsl:template match="books">
<table border="1" width="100%">
<xsl:for-each select="book">
<tr>
<td>
<i><xsl:value-of
select="name"/></i> </td>
<td>
<xsl:value-of
select="author"/> </td>
<td>
<xsl:value-of select="price"/>
</td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
<book>
<name>Great Mistry</name>
<author>NUHA</author>
<price>2000</price>
</book>
</books>
</c:set>
TUTORIALS POINT
Simply Easy Learning
BOOKS INFO:
Padam History
ZARA
100
Great Mistry
NUHA
2000
TUTORIALS POINT
Simply Easy Learning
CHAPTER
24
JSP JavaBeans
JavaBean is a specially constructed Java class written in the Java and coded according to the
JavaBeans
API specifications.
Following are the unique characteristics that distinguish a JavaBean from other Java classes:
It provides a default, no-argument constructor.
It should be serializable and implement the Serializable interface.
It may have a number of properties which can be read or written.
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 classes that you define.
A JavaBean property may be read, write, read only, or write only. JavaBean properties are accessed through two
methods in the JavaBean's implementation class:
Method
Description
getPropertyName()
setPropertyName()
A read-only attribute will have only a getPropertyName() method, and a write-only attribute will have only a
setPropertyName() method.
JavaBeans Example:
Consider a student class with few properties:
package com.tutorialspoint;
TUTORIALS POINT
}
public int getAge(){
return age;
}
public void setFirstName(String firstName)
{ this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
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/>
Here values for the scope attribute could be page, request, session or application based on your requirement. The
value of the id attribute may be any value as a long as it is a unique name among other useBean declarations in
the same JSP.
Following example shows its simple usage:
<html>
<head>
<title>useBean Example</title>
</head>
<body>
<jsp:useBean id="date"
class="java.util.Date" /> <p>The date/time is <
%= date %>
</body>
</html>
This would produce following result:
The date/time is Thu Sep 30 11:18:11 GST 2010
TUTORIALS POINT
Simply Easy Learning
value="value"/>
<jsp:getProperty name="bean's id" property="property name"/>
...........
</jsp:useBean>
The name attribute references the id of a JavaBean previously introduced to the JSP by the useBean action. The
property attribute is the name of the get or set methods that should be invoked.
Following is a simple example to access the data using above syntax:
<html>
<head>
<title>get and set properties Example</title>
</head>
<body>
<jsp:useBean id="students"
class="com.tutorialspoint.StudentsBean">
TUTORIALS POINT
Simply Easy Learning
TUTORIALS
POINT
Simply Easy
Learning
CHAPTER
25
JSP Custom Tags
custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is
translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web container
then invokes those operations when the JSP page's servlet is executed.
JSP tag extensions let you create new tags that you can insert directly into a JavaServer Page just as you would
the built-in tags you learned about in earlier chapter. The JSP 2.0 specification introduced Simple Tag Handlers
for writing these custom tags.
To write a customer tab you can simply extend SimpleTagSupport class and override the doTag()method, where
you can place your code to generate content for the tag.
TUTORIALS POINT
Simply Easy Learning
Let us compile above class and copy it in a directory available in environment variable CLASSPATH. Finally create
following tag library file: <Tomcat-Installation-Directory>webapps\ROOT\WEB-INF\custom.tld.
<taglib> <tlib-version>1.0</tlibversion> <jsp-version>2.0</jspversion> <short-name>Example
TLD</short-name> <tag>
<name>Hello</name> <tagclass>com.tutorialspoint.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
Now it's time to use above defined custom tag Hello in our JSP program as follows:
<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%>
<html>
<head>
<title>A sample custom
tag</title> </head>
<body>
<ex:Hello/>
</body>
</html>
Try to call above JSP and this should produce following result:
Hello Custom Tag!
getJspBody().invoke(sw);
getJspContext().getOut().println(sw.toString());
TUTORIALS POINT
Simply Easy Learning
}
In this case, the output resulting from the invocation is first captured into a StringWriter before being written to the
JspWriter associated with the tag. Now accordingly we need to change TLD file as follows:
<taglib> <tlib-version>1.0</tlibversion> <jsp-version>2.0</jspversion>
<short-name>Example TLD with Body</shortname> <tag>
<name>Hello</name> <tagclass>com.tutorialspoint.HelloTag</tag-class>
<body-content>scriptless</body-content>
</tag>
</taglib>
Now let us call above tag with proper body as follows:
<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%>
<html>
<head>
<title>A sample custom
tag</title> </head>
<body>
<ex:Hello>
This is message
body </ex:Hello>
</body>
</html>
This will produce following result:
This is message body
TUTORIALS POINT
Simply Easy Learning
}
else {
}
The attribute's name is "message", so the setter method is setMessage(). Now let us add this attribute in TLD file
using <attribute> element as follows:
<taglib> <tlib-version>1.0</tlibversion> <jsp-version>2.0</jspversion>
<short-name>Example TLD with Body</shortname> <tag>
<name>Hello</name> <tagclass>com.tutorialspoint.HelloTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>message</name>
</attribute>
</tag>
</taglib>
Purpose
name
The name element defines the name of an attribute. Each attribute name
TUTORIALS POINT
Simply Easy Learning
rtexprvalue
type
description
fragment
<name>attribute_name2</name>
<required>true</required>
<type>java.util.Date</type>
</attribute>
.....
TUTORIALS POINT
Simply Easy Learning
CHAPTER
26
JSP Expression Language
SP Expression Language (EL) makes it possible to easily access application data stored in JavaBeans
components. JSP EL allows you to create expressions both (a) arithmetic and (b) logical. Within a JSP EL
expression, you can use integers, floating point numbers, strings, the built-in constants true and false for boolean
values, and null.
Simple Syntax:
Typically, when you specify an attribute value in a JSP tag, you simply use a string. For example:
${expr}
Here expr specifies the expression itself. The most common operators in JSP EL are . and []. These two
operators allow you to access various attributes of Java Beans and built-in JSP objects.
For example above syntax <jsp:setProperty> tag can be written with an expression like:
<jsp:text>
<h1>Hello JSP!</h1>
</jsp:text>
TUTORIALS POINT
You can include a JSP EL expression in the body of a <jsp:text> tag (or any other tag) with the same ${} syntax
you use for attributes. For example:
<jsp:text>
Box Perimeter is: ${2*box.width + 2*box.height}
</jsp:text>
EL expressions can use parentheses to group subexpressions. For example, ${(1 + 2) * 3} equals 9, but ${1 + (2 *
3)} equals 7.
To deactivate the evaluation of EL expressions, we specify the isELIgnored attribute of the page directive as
below:
<%@ page isELIgnored ="true|false" %>
The valid values of this attribute are true and false. If it is true, EL expressions are ignored when they appear in
static text or tag attributes. If it is false, EL expressions are evaluated by the container.
Description
[]
()
Addition
Multiplication
/ or div
Division
% or mod
Modulo (remainder)
== or eq
!= or ne
< or lt
> or gt
<= or le
>= or gt
&& or and
|| or or
! or not
TUTORIALS POINT
Simply Easy Learning
empty
Functions in JSP EL :
JSP EL allows you to use functions in expressions as well. These functions must be defined in custom tag
libraries. A function usage has the following syntax:
${fn:length("Get my length")}
To use a function from any tag library (standard or custom), you must install that library on your server and must
include the library in your JSP using <taglib> directive as explained in JSTL chapter.
Description
pageScope
requestScope
sessionScope
applicationScope
param
paramValues
header
headerValues
initParam
Context-initialization parameters
cookie
Cookie values
pageContext
You can use these objects in an expression as if they were variables. Here are few examples which would clear
the concept:
TUTORIALS POINT
Simply Easy Learning
${pageContext.request.queryString}
TUTORIALS POINT
Simply Easy Learning
For example, to access a header named user-agent, use the expression ${header.user-agent} or ${header["useragent"]}.
Following is the example to access a header parameter named user-agent:
The header object returns single string values, whereas the headerValues object returns string arrays.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
27
JSP Exception Handling
hen you are writing JSP code, a programmer may leave a coding errors which can occur at any part
of the code. You can have following type of errors in your JSP code:
Checked exceptions: Achecked 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 occurs that probably could have been avoided
by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of
compliation.
Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For
example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
This tutorial will give you few simple and elegant ways to handle run time exception/error occuring in your JSP
code.
Returns an array containing each element on the stack trace. The element at index 0 represents the top of
the call stack, and the last element in the array represents the method at the bottom of the call stack.
TUTORIALS POINT
Simply Easy Learning
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.
Following is an example to specifiy an error page for a main.jsp. To set up an error page, use the <%@ page
errorPage="xxx" %> directive.
<%@ page errorPage="ShowError.jsp" %>
<html>
<head>
<title>Error Handling Example</title>
</head>
<body>
<%
// Throw an exception to invoke the error page
int x = 1;
if (x == 1)
{
throw new RuntimeException("Error condition!!!");
}
%>
</body>
</html>
Now you would have to write one Error Handling JSP ShowError.jsp, which is given below. Notice that the errorhandling page includes the directive <%@ page isErrorPage="true" %>. This directive causes the JSP compiler to
generate the exception instance variable.
<%@ page isErrorPage="true" %>
<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps...</h1>
TUTORIALS POINT
Simply Easy Learning
items="${pageContext.exception.stackTrace}">
<p>${trace}</p>
</c:forEach>
</td>
</tr>
</table>
</body>
</html>
TUTORIALS POINT
Simply Easy Learning
Opps...
Error:
URI:
/main.jsp
Status code:
500
Stack trace:
org.apache.jsp.main_jsp._jspService(main_jsp.java:65)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:68)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
...................
%>
</body>
</html>
TUTORIALS POINT
Simply Easy Learning
CHAPTER
28
JSP Debugging
t is always difficult to testing/debugging a JSP and servlets. JSP and Servlets tend to involve a large amount
Using System.out.println():
System.out.println() is easy to use as a marker to test whether a certain piece of code is being executed or not.
We can print out variable values as well. Additionally:
Since the System object is part of the core Java objects, it can be used everywhere without the need to install
any extra classes. This includes Servlets, JSP, RMI, EJB's, ordinary Beans and classes, and standalone
applications.
Compared to stopping at breakpoints, writing to System.out doesn't interfere much with the normal execution
flow of the application, which makes it very valuable when timing is crucial.
Following is the syntax to use System.out.println():
System.out.println("Debugging message");
Following is a simple example of using System.out.print():
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"
%> <html>
<head><title>System.out.println</title></head>
<body>
TUTORIALS POINT
-4
-3
-2
-1
0
1
2
3
4
5
If you are using Tomcat, you will also find these lines appended to the end of stdout.log in the logs directory.
counter=1
counter=2
counter=3
counter=4
counter=5
counter=6
counter=7
counter=8
counter=9
counter=10
This way you can pring variables and other information into system log which can be analyzed to find out the root
cause of the problem or for various other reasons.
+ pageContext.findAttribute("myCount");
logger.info( message );
TUTORIALS POINT
Simply Easy Learning
This would generate similar result at the browser and in stdout.log, but you will have additional information in
stdout.log. Here we are using info method of the logger because we are logging message just for informational
purpose. Here is a snapshot of stdout.log file:
24-Sep-2010
_jspService
24-Sep-2010
_jspService
24-Sep-2010
_jspService
24-Sep-2010
_jspService
24-Sep-2010
_jspService
24-Sep-2010
_jspService
24-Sep-2010
_jspService
24-Sep-2010
_jspService
24-Sep-2010
_jspService
24-Sep-2010
_jspService
23:31:31 org.apache.jsp.main_jsp
INFO: counter=1 myCount=-4
23:31:31 org.apache.jsp.main_jsp
INFO: counter=2 myCount=-3
23:31:31 org.apache.jsp.main_jsp
INFO: counter=3 myCount=-2
23:31:31 org.apache.jsp.main_jsp
INFO: counter=4 myCount=-1
23:31:31 org.apache.jsp.main_jsp
INFO: counter=5 myCount=0
23:31:31 org.apache.jsp.main_jsp
INFO: counter=6 myCount=1
23:31:31 org.apache.jsp.main_jsp
INFO: counter=7 myCount=2
23:31:31 org.apache.jsp.main_jsp
INFO: counter=8 myCount=3
23:31:31 org.apache.jsp.main_jsp
INFO: counter=9 myCount=4
23:31:31 org.apache.jsp.main_jsp
INFO: counter=10 myCount=5
Messages can be sent at various levels by using the convenience functions severe(), warning(), info(), config(),
fine(), finer(), and finest(). Here finest() method can be used to log finest information and severe() method can be
used to log severe information.
You can use
importance.
Log4J Framework
Debugging Tools:
NetBeans is a free and open-source Java Integrated Development Environment that supports the development of
standalone Java applications and Web applications supporting the JSP and servlet specifications and includes a
JSP debugger as well.
NetBeans supports the following basic debugging functionalities:
Breakpoints
Stepping through code
Watchpoints
You can refere to NteBeans documentation to understand above debugging functionalities.
TUTORIALS POINT
Most debuggers hide this detail by automatically knowing how to debug applets. Until they do the same for JSP,
you have to help your debugger by doing the following:
Set your debugger's classpath so that it can find sun.servlet.http.Http-Server and associated classes.
Set your debugger's classpath so that it can also find your JSP and support classes, typically ROOT\WEBINF\classes.
Once you have set the proper classpath, start debugging sun.servlet.http.HttpServer. You can set breakpoints in
whatever JSP you're interested in debugging, then use a web browser to make a request to the HttpServer for the
given JSP (http://localhost:8080/JSPToDebug). You should see execution stop at your breakpoints.
Using Comments:
Comments in your code can help the debugging process in various ways. Comments can be used in lots of other
ways in the debugging process.
The JSP uses Java comments and single line (// ...) and multiple line (/* ... */) comments can be used to
temporarily remove parts of your Java code. If the bug disappears, take a closer look at the code you just
commented and find out the problem.
TUTORIALS POINT
CHAPTER
29
JSP Security
avaServer Pages and servlets make several mechanisms available to Web developers to secure
applications. Resources are protected declaratively by identifying them in the application deployment descriptor
and assigning a role to them.
Several levels of authentication are available, ranging from basic authentication using identifiers and passwords to
sophisticated authentication using certificates.
rolename="tomcat"/>
rolename="role1"/>
rolename="manager"/>
rolename="admin"/>
TUTORIALS POINT
Simply Easy Learning
<web-resource-name>
SecuredBookSite
</web-resource-name>
<url-pattern>/secured/*</url-pattern>
<http-method>GET</http-method> <httpmethod>POST</http-method>
</web-resource-collection>
<auth-constraint>
<description>
Let only managers use this app
</description> <rolename>manager</role-name>
</auth-constraint>
</security-constraint>
<security-role>
<role-name>manager</rolename> </security-role>
<login-config> <authmethod>BASIC</auth-method>
</login-config>
...
</web-app>
TUTORIALS POINT
Simply Easy Learning
</body>
</html>
Here you have to make sure that the login form must contain form elements named j_username and j_password.
The action in the <form> tag must be j_security_check. POST must be used as the form method. Same time you
would have to modify <login-config> tag to specify auth-method as FORM:
<web-app>
...
<security-constraint> <webresource-collection>
<web-resource-name>
SecuredBookSite
</web-resource-name>
<url-pattern>/secured/*</url-pattern>
<http-method>GET</http-method> <httpmethod>POST</http-method>
</web-resource-collection>
<auth-constraint>
<description>
Let only managers use this app
</description> <rolename>manager</role-name>
</auth-constraint>
</security-constraint>
<security-role>
<role-name>manager</rolename> </security-role>
<login-config> <authmethod>FORM</auth-method>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/error.jsp</form-error-page>
</form-login-config>
</login-config>
...
</web-app>
Now when you try to access any resource with URL /secured/*, it would display above form asking for user id and
password. When the container sees the "j_security_check" action, it uses some internal mechanism to
authenticate the caller.
If the login succeeds and the caller is authorized to access the secured resource, then the container uses a
session-id to identify a login session for the caller from that point on. The container maintains the login session
with a cookie containing the session-id. The server sends the cookie back to the client, and as long as the caller
presents this cookie with subsequent requests, then the container will know who the caller is.
If the login fails, then the server sends back the page identified by the form-error-page setting
Here j_security_check is the action that applications using form based login have to specify for the login form. In
the same form you should also have a text input control called j_username and a password input control called
j_password. When you see this it means that the information contained in the form will be submitted to the server,
which will check name and password. How this is done is server specific.
Check Standard Realm Implementations to understand how j_security_check works for Tomcat container.
TUTORIALS POINT
Simply Easy Learning
String getAuthType()
The getAuthType() method returns a String object that represents the name of the authentication scheme
used to protect the Servlet.
boolean isUserInRole(java.lang.String role)
The isUserInRole() method returns a boolean value: true if the user is in the given role or false if they are not.
String getProtocol()
The getProtocol() method returns a String object representing the protocol that was used to send the request.
This value can be checked to determine if a secure protocol was used.
boolean isSecure()
The isSecure() method returns a boolean value representing if the request was made using HTTPS. A value
of true means it was and the connection is secure. A value of false means the request was not.
Principle getUserPrinciple()
The getUserPrinciple() method returns a java.security.Principle object that contains the name of the current
authenticated user.
For example, a JavaServer Page that links to pages for managers, you might have the following code:
<%
<a
<a
<%
if (request.isUserInRole("manager")) { %>
href="managers/mgrreport.jsp">Manager Report</a>
href="managers/personnel.jsp">Personnel Records</a>
} %>
By checking the user's role in a JSP or servlet, you can customize the Web page to show the user only the items
she can access. If you need the user's name as it was entered in the authentication form, you can call
getRemoteUser method in the request object.
TUTORIALS POINT
CHAPTER
30
JSP Internationalization
Internationalization (i18n): This means enabling a web site to provide different versions of content
translated into the visitor's language or nationality.
Localization (l10n): This means adding resources to a web site to adapt it to a particular geographical or
cultural region for example Hindi translation to a web site.
locale: This is a particular cultural or geographical region. It is usually referred to as a language symbol
followed by a country symbol which are separated by an underscore. For example "en_US" represents
english locale for US.
There are number of items which should be taken care while building up a global website. This tutorial would not
give you complete detail on this but it would give you a good example on how you can offer your web page in
different languages to internet community by differentiating their location ie. locale.
A JSP can pickup appropriate version of the site based on the requester's locale and provide appropriate site
version according to the local language, culture and requirements. Following is the method of request object
which returns Locale object.
java.util.Locale request.getLocale()
Detecting Locale:
Following are the important locale methods which you can use to detect requester's location, language and of
course locale. All the below methods display country name and language name set in requester's browser.
S.N. Method & Description
1
2
String getCountry()
This method returns the country/region code in upper case for this locale in ISO 3166 2-letter
format.
String getDisplayCountry()
This method returns a name for the locale's country that is appropriate for display to the user.
String getLanguage()
This method returns the language code in lower case for this locale in ISO 639 format.
String getDisplayLanguage()
This method returns a name for the locale's language that is appropriate for display to the user.
TUTORIALS POINT
Simply Easy Learning
5
6
String getISO3Country()
This method returns a three-letter abbreviation for this locale's country.
String getISO3Language()
This method returns a three-letter abbreviation for this locale's language.
Example:
This example shows how you display a language and associated country for a request in a JSP:
<%@ page import="java.io.*,java.util.Locale" %>
<%@ page import="javax.servlet.*,javax.servlet.http.* "%>
<%
//Get the client's Locale
Locale locale = request.getLocale();
String language = locale.getLanguage();
String country = locale.getCountry();
%>
<html>
<head>
<title>Detecting
Locale</title> </head>
<body>
<center>
<h1>Detecting Locale</h1>
</center>
<p align="center">
<%
out.println("Language : " + language
+ "<br />");
out.println("Country
: " + country
+ "<br />");
%>
</p>
</body>
</html>
Languages Setting:
A JSP can output a page written in a Western European language such as English, Spanish, German, French,
Italian, Dutch etc. Here it is important to set Content-Language header to display all the characters properly.
Second point is to display all the special characters using HTML entities, For example, "ñ" represents "",
and "¡" represents "" as follows:
<%@ page import="java.io.*,java.util.Locale" %>
<%@ page import="javax.servlet.*,javax.servlet.http.* "%>
<%
// Set response content type
response.setContentType("text/html"); /
/ Set spanish language code.
response.setHeader("Content-Language", "es");
String title = "En Espaol";
%>
<html>
<head>
<title><% out.print(title); %></title>
</head>
TUTORIALS POINT
Simply Easy Learning
<body>
<center>
<h1><% out.print(title); %></h1>
</center>
<div align="center">
<p>En Espaol</p>
<p>Hola Mundo!</p>
</div>
</body>
</html>
%>
<html>
<head>
<title><% out.print(title);
%></title> </head>
<body>
<center>
<h1><% out.print(title); %></h1>
</center>
<div align="center">
<p>Local Date: <% out.print(date); %></p>
</div>
</body>
</html>
<%
String title = "Locale Specific
Currency"; //Get the client's Locale
Locale locale = request.getLocale( );
TUTORIALS POINT
Simply Easy Learning
<%
String title = "Locale Specific
Percentage"; //Get the client's Locale
Locale locale = request.getLocale( );
NumberFormat nft = NumberFormat.getPercentInstance(locale);
String formattedPerc = nft.format(0.51);
%>
<html>
<head>
<title><% out.print(title);
%></title> </head>
<body>
<center>
<h1><% out.print(title); %></h1>
</center>
<div align="center">
<p>Formatted Percentage: <% out.print(formattedPerc); %></p>
</div>
</body>
</html>
TUTORIALS POINT
Simply Easy Learning