An Introduction to Java Server PagesT and ServletsT
PART II: An Introduction to JSPs
Author: Danielle Danielsson
Last Revised: 1st February 2001
Java Server PagesT (JSP) is a server-side scripting technology. If you have worked with Microsoft's Active Server Pages (ASP), then you will find a few similarities between the two. The main difference is that while ASP is proprietary and cannot run on non-Microsoft servers, at least not without a plug-in such as ChiliASPT, JSP can be implemented by any vendor, hence the now impressive availablility of JSP and Servlet supporting engines, some freely available, and others at varying commercial prices.
Like ASP, you can use other scripting languages like VBScript and JavaScript. In JSP the default language is Java, consequently, unlike ASP, you have the full power of the Java API in your armory. If you are only beginning to explore Java, you can do so at a very basic level, and then as your proficiency increases you can write very complex server side applications with JSP, Servlets, and JavaBeans.
Unlike ASP, JSP is interpreted only once after the servlet has been compiled. What servlet, you might ask. A JSP is really a servlet. When a JSP page is requested for the very first time, the JSP engine takes all of the contents of the JSP and converts them into a servlet class and then compiles it into bytecode. If there has been no change to the JSP page since its first compilation, the JSP page will be interpreted only once. So, unlike ASP which interprets the code inside every ASP page every time it is called, JSP is interpreted only once. Consequently, JSP's are faster than ASP's.
The main attraction of JSP is that it enables the separation of code from the presentation part of a web page. This is achieved through the use of JavaBeans. Instead of intermingling Java code with HTML in one page, JavaBeans encapsulate the code.
If you are unfamiliar with JavaBeans (oops, here comes another tutorial!), we'll develop a very simple one later in this tutorial to demonstrate how it is used from a JSP. Briefly, a JavaBean contains setter and getter methods eg. setMyAge, getMyAge. These are properties of the JavaBean which can be set or retrieved through JSP Action tags, as shown below.
| Listing 2.1 |
|
<%--Instructs the server instantiate the JavaBean --%>
<jsp:useBean
id="bean_name"
class="package.ClassName"
scope="page | request | session | application"/>
<%-- Retrieves the property of the instantiated JavaBean --%>
<jsp:getProperty name="..." property="...">
<%-- Sets the the property of the instantiated JavaBean--%>
<jsp:setProperty name="..." property="..." value="....">
|
All of the above will become clear after we develop a JSP and a JavaBean that with propterties that are then displayed in the calling JSP. But first, lets take a look at the what constitutes a JSP.
A JSP can consist of Actions, Directives and Variables, as well as our old friend, HTML.
Since we just had a brief look at Actions in Listing 2.1 above, lets start with an overview of JSP Actions.
| JSP Actions |
| Syntax |
Explanation |
| <%=expression %> |
The Expression is evaluated on the server when the JSP is called, and the result is printed into this location in the JSP.
The expression can be in any language specified by the language directive. See the Directives table.
An expression is placed in the service method of the Servlet class. |
| <% scriptlet code %> |
Scriptlet is a short piece of code that is executed on the server.
The language of the scriptlet is specified by the language directive. See the Directives table.
A scriplet is placed in the service method of the Servlet class |
| <%! declaration code %> |
This is code, that is placed in the body of the Servlet class and outside of the service method. |
<jsp:include
page="relative path"/> |
Includes the file specified in the page attribute at the time the page is requested.
If code inside the included file has to be executed, then use the include directive, <!@include file="relative path"> |
| <jsp:forward page="path"/> |
Request is forwarded to page specified in the path attribute. |
|
<jsp:plugin
type="bean|applet"
code="objectCode"
codebase= "objectCodebase"
{align="alignment"}
{archive="archiveList"}
{height="height"}
{hspace="hspace"}
{jreversion="jreversion"}
{name="componentName"}
{vspace="vspace"}
{width="width"}
{nspluginurl="url"}
{iepluginurl="url"}
{<jsp:params>
{<jsp:param name="paramName"
value="paramValue"/ >}+ </jsp:params> }
{<jsp:fallback> any_text
</jsp:fallback> }
>
</jsp:plugin>
|
Used to invoke an applet in the client browser.
Attribute values in red are defined by the HTML specification.
type: defines the type of the component eg. bean or applet;
jreversion: specifies the JRE version that the component requires. The default is 1.1
nspluginurl: url where the required JRE can be downloaded for Netscape Navigator;
iepluginurl: url where the required JRE can be
downloaded for Internet Explorer.
jsp:param: the parameters that are to be passed
in to the component;
jsp:fallback: any text if the client is unable
to load the plugin.
|
| Actions associated with interacting with a JavaBean instance: |
|
<jsp:useBean
id="bean_name"
class="package.class"
scope="page|request|
session|application" />
|
id = name for the bean;
class = JavaBean's class
scope = bean lifetime
page: applies only to page, and is stored in the pageContext object;
Request: applies only to current request and
is stored in the request
object;
Session: applies only to the current session and is stored in the session object;
Application: applies to the current application and is stored in the application object. |
<jsp:getProperty
name="..."
property="..." > |
Retrieves data from the bean.
name = bean name;
property = bean property name;
|
<jsp:setProperty
name="..."
property="..."
{value="..." | param="..."}> |
Sets the property value inside the bean.
name = bean name;
property = bean property name to set. This variable can also take "*", all request paramaters with matching bean property names will be passed on to their respective bean property set methods.
value and param are optional attributes.
value = accepts values of any type. The receiving setter method can user the Object.valueOf to make the conversions if necessary.
param = specifies which request parameter will be the supplier of values to the setter method.
|
| JSP Directives |
There are three directives:
* Include Directive
* Taglib Directive
* Page Directive |
The Include Directive
|
| Syntax |
Explanation |
|
<%@ include file="relative URL" %><%@ include file="relativeURL" %> <%@ include file="relativeURL" %>
<%@ include file="relativeURL" %> |
Inserts a JSP, HTML, or text file contents at this location when the JSP is first compiled. Any code in the called JSP file will be first executed and the results inserted into the calling JSP. |
| The Taglib Directive |
| Syntax |
Explanation |
<%@ taglib
uri="URITOTagLibrary"
prefix="tagPrefix"
%> |
Declares and locates a custom tag library and defines the prefix to be used in the JSP page.
Creation of custom tags is not covered in this tutorial. Hang around for yet another tutorial
:-)
|
| The Page Directive |
| Syntax |
Explanation |
<%@ 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" ]
%> |
The <%@page ...%> directive applies to the entire JSP, and is normally placed at the top of the page.
The directive can be used more than once in the JSP file, but each attribute, with the exception of import, can only be used once in the same file.
Hence, the directive can be broken down into multiple smaller directives eg.
<%@page language="Java"%> ,
<%@page errorPage="relativeUrl"%>.
|
<%@page language="language" %>
sets the language for this page. The default is Java. |
<%@page extends="package.class" %>
Recalling that JSP's are compiled into servlets, this directive explicitly changes the name of the class file generated by the JSP engine. Do not use this directive unless you have good reasons to do so. I can't think of one at all... |
|
<%@page import="{package.class|package.*}"%>
Classes or packages that need to be imported for scriptlets, expressions and declarations.
By default the following packages are imported:
java.lang.*;
java.servlet.*;
java.servlet.jsp.*;
java.servlet.http.*;
|
<%@page session="true|false" %>
Specifies if the JSP is part of a session. The default is true. |
<%@page buffer="none|8Kb|sizeKb" %>
This directive permits the buffering of output before it is sending it out to the client via HTTP. One place where buffering may come in use is in error recovery and forwarding.
For example if some fields in an online form are missing, those fields that have been filled in can be recovered from the buffer and forwarded to the form page for another try at filling in all required fields.
The default size is 8Kb. If buffer is set to none, then all output will be flushed before returning to the client. |
<%@page autoFlush="true|false"%>
If the buffer is full, the buffer will be automatically flushed if set to true, which is the default. If it is set to false and the buffer overflows an error will be generated. |
<%@page isTheadSafe="true|false"%>
Determines thread safety for a particular JSP file. If set to true, the default, multiple clients can simultaneously request this JSP file.
A note of caution: even if set to false, multiple instances of the the same JSP can still be created by the JSP engine. Hence, always ensure that relevant methods are synchronized. |
<%@page info="text"%>
Some text string that can provide information about the JSP file. It can be retrieved with Servlet.getServletInfo() |
<%@page errorPage="realativeURL"%>
Sets the path to the error page that the current page uses to send error messages. |
<%@page isErrorPage="true|false"%>
This directive must be in the file that has been specified in <%@page errorPage="realativeURL"%> to handle error messsages. It provides access to the exception object of the file that threw the error. |
<%@page contentType="mimeType [;charset=characterSet | "text/html;charset=ISO-8859-1"] "%>
Becomes very useful if the JSP sends a response object that handles languages other than Western character types. It can therefore be set to handle foreign language characters. |
JSP Objects
These are objects that are available to every JSP without the need to first define them. |
| Type |
Explanation |
request
javax.servlet.HttpServletRequest |
Contains information sent by the client, to the server. eg. if a form has been sent then this object will contain the form field entries. |
response
javax.servlet.HttpServletResponse |
The servlet's response object. It will return the requested data to the client. |
out
javax.servlet.jsp.jspWriter |
The buffered stream output in response to the HTTP request. Used mainly in scriptlets. |
pageContext
javax.servlet.jsp.PageContext
|
The context of the current page. |
application
javax.servlet.ServletContext |
The servlet context supplied by the configuration object. |
config
javax.servlet.jsp.ServletConfig |
The ServletConfig object for the current page. |
exception
java.lang.Throwable |
The uncaught exception that caused the error page to be invoked. |
session
javax.servlet.HttpSession |
The session object that is returned to the client. |
Finally we can put some of what we've learnt to a test.
Lets first take a look at the JavaBean.
| Listing 2.4 MySimpleBean.java |
|
package servlet_tutorials.SimpleServlet;
public class MySimpleBean {
public String destination = null;
public MySimpleBean() {}
public String getInternals(){
// Create the HTML for output to the browser
//
String pageText = "<P><CENTER><FONT COLOR='GREEN'><H2>All great journeys start with one small step.</H2></FONT></CENTER>";
return pageText;
}
public void setMyDestination(String destination){
this.destination = destination;
}
public String getMyDestination(){
return this.destination;
}
}
|
Next, we'll write the JSP that will communicate with the JavaBean.
| Listing 2.2 JSP file interacting with a JavaBean |
|
<HTML>
<%-- JSP Directives Syntax: --%>
<%@ page buffer=35 %>
<%@ page errorPage="error.jsp" %>
<%--JSP Action tag --%>
<jsp:useBean id="simplebean" class="servlet_tutorials.SimpleServlet.MySimpleBean"/>
<BODY> Message from the bean's belly:
<jsp:getProperty name="simplebean" property="internals"/> <p>
And here we go again...
<%-- An example of accessing the property via Java expression Syntax: <%= expression %> --%>
<%=simplebean.getInternals() %>
<%-- Set the destination. The format shown is known as a scriptlet, Syntax: <% java code goes here %> ie. Java code is inserted into the JSP --%>
<%simplebean.setMyDestination("Paraguay");%>
We're on our way to ...
<%-- Get the destination --%>
<jsp:getProperty name="simplebean" property="mydestination"/>
and
<%-- Set the destination --%>
<jsp:setProperty name="simplebean" property="mydestination" value="Colombia"/>
<%-- Get the destination by using a Java expression, and give it some color this time. --%>
<font color="red">
<%=simplebean.getMyDestination()%>
<%-- Lets test the use of a declaration --%>
<%! String my_destination; %>
<% my_destination = simplebean.getMyDestination(); %> and lastly, <%=my_destination%>
</font>
</BODY>
</HTML>
|
All of the above will produce the following output,
| Listing 2.3 error.jsp |
<html>
<%@ page isErrorPage="true" %>
<head> <title>Error!</title>
</head>
<BODY BGCOLOR=#9999cc>
<TABLE CELLSPACING=0 WIDTH=100%>
<TR bgcolor="#9999cc">
<TD>
<font size="+2" color="#FFFF33">
Error!
</font>
</TABLE>
<font size="+7" face="Verdana, Arial, Helvetica, sans-serif">An error has occurred!</font> <font face="Verdana, Arial, Helvetica, sans-serif" size="+2"><BR>Something has gone sorely wrong! <br> Try again. If that too fails, send a message explaining the error to the
<A HREF="mailto:danielsson@consultant.com">administrator</A></FONT><BR CLEAR=ALL> <B><U>Details:</U></B> <PRE> <%= exception.toString() %> </PRE> </BODY> </HTML> |
The error screen looks like this,

Well, we've covered a lot of theory and wrote a bit of code to see some of the theory in action. As you can see, there is a lot to JSP, and it provides a good basis for developing object oriented, extensible and maintainable web based applications.
A frequent question asked by those new to JSP/Servlet technologies is when to use JSP and when to go for a Servlet. This will be answered in Part 3, where we'll cover the architecture of applications that are developed with JSP and Servlets, and provide an example of the development of a web-based searchable phonebook.
See you in Part 3!
|