This is the age of dynamic web sites. Gone are the days when people used to feel proud of their static sites. Now even business is done online and you need dynamic web sites to deal with this.

Java provides JavaServer Pages (JSP), which enables the development of dynamic web sites. JSP files are simple text files with JSP extension. These include HTML code along with Java code. Java code is executed on the server and the user only gets HTML code in the browser.
JSP is multi platform and also it can be used as a component by using JavaBeans and EJB.

Web servers

You need to web server on your machine to start running JSP pages. There are many JSP supported web servers available. Few of them are as follows:

Blazix from Desiderata Software (1.5 Megabytes, JSP, Servlets and EJBs)
TomCat from Apache (Approx 6 Megabytes)
WebLogic from BEA Systems (Approx 40 Megabytes, JSP, Servlets and EJBs)
WebSphere from IBM (Approx 100 Megabytes, JSP, Servlets and EJBs)

Hello World JSP

JSP page comprises of HTML code along with Java code. Server side code is enclosed under <%%> tags.
Java Code:
<HTML>
<BODY>
<%
   out.println( "Hello World" );
%>
</BODY>
</HTML>

JSP Tags

There are 5 different types of JSP tags.

- Declaration tag
- Expression tag
- Directive tag
- Scriptlet tag
- Action tag

Declaration tag

Declaration tag is used to declare variables and methods. Declarations are enclosed under
Java Code:
<%! %>
All the code written in this declaration tag must end in a semicolon ( ; ).
<%!
private int counter = 0 ;
private String getName ( int id) ;
%>

Expression tag

Extression tag ( <%= %>) is used to execute Java expressions. It is a shot form of out.println(). Thing to remember is that you should not place a semicolon (;) at the end of code inside this tag.

Java Code:
Date : <%= new java.util.Date() %>
Directive tag

A JSP directive ( <%@ directive ... %>) gives JSP engine some special information about the page. There are different types of directives:

- page directive (for processing information for the page)
-include directive (to mention the files to be included)
-tag library (to mention the tag library to be used in the page)


JSP directives change the way the JSP Engine processes the page but do not produce any visible output when the page is requested.

Page directive

The page directive has many optional attributes. One should use only the ones that are needed. Syntax of page directive is as follows:

Java Code:
<%@ page 
          [ language="java" ] 
          [ extends="package.class" ] 
          [ import="{package.class | package.*}, ..." ] 
          [ session="true | false" ] 
          [ buffer="none | 8kb | sizekb" ] 
          [ autoFlush="true | false" ] 
          [ isThreadSafe="true | false" ] 
          [ info="text" ] 
          [ errorPage="relativeURL" ] 
          [ contentType="mimeType [ ;charset=characterSet ]"   |   
                                       "text/html ; charset=ISO-8859-1" ] 
          [ isErrorPage="true | false" ] 
%>
Lets take few examples:

Java Code:
<%@ page import="java.util.*, java.lang.*" %> 
<%@ page buffer="5kb" autoFlush="false" %> 
<%@ page errorPage="error.jsp" %>

Presented below is an example that shows how to import a class from a package and how to use it.

Java Code:
<%@page import="package1.Class1" %>
<html>
  <head><title>Example</title></head>
	
   <body>
    <font size="20" color="red">
     <%
	Class1 obj = new Class1();
	out.print(obj.show());
     %>
    </font>
   </body>
</html>

package package1;

public class Class1{
  public String show(){
    return "JSP Tutorial";
  }
}
Include directive

We use include directive to include files into our JSP. An example would be header or footer files.


Java Code:
<%@ include file = "include/privacy.html" %>
<%@ include file = "navigation.jsp" %>
Tag Lib directive

Tag lib contains custom tags that can be used in JSP. There are some standard taglibs available. You may write your own taglib as well. These taglibs are included into JSP using taglib directive.

Java Code:
<%@ taglib uri = "tag library URI" prefix = "tag Prefix" %>


