Thursday 23 May 2013

JSP

Want to learn Advanced JSP click here
JSP Tutorial
JavaServer Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent 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.

JSP - Overview

What is JavaServer Pages?

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

Why Use JSP?

JavaServer Pages often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But JSP offer several advantages in comparison with the CGI.
  • Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of having a separate CGI files.
  • JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested.
  • JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
  • JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.
Finally, JSP is an integral part of J2EE, a complete platform for enterprise class applications. This means that JSP can play a part in the simplest applications to the most complex and demanding.

Advantages of JSP:

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

JSP - Architecture

The 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 Architecture

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.
  • 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:
JSP Processing
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

JSP - Life Cycle

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:
JSP Life Cycle

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.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows:
void _jspService(HttpServletRequest request, 
                 HttpServletResponse response)
{
   // Service handling code...
}
The _jspService() method of a JSP is invoked 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.
}

JSP - Syntax

This tutorial 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:
Hello World

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:
<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:
Today's date: 11-Sep-2010 21:24:25

JSP Comments:

JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out" 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:
SyntaxPurpose
<%-- comment --%>A JSP comment. Ignored by the JSP engine.
<!-- comment -->An HTML comment. Ignored by the browser.
<\%Represents static <% literal.
%\>Represents static %> literal.
\'A single quote in an attribute that uses single quotes.
\"A double quote in an attribute that uses double quotes.

JSP Directives:

A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>
There are three types of directive tag:
DirectiveDescription
<%@ page ... %>Defines page-dependent attributes, such as scripting language, error page, and buffering requirements.
<%@ include ... %>Includes a file during the translation phase.
<%@ taglib ... %>Declares a tag library, containing custom actions, used in the page

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:
SyntaxPurpose
jsp:includeIncludes a file at the time the page is requested
jsp:includeIncludes a file at the time the page is requested
jsp:useBeanFinds or instantiates a JavaBean
jsp:setPropertySets the property of a JavaBean
jsp:getPropertyInserts the property of a JavaBean into the output
jsp:forwardForwards the requester to a new page
jsp:pluginGenerates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin
jsp:elementDefines XML elements dynamically.
jsp:attributeDefines dynamically defined XML element's attribute.
jsp:bodyDefines dynamically defined XML element's body.
jsp:textUse to write template text in JSP pages and documents.
I would explain JSP actions in separate chapter JSP - Actions

JSP Implicit Objects:

JSP supports nine automatically defined variables, which are also called implicit objects. These variables are:
ObjectsDescription
requestThis is the HttpServletRequest object associated with the request.
responseThis is the HttpServletResponse object associated with the response to the client.
outThis is the PrintWriter object used to send output to the client.
sessionThis is the HttpSession object associated with the request.
applicationThis is the ServletContext object associated with application context.
configThis is the ServletConfig object associated with the page.
pageContextThis encapsulates use of server-specific features like higher performance JspWriters.
pageThis is simply a synonym for this, and is used to call the methods defined by the translated servlet class.
ExceptionThe Exception object allows the exception data to be accessed by designated JSP.
I 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> 
This would produce following result:
Today is not weekend
Now look at the following switch...case block which has been written a bit differentlty using out.println()and inside Scriptletas:
<%! int day = 3; %> 
<html> 
<head><title>SWITCH...CASE Example</title></head> 
<body>
<% 
switch(day) {
case 0:
   out.println("It\'s Sunday.");
   break;
case 1:
   out.println("It\'s Monday.");
   break;
case 2:
   out.println("It\'s Tuesday.");
   break;
case 3:
   out.println("It\'s Wednesday.");
   break;
case 4:
   out.println("It\'s Thursday.");
   break;
case 5:
   out.println("It\'s Friday.");
   break;
default:
   out.println("It's Saturday.");
}
%>
</body> 
</html> 
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 do…while 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++){ %>
   <font color="green" size="<%= fontSize %>">
    JSP Tutorial
   </font><br />
<%}%>
</body> 
</html> 
This would produce following result:
JSP Tutorial 
JSP Tutorial 
JSP Tutorial 
Above example can be written using while loop as follows:
<%! int fontSize; %> 
<html> 
<head><title>WHILE LOOP Example</title></head> 
<body>
<%while ( fontSize <= 3){ %>
   <font color="green" size="<%= fontSize %>">
    JSP Tutorial
   </font><br />
<%fontSize++;%>
<%}%>
</body> 
</html> 
This would also produce following result:
JSP Tutorial 
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 
Equality  == != Left to right 
Bitwise AND Left to right 
Bitwise XOR Left to right 
Bitwise OR Left to right 
Logical AND && Left to right 
Logical OR || Left to right 
Conditional ?: Right to left 
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left 
Comma Left to right 

JSP Literals:

The JSP expression language defines the following literals:
  • Boolean: true and false
  • Integer: as in Java
  • Floating point: as in Java
  • String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\.
  • Null: null

JSP 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:
SyntaxPurpose
jsp:includeIncludes a file at the time the page is requested
jsp:useBeanFinds or instantiates a JavaBean
jsp:setPropertySets the property of a JavaBean
jsp:getPropertyInserts the property of a JavaBean into the output
jsp:forwardForwards the requester to a new page
jsp:pluginGenerates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin
jsp:elementDefines XML elements dynamically.
jsp:attributeDefines dynamically defined XML element's attribute.
jsp:bodyDefines dynamically defined XML element's body.
jsp:textUse to write template text in JSP pages and documents.

Common Attributes:

There are two attributes that are common to all Action elements: the id attribute and the scope attribute.
  • Id attribute: The id attribute uniquely identifies the Action element, and allows the action to be referenced inside the JSP page. If the Action creates an instance of an object the id value can be used to reference it through the implicit object PageContext
  • Scope attribute: This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute are directly related, as the scope attribute determines the lifespan of the object associated with the id. The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application.

The <jsp:include> Action

This action lets you insert files into the page being generated. The syntax looks like this:
<jsp:include page="relative URL" flush="true" />
Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet, this action inserts the file at the time the page is requested.
Following is the list of attributes associated with include action:
AttributeDescription
pageThe relative URL of the page to be included.
flushThe 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:

The include action Example

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

The <jsp:useBean> Action

The useBean action is quite versatile. It first searches for an existing object utilizing the id and scope variables. If an object is not found, it then tries to create the specified object.
The simplest way to load a bean is as follows:
<jsp:useBean id="name" class="package.class" />
Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to modify and retrieve bean properties.
Following is the list of attributes associated with useBean action:
AttributeDescription
classDesignates the full package name of the bean.
typeSpecifies the type of the variable that will refer to the object.
beanNameGives 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.

The <jsp:setProperty> Action

The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action. There are two basic ways to use the setProperty action:
You can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:
<jsp:useBean id="myName" ... />
...
<jsp:setProperty name="myName" property="someProperty" .../>
In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found.
A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as below:
<jsp:useBean id="myName" ... >
...
   <jsp:setProperty name="myName" property="someProperty" .../>
</jsp:useBean>
Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found.
Following is the list of attributes associated with setProperty action:
AttributeDescription
nameDesignates the bean whose property will be set. The Bean must have been previously defined.
propertyIndicates 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.
valueThe 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.
paramThe param attribute is the name of the request parameter whose value the property is to receive. You can't use both value and param, but it is permissible to use neither.

The <jsp:getProperty> Action

The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output.
The getProperty action has only two attributes, both of which are required ans simple syntax is as follows:
<jsp:useBean id="myName" ... />
...
<jsp:getProperty name="myName" property="someProperty" .../>
Following is the list of required attributes associated with setProperty action:
AttributeDescription
nameThe name of the Bean that has a property to be retrieved. The Bean must have been previously defined.
propertyThe property attribute is the name of the Bean property to be retrieved.

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;
   }
}
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:

Using JavaBeans in JSP

Got message....
Hello JSP...

The <jsp:forward> Action

The forward action terminates the action of the current page and forwards the request to another resource such as a static page, another JSP page, or a Java Servlet.
The simple syntax of this action is as follows:
<jsp:forward page="Relative URL" />
Following is the list of required attributes associated with forward action:
AttributeDescription
pageShould 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:
<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

The <jsp:plugin> Action

The plugin action is used to insert Java components into a JSP page. It determines the type of browser and inserts the <object> or <embed> tags as needed.
If the needed plugin is not present, it downloads the plugin and then executes the Java component. The Java component can be either an Applet or a JavaBean.
The plugin action has several attributes that correspond to common HTML tags used to format Java components. The <param> element can also be used to send parameters to the Applet or Bean.
Following is the typical syntax of using plugin action:
<jsp:plugin type="applet" codebase="dirname" code="MyApplet.class"
                           width="60" height="80">
   <jsp:param name="fontcolor" value="red" />
   <jsp:param name="background" value="black" />
 
   <jsp:fallback>
      Unable to initialize Java Plugin
   </jsp:fallback>
 
</jsp:plugin>
You can try this action using some applet if you are interested. A new element, the <fallback> element, can be used to specify an error string to be sent to the user in case the component fails.