@page buffer example
The buffer attribute sets the buffer size in kilobytes that is used by the out object to handle output generated by the JSP page on the client web browser.
Java Code:
<%@page buffer="5kb" autoFlush="false" %>
<%
	for(int i = 0; i < 10; i++){
		out.println("<html><body><img src=images/marijuana_leaf.jpg />
</body></html>");
	}
%>
IsThreadSafe attribute

isThreadSafe attribute of the page directive supports the facility of maintaining thread for sending multiple and concurrent requests from the JSP container to the JSP page. The default value for this is true. If it is specified as false, then the JSP container can send only one request at one time. Review the example below:

Java Code:
<%@page isThreadSafe="true" %>
<html>
<head><title>Example of isThreadSafe attribute of page
directive in JSP.</title></head>
<body>
<table border="1" cellspacing="0" cellpadding="0"
bgcolor="ffff00">
<tr>
<td><strong>This is the example
of isThreadSafe attribute of page directive.</strong></td>
</tr>
</table>
</body>
</html>
info Attribute

Page directive has an info attribute that simply sets the information of the JSP page which is retrieved later by using Servlet.getServletInfo() method. The value of the attribute will be a text string.

Java Code:
<%@page info="This is the example of info attribute of the page directive." %>
<html>
<head><title>Info Attribute of page directive in JSP.</title></head>
<body>
<%
out.println("Example of the info
attribute of the page directive in JSP.");
%>
</body>
</html>
errorPage attribute

JSP page directive includes an errorPage attribute which sets a url for an error page. If any exception is generated then the attribute refers to the file which is mentioned in the given url. What if you do not mention errorPage attribute since it is optional? Then exception will be displayed in the current page.

Java Code:
<%@page errorPage="error.jsp" %>
<html>
<head><title>Showing Error Page.</title></head>
<body>
<form method="post">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Enter a number: </td>
<td><input type="text" name="txtNum" />
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="B1" value=
"Divide by zero" />
</tr>
</table>
</form>
<%
if(request.getParameter("txtNum") != null){
if(!request.getParameter("txtNum").equals("")){
int div = Integer.parseInt(request.
getParameter("txtNum")) / 0;
out.println("Answer is: " + div);
}
else{
out.println("<html><font color=red>Please
enter a number.</font></html>");
}
}
%>
</body>
</html>
error.jsp

Java Code:
<%@page isErrorPage="true" %>
<html>
<head><title>Error Page.</title></head>
<body bgcolor="blue">
<font size="16" color="white">Your page generated
an error:"<br/>
Exception:<br/></font>
<%= exception.toString() %>
</body>
</html>
contentType Attribute

The contentType attribute of the page directive in JSP specifies the MIME type and the character encoding that is used for the JSP response. The default MIME type is "text/html" and the default character set is "ISO-8859-1".


Java Code:
<%@page contentType="text/html" %>
<html>
<head><title>Example of contextType attribute of page directive in JSP.</title></head>
<body>
<table border="1" cellspacing="0" cellpadding="0" bgcolor="ffff00">
<tr>
<td><strong>This is the html page.</strong></td>
</tr>
</table>
</body>
</html>
The above example was a simple one, which displays the contents in the browser in normal web form.

Now lets try to set the type to xml and see what happens.

Java Code:
<%@page contentType="text/xml" %>
<html>
<head><title>Example of contextType attribute
of page directive in JSP.</title></head>
<body>
<table border="1" cellspacing="0" cellpadding="0" bgcolor="ffff00">
<tr>
<td><strong>This is the xml page.</strong></td>
</tr>
</table>
</body>
</html>
The output of the above example will be in XML form on the browser.

Scriptlet tag

Scriptlet tag ( <% ... %> ) is used to write valid Java code in a JSP. This code can access variables and methods or even bean that is declared.

Java Code:
<% 

        String username = "Dave" ; 

        out.println ( username ) ;
  %>
Action tag

Action tag is used to enable the use of JavaBeans, to transfer control between pages and for browser independent support for applets.

To use a JavaBeans in a JSP page use the following syntax:


Java Code:
<jsp : usebean id = " ...." scope = "application" class = "com..." />
As you must have noted, we have used application scope in the example below. There are 4 different scopes you may use.

page - valid until page completes.

request - bean instance lasts for the client request

session - bean lasts for the client session.

application - bean instance created and lasts until application ends.

JSP loop example

Presented below is a simple JSP loop example.

Java Code:
<HTML>
<HEAD> 
<TITLE> JSP loop</TITLE> 
</HEAD> 
<BODY> 
<font face=verdana color=darkblue>
JSP loop
<BR> <BR> 
<%!

public String writeThis(int x)
{

            String myText="";

            for (int i = 1; i < x; i )
            myText = myText "<font size=" i " color=darkred face=verdana> 
            JSP Tutorial</font><br>" ;

            return myText;

}

%> 
This is a loop example from the 
<br>
<%= writeThis(8) %> 
</font>
</BODY> 
</HTML>
Implicit objects

There are several objects that are automatically available in JSP called implicit objects. You are not required to declare or instantiate them, they are ready to use. JSP includes following implicit objects:

Request (Javax.servlet.http.httpservletrequest)
Response (Javax.servlet.http. httpservletresponse)
Out (Javax.servlet.jsp.JspWriter)
Session (Javax.servlet.http.httpsession)
PageContent (Javax.servlet.jsp.pagecontext)
Application (Javax.servlet.http.ServletContext)
Config (Javax.servlet.http.ServletConfig)
Page (Java.lang.Object)

Request object is used to access to information associated with a request. This object is normally used in looking up parameter values and cookies.

Java Code:
<% String str = request.getParameter("username"); %> 
User = <%= str %>
The code snippet presented above gets the parameter named username and displays it.

A from example

Presented below is a simple HTML form with a text field.

Java Code:
<html> 

<head> 

<title>Welcome</title> 

</head> 

<body>

<form action="welcome.jsp" method="post">

Enter your  name:<br>

<input type="text" name="name"><br>

<input type="submit" name="submit">

</form>

</body>

</html>
The form posts to welcome.jsp which is used for processing.

welcome.jsp

Java Code:
<html> 

<head> 

<title>Welcome</title> 

</head> 

<body>

<font size=3>

We received your information.

<br><br>

<%

String sName = request.getParameter("name");

out.print(sName);

%>

</font>

</body>

</html>
Session example

Lets make the example a bit complex. Presented below is a simple HTML form which posts to session.jsp.

Java Code:
<html>
  <head><title>Disable Session Environment.</title></head>
   <body>
    <form action="session.jsp" method="post">
	<table border="0" cellspacing="0" cellpadding="0">
	 <tr>
	  <td>User Name: </td>
	  <td><input type="text" size="20" name="txtUserName" />
	 </tr>
	 <tr>
	  <td>Password: </td>
	  <td><input type="password" size="20" name="txtPassword" />
	 </tr>
	 <tr>
	  <td>&nbsp;</td>
	   <td><input type="submit" value="Submit" name="B1" /></td>
	 </tr>
	</table>
     </form>
    </body>
</html>
Now lets review session.jsp. It gets the username and password from the posted form. If the username and password are not null, then they are stored in the session variables and a link is provided to navigate to.

Java Code:
<%@page language="java" %>
<%
	String userName = request.getParameter("txtUserName");
	String password = request.getParameter("txtPassword");
	if(userName == null)
		userName = "";
	if(password == null)
		password = "";
	if(!userName.equals("") && !password.equals("")){
		session.setAttribute("SessionUser", userName);
		session.setAttribute("SessionPassword", password);
		out.println("Welcome " + userName + "!");
		out.println("<br/><a href=sessionresult.jsp>
                            Next Page with session true.</a>");
		out.println("<br/><a href=ShowFalseSession.jsp>
                            Next Page with session false.</a>");
	}
	else if(userName.equals("")){
		out.println("<font color=red><b>User name required.</b></font>");
		out.println("<br/><a href=sessionForm.jsp>Go back!</a>");
	}
	else if(password.equals("")){
		out.println("<font color=red><b>Password required.</b></font>");
		out.println("<br/><a href=sessionForm.jsp>Go back!</a>");
	}
%>
sessionresult.jsp simply prints the username and password stored in the session variables.


Java Code:
<%@page language="java" session="true" %>
<%
	String username = (String)session.getAttribute("SessionUser");
	String password = (String)session.getAttribute("SessionPassword");
	out.println("<b>Welcome " + username + "!</b>");
%>
ShowFalseSession.jsp

Java Code:
<%@page language="java" session="false" %>
<%
	out.println("The value of session attribute is false!");
%>
Request object getQueryString

This getQueryString method of equest object is used for getting the query string which comprises of value of the attribute of the html from where the jsp page is referenced. There all attribute of the form with form attributes is available in the query string.

Java Code:
<html>
<head><title>getQueryString() method of request object.</title></head>
<body>
<form method="get">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td>User Name: </td>
<td><input type="text" size="20" name="txtUserName" />
</tr>
<tr>
<td>Password: </td>
<td><input type="password" size="20" name="txtPassword" />
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" value="Submit" name="B1" /></td>
</tr>
</table>
</form>
<%
if(request.getQueryString() != null)
out.println(request.getQueryString());
%>
</body>
</html>
Request object getRequestURI

Request object provides getRequestURI method for getting the information of the URI of the current page of your JSP application. It returns the URI of the current page from the URL (Unified Resource Locator). The retrieved URI is the string, which is mentioned in the URL after the host name up to the current page. The retrieved URI does not contain the host name or any parameter mentioned from the query string after the page name in the URL.
Review the example below:

Java Code:
<html>
<body>
<form action="GetRequestURIMethod.jsp" method="get">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td>User Name: </td>
<td><input type="text" size="20" name=
"txtUserName" />
</tr>
<tr>
<td>Password: </td>
<td><input type="password" size="20"
name="txtPassword" />
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" value="Submit"
name="B1" /></td>
</tr>
</table>
</form>
</body>
</html>

GetRequestURIMehtod.jsp

Java Code:
<%
	out.println("<b>" + request.getRequestURI() + "</b>");
%>