The <jsp:element> Action

The <jsp:attribute> Action

The <jsp:body> Action

The <jsp:element>, lt;jsp:attribute> and <jsp:body> actions are used to define XML elements dynamically. The word dynamically is important, because it means that the XML elements can be generated at request time rather than statically at compile time.
Following is a simple example to define XML elements dynamically:
<%@page language="java" contentType="text/html"%>
<html xmlns="http://www.w3c.org/1999/xhtml"
      xmlns:jsp="http://java.sun.com/JSP/Page">

<head><title>Generate XML Element</title></head>
<body>
<jsp:element name="xmlElement">
<jsp:attribute name="xmlElementAttr">
   Value for the attribute
</jsp:attribute>
<jsp:body>
   Body for XML element
</jsp:body>
</jsp:element>
</body>
</html>
This would produce following HTML code at run time:
<html xmlns="http://www.w3c.org/1999/xhtml"
      xmlns:jsp="http://java.sun.com/JSP/Page">
 
<head><title>Generate XML Element</title></head>
<body>
<xmlElement xmlElementAttr="Value for the attribute">
   Body for XML element
</xmlElement>
</body>
</html>

The <jsp:text> Action

The <jsp:text> action can be used to write template text in JSP pages and documents. Following is the simple syntax for this action:
<jsp:text>Template data</jsp:text>
The body fo the template cannot contain other elements; it can only contain text and EL expressions ( Note: EL expressions are explained in subsequent chapter). Note that in XML files, you cannot use expressions such as ${whatever > 0}, because the greater than signs are illegal. Instead, use the gt form, such as ${whatever gt 0} or an alternative is to embed the value in a CDATA section.
<jsp:text><![CDATA[<br>]]></jsp:text>
If you need to include a DOCTYPE declaration, for instance for XHTML, you must also use the <jsp:text> element as follows:
<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>
Try above example with and without <jsp:text> action.

JSP - Form Processing

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

Reading Form Data using JSP

JSP handles form data parsing automatically using the following methods depending on the situation:
  • 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.

GET Method Example Using URL:

Here is a simple URL which will pass two values to HelloForm program using GET method.
http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI
Below is main.jsp JSP program to handle input given by web browser. We are going to usegetParameter() method which makes it very easy to access passed information:
<html>
<head>
<title>Using GET Method to Read Form Data</title>
</head>
<body>
<center>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
   <%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last  Name:</b>
   <%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
Now type http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI in your browser's Location:box. This would generate following result:

Using GET Method to Read Form Data

  • First Name: ZARA
  • Last Name: ALI

GET Method Example Using Form:

Here is a simple example which passes two values using HTML FORM and submit button. We are going to use same JSP main.jsp to handle this input.
<html>
<body>
<form action="main.jsp" method="GET">
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>
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.

POST Method Example Using Form:

Let us do little modification in the above JSP to handle GET as well as POST methods. Below ismain.jsp JSP program to handle input given by web browser using GET or POST methods.
Infact there is no change in above JSP because only way of passing parameters is changed and no binary data is being passed to the JSP program. File handling related concepts would be explained in separate chapter where we need to read binary data stream.
<html>
<head>
<title>Using GET and POST Method to Read Form Data</title>
</head>
<body>
<center>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
   <%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last  Name:</b>
   <%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
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.
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.

Passing Checkbox Data to JSP Program

Checkboxes are used when more than one option is required to be selected.
Here is example HTML code, CheckBox.htm, for a form with two checkboxes
<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" /> 
                                                Chemistry
<input type="submit" value="Select Subject" />
</form>
</body>
</html>
The result of this code is the following form
 Maths  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>
For the above example, it would display following result:

Reading Checkbox Data

  • Maths Flag : : on
  • Physics Flag: : null
  • Chemistry Flag: : on

Reading All Form Parameters:

Following is the generic example which uses getParameterNames() method of HttpServletRequest to read all the available form parameters. This method returns an Enumeration that contains the parameter names in an unspecified order.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner, usinghasMoreElements() method to determine when to stop and using nextElement() method to get each parameter name.
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>HTTP Header Request Example</title>
</head>
<body>
<center>
<h2>HTTP Header Request Example</h2>
<table width="100%" border="1" align="center">
<tr bgcolor="#949494">
<th>Param Name</th><th>Param Value(s)</th>
</tr>
<%
   Enumeration paramNames = request.getParameterNames();

   while(paramNames.hasMoreElements()) {
      String paramName = (String)paramNames.nextElement();
      out.print("<tr><td>" + paramName + "</td>\n");
      String paramValue = request.getHeader(paramName);
      out.println("<td> " + paramValue + "</td></tr>\n");
   }
%>
</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>
Now try calling JSP using above Hello.htm, this would generate a result something like as below based on the provided input:

Reading All Form Parameters

Param NameParam Value(s)
mathson
chemistryon
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.

JSP - Cookies Handling

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

The Anatomy of a Cookie:

Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A JSP that sets a cookie might send headers that look something like this:
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; 
                 path=/; domain=only4programmers.blogspot.com.
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser's headers might look something like this:
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.

Servlet Cookies Methods:

Following is the list of useful methods associated with Cookie object which you can use while manipulating cookies in JSP:
S.N.Method & Description
1public void setDomain(String pattern)
This method sets the domain to which cookie applies, for example only4programmers.blogspot.com.
2public String getDomain()
This method gets the domain to which cookie applies, for example only4programmers.blogspot.com.
3public void setMaxAge(int expiry)
This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session.
4public int getMaxAge()
This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown.
5public String getName()
This method returns the name of the cookie. The name cannot be changed after creation.
6public void setValue(String newValue)
This method sets the value associated with the cookie.
7public String getValue()
This method gets the value associated with the cookie.
8public void setPath(String uri)
This method sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories.
9public String getPath()
This method gets the path to which this cookie applies.
10public void setSecure(boolean flag)
This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL) connections.
11public void setComment(String purpose)
This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie to the user.
12public String getComment()
This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment.

Setting Cookies with JSP:

Setting cookies with JSP involves three steps:
(1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
Cookie cookie = new Cookie("key","value");
Keep in mind, neither the name nor the value should contain white space or any of the following characters:
[ ] ( ) = , " / ? @ : ;
(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24); 
(3) Sending the Cookie into the HTTP response headers: You use response.addCookie to add cookies in the HTTP response header as follows:
response.addCookie(cookie);

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>
   <%= 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 />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Keep above HTML content in a file hello.jsp and put hello.jsp and main.jsp in <Tomcat-installation-directory>/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.

Reading Cookies with JSP:

To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling thegetCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value.

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>
</center>
<%
   Cookie cookie = null;
   Cookie[] cookies = null;
   // Get an array of Cookies associated with this domain
   cookies = request.getCookies();
   if( cookies != null ){
      out.println("<h2> Found Cookies Name and Value</h2>");
      for (int i = 0; i < cookies.length; i++){
         cookie = cookies[i];
         out.print("Name : " + cookie.getName( ) + ",  ");
         out.print("Value: " + cookie.getValue( )+" <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. 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:

Found Cookies Name and Value

Name : first_name, Value: John
Name : last_name, Value: Player

Delete Cookies with JSP:

To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps:
  • Read an already existing cookie and store it in Cookie object.
  • Set cookie age as zero using setMaxAge() method to delete an existing cookie.
  • Add this cookie back into response header.

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>
<%
   Cookie cookie = null;
   Cookie[] cookies = null;
   // Get an array of Cookies associated with this domain
   cookies = request.getCookies();
   if( cookies != null ){
      out.println("<h2> Found Cookies Name and Value</h2>");
      for (int i = 0; i < cookies.length; i++){
         cookie = cookies[i];
         if((cookie.getName( )).compareTo("first_name") == 0 ){
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            out.print("Deleted cookie: " + 
            cookie.getName( ) + "<br/>");
         }
         out.print("Name : " + cookie.getName( ) + ",  ");
         out.print("Value: " + cookie.getValue( )+" <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:

Cookies Name and Value

Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player
Now try to run http://localhost:8080/main.jsp once again and it should display only one cookie as follows:

Found Cookies Name and Value

Name : last_name, Value: Player
You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select Internet Options. To delete all cookies, press Delete Cookies.

JSP - Handling Date

One 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.utilpackage, 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:
SNMethods with Description
1boolean after(Date date)
Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false.
2boolean before(Date date)
Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false.
3Object clone( )
Duplicates the invoking Date object.
4int 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.
5int compareTo(Object obj)
Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException.
6boolean equals(Object date)
Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false.
7long getTime( )
Returns the number of milliseconds that have elapsed since January 1, 1970.
8int hashCode( )
Returns a hash code for the invoking object.
9void setTime(long time)
Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970
10String toString( )
Converts the invoking Date object into a string and returns the result.

Getting Current Date & Time

This is very easy to get current date and time in JSP program. You can use a simple Date object withtoString() method to print current date and time as follows:
<%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
<html>
<head>
<title>Display Current Date & Time</title>
</head>
<body>
<center>
<h1>Display Current Date & Time</h1>
</center>
<%
   Date date = new Date();
   out.print( "<h2 align=\"center\">" +date.toString()+"</h2>");
%>
</body>
</html>
Now let us keep about code in CurrentDate.jsp and then call this JSP using URL http://localhost:8080/CurrentDate.jsp. This would produce following result:

Display Current Date & Time

Mon Jun 21 21:46:49 GMT+04:00 2010

Try to refresh URL http://localhost:8080/CurrentDate.jsp and you would find difference in seconds everytime you would refresh.

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.
  • You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.

Date Formatting using SimpleDateFormat:

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.
Let us modify above example as follows:
<%@ page import="java.io.*,java.util.*" %>
<%@ page import="javax.servlet.*,java.text.*" %>
<html>
<head>
<title>Display Current Date & Time</title>
</head>
<body>
<center>
<h1>Display Current Date & Time</h1>
</center>
<%
   Date dNow = new Date( );
   SimpleDateFormat ft = 
   new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
   out.print( "<h2 align=\"center\">" + ft.format(dNow) + "</h2>");
%>
</body>
</html>
Compile above servlet once again and then call this servlet using URL http://localhost:8080/CurrentDate. This would produce following result:

Display Current Date & Time

Mon 2010.06.21 at 10:06:44 PM GMT+04:00

Simple DateFormat format codes:

To specify the time format use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following:
CharacterDescriptionExample
GEra designatorAD
yYear in four digits2001
MMonth in yearJuly or 07
dDay in month10
hHour in A.M./P.M. (1~12)12
HHour in day (0~23)22
mMinute in hour30
sSecond in minute55
SMillisecond234
EDay in weekTuesday
DDay in year360
FDay of week in month2 (second Wed. in July)
wWeek in year40
WWeek in month1
aA.M./P.M. markerPM
kHour in day (1~24)24
KHour in A.M./P.M. (0~11)10
zTime zoneEastern Standard Time
'Escape for textDelimiter
"Single quote`
For a complete list of constant available methods to manipulate date, you can refer to standard Java documentation.

JSP - Page Redirecting

Page 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>
<%
   // New location to be redirected
   String site = new String("http://www.photofuntoos.com");
   response.setStatus(response.SC_MOVED_TEMPORARILY);
   response.setHeader("Location", site); 
%>
</body>
</html>
Now let us put above code in PageRedirect.jsp and call this JSP using URL http://localhost:8080/PageRedirect.jsp. This would take you given URL http://www.photofuntoos.com.

JSP - Hits Counter

A hit counter tells you about the number of visits on a particular page of your web site. Usually you attach a hit counter with your index.jsp page assuming people first land on your home page.
To implement a hit counter you can make use of 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 */
       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:
Welcome back to my website!
Total number of visits: 12

Hit Counter Resets:

What about if you re-start your application ie. web server, this will reset your application variable and your counter will reset to zero. To avoid this loss, you can implement your counter in professional way which is as follows:
  • Define a database table with a single count, let us say hitcount. Assign a zero value to it.
  • With every hit, read the table to get the value of hitcount.
  • Increase the value of hitcount by one and update the table with new value.
  • Display new value of hitcount as total page hit counts.
  • If you want to count hits for all the pages, implement above logic for all the pages.

JSP - Auto Refresh

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

Auto Page Refresh Example:

Following example would use setIntHeader() method to set Refresh header to simulate a digital clock:
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Auto Refresh Header Example</title>
</head>
<body>
<center>
<h2>Auto Refresh Header Example</h2>
<%
   // Set refresh, autoload time as 5 seconds
   response.setIntHeader("Refresh", 5);
   // Get current time
   Calendar calendar = new GregorianCalendar();
   String am_pm;
   int hour = calendar.get(Calendar.HOUR);
   int minute = calendar.get(Calendar.MINUTE);
   int second = calendar.get(Calendar.SECOND);
   if(calendar.get(Calendar.AM_PM) == 0)
      am_pm = "AM";
   else
      am_pm = "PM";
   String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
   out.println("Crrent Time: " + CT + "\n");
%>
</center>
</body>
</html>
Now put the above code in main.jsp and try to access it. This would display current system time after every 5 seconds as follows. Just run the JSP and wait to see the result:

Auto Refresh Header Example

Current Time is: 9:44:50 PM
To become more comfortable with other methods you can try few more above listed methods in the same fashion.


No comments:

Post a Comment