Popular Posts

Saturday, May 30, 2009

Example Using Scripting Elements and Directives

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Using JavaServer Pages</TITLE>

<META NAME="author" CONTENT="Marty Hall -- hall@apl.jhu.edu">
<META NAME="keywords"
CONTENT="JSP,JavaServer Pages,servlets">
<META NAME="description"
CONTENT="A quick example of the four main JSP tags.">
<LINK REL=STYLESHEET
HREF="My-Style-Sheet.css"
TYPE="text/css">
</HEAD>

<BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE"
VLINK="#551A8B" ALINK="#FF0000">

<CENTER>
<TABLE BORDER=5 BGCOLOR="#EF8429">
<TR><TH CLASS="TITLE">
Using JavaServer Pages</TABLE>
</CENTER>
<P>

Some dynamic content created using various JSP mechanisms:
<UL>
<LI><B>Expression.</B><BR>
Your hostname: <%= request.getRemoteHost() %>.
<LI><B>Scriptlet.</B><BR>
<% out.println("Attached GET data: " +
request.getQueryString()); %>
<LI><B>Declaration (plus expression).</B><BR>
<%! private int accessCount = 0; %>
Accesses to page since server reboot: <%= ++accessCount %>
<LI><B>Directive (plus expression).</B><BR>
<%@ page import = "java.util.*" %>
Current date: <%= new Date() %>
</UL>


</BODY>
</HTML>

Here's a typical result:

request,response,out,session,application,config,pageContext,page

request
This is the HttpServletRequest associated with the request, and lets you look at the request parameters (via getParameter), the request type (GET, POST, HEAD, etc.), and the incoming HTTP headers (cookies, Referer, etc.). Strictly speaking, request is allowed to be a subclass of ServletRequest other than HttpServletRequest, if the protocol in the request is something other than HTTP. This is almost never done in response
This is the HttpServletResponse associated with the response to the client. Note that, since the output stream (see out below) is buffered, it is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client.
out
This is the PrintWriter used to send output to the client. However, in order to make the response object (see the previous section) useful, this is a buffered version of PrintWriter called JspWriter. Note that you can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive. This was discussed in Section 5. Also note that out is used almost exclusively in scriptlets, since JSP expressions automatically get placed in the output stream, and thus rarely need to refer to out explicitly.
session
This is the HttpSession object associated with the request. Recall that sessions are created automatically, so this variable is bound even if there was no incoming session reference. The one exception is if you use the session attribute of the page directive (see Section 5) to turn sessions off, in which case attempts to reference the session variable cause errors at the time the JSP page is translated into a servlet.
application
This is the ServletContext as obtained via getServletConfig().getContext().
config
This is the ServletConfig object for this page.
pageContext
JSP introduced a new class called PageContext to encapsulate use of server-specific features like higher performance JspWriters. The idea is that, if you access them through this class rather than directly, your code will still run on "regular" servlet/JSP engines.
page
This is simply a synonym for this, and is not very useful in Java. It was created as a placeholder for the time when the scripting language could be something other than Java.

Predefined Variables

To simplify code in JSP expressions and scriptlets, you are supplied with eight automatically defined variables, sometimes called implicit objects. The available variables are request, response, out, session, application, config, pageContext, and page. Details for each are given below.

The JSP include Directive

This directive lets you include files at the time the JSP page is translated into a servlet. The directive looks like this:

<%@ include file="relative url" %>

The URL specified is normally interpreted relative to the JSP page that refers to it, but, as with relative URLs in general, you can tell the system to interpret the URL relative to the home directory of the Web server by starting the URL with a forward slash. The contents of the included file are parsed as regular JSP text, and thus can include static HTML, scripting elements, directives, and actions.

For example, many sites include a small navigation bar on each page. Due to problems with HTML frames, this is usually implemented by way of a small table across the top of the page or down the left-hand side, with the HTML repeated for each page in the site. The include directive is a natural way of doing this, saving the developers from the maintenance nightmare of actually copying the HTML into each separate file. Here's some representative code:




Servlet Tutorial: JavaServer Pages (JSP) 1.0



HREF="Site-Styles.css"
TYPE="text/css">



<%@ include file="/navbar.html" %>






Note that since the include directive inserts the files at the time the page is translated, if the navigation bar changes, you need to re-translate all the JSP pages that refer to it. This is a good compromise in a situation like this, since the navigation bar probably changes infrequently, and you want the inclusion process to be as efficient as possible. If, however, the included files changed more often, you could use the jsp:include action instead. This includes the file at the time the JSP page is requested, and is discussed in the tutorial

The JSP page Directive

The page directive lets you define one or more of the following case-sensitive attributes:

* import="package.class" or import="package.class1,...,package.classN". This lets you specify what packages should be imported. For example:
<%@ page import="java.util.*" %>
The import attribute is the only one that is allowed to appear multiple times.
* contentType="MIME-Type" or
contentType="MIME-Type; charset=Character-Set"
This specifies the MIME type of the output. The default is text/html. For example, the directive
<%@ page contentType="text/plain" %>
has the same effect as the scriptlet
<% response.setContentType("text/plain"); %>
* isThreadSafe="true|false". A value of true (the default) indicates normal servlet processing, where multiple requests can be processed simultaneously with a single servlet instance, under the assumption that the author synchronized access to instance variables. A value of false indicates that the servlet should implement SingleThreadModel, with requests either delivered serially or with simultaneous requests being given separate servlet instances.
* session="true|false". A value of true (the default) indicates that the predefined variable session (of type HttpSession) should be bound to the existing session if one exists, otherwise a new session should be created and bound to it. A value of false indicates that no sessions will be used, and attempts to access the variable session will result in errors at the time the JSP page is translated into a servlet.
* buffer="sizekb|none". This specifies the buffer size for the JspWriter out. The default is server-specific, but must be at least 8kb.
* autoflush="true|false". A value of true, the default, indicates that the buffer should be flushed when it is full. A value of false, rarely used, indicates that an exception should be thrown when the buffer overflows. A value of false is illegal when also using buffer="none".
* extends="package.class". This indicates the superclass of servlet that will be generated. Use this with extreme caution, since the server may be using a custom superclass already.
* info="message". This defines a string that can be retrieved via the getServletInfo method.
* errorPage="url". This specifies a JSP page that should process any Throwables thrown but not caught in the current page.
* isErrorPage="true|false". This indicates whether or not the current page can act as the error page for another JSP page. The default is false.
* language="java". At some point, this is intended to specify the underlying language being used. For now, don't bother with this since java is both the default and the only legal choice.

The XML syntax for defining directives is



For example, the XML equivalent of

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

is

JSP Directives

A JSP directive affects the overall structure of the servlet class. It usually has the following form:

<%@ directive attribute="value" %>

However, you can also combine multiple attribute settings for a single directive, as follows:

<%@ directive attribute1="value1"
attribute2="value2"
...
attributeN="valueN" %>

There are two main types of directive: page, which lets you do things like import classes, customize the servlet superclass, and the like; and include, which lets you insert a file into the servlet class at the time the JSP file is translated into a servlet. The specification also mentions the taglib directive, which is not supported in JSP version 1.0, but is intended to let JSP authors define their own tags. It is expected that this will be the main new contribution of JSP 1.1.

JSP Declarations

A JSP declaration lets you define methods or fields that get inserted into the main body of the servlet class (outside of the service method processing the request). It has the following form:

<%! Java Code %>

Since declarations do not generate any output, they are normally used in conjunction with JSP expressions or scriptlets. For example, here is a JSP fragment that prints out the number of times the current page has been requested since the server booted (or the servlet class was changed and reloaded):

<%! private int accessCount = 0; %>
Accesses to page since server reboot:
<%= ++accessCount %>

As with scriptlets, if you want to use the characters "%>", enter "%\>" instead. Finally, note that the XML equivalent of <%! Code %> is


Code

JSP Scriptlets

If you want to do something more complex than insert a simple expression, JSP scriptlets let you insert arbitrary code into the servlet method that will be built to generate the page. Scriptlets have the following form:

<% Java Code %>

Scriptlets have access to the same automatically defined variables as expressions. So, for example, if you want output to appear in the resultant page, you would use the out variable.

<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>

Note that code inside a scriptlet gets inserted exactly as written, and any static HTML (template text) before or after a scriptlet gets converted to print statements. This means that scriptlets need not contain complete Java statements, and blocks left open can affect the static HTML outside of the scriptlets. For example, the following JSP fragment, containing mixed template text and scriptlets

<% if (Math.random() < 0.5) { %>
Have a nice day!
<% } else { %>
Have a lousy day!
<% } %>

will get converted to something like:

if (Math.random() < 0.5) {
out.println("Have a nice day!");
} else {
out.println("Have a lousy day!");
}

If you want to use the characters "%>" inside a scriptlet, enter "%\>" instead. Finally, note that the XML equivalent of <% Code %> is


Code

JSP Expressions

A JSP expression is used to insert Java values directly into the output. It has the following form:

<%= Java Expression %>

The Java expression is evaluated, converted to a string, and inserted in the page. This evaluation is performed at run-time (when the page is requested), and thus has full access to information about the request. For example, the following shows the date/time that the page was requested:

Current time: <%= new java.util.Date() %>

To simplify these expressions, there are a number of predefined variables that you can use. These implicit objects are discussed in more detail later, but for the purpose of expressions, the most important ones are:

* request, the HttpServletRequest;
* response, the HttpServletResponse;
* session, the HttpSession associated with the request (if any); and
* out, the PrintWriter (a buffered version of type JspWriter) used to send output to the client.

Here's an example:

Your hostname: <%= request.getRemoteHost() %>

Finally, note that XML authors can use an alternative syntax for JSP expressions:


Java Expression


Remember that XML elements, unlike HTML ones, are case sensitive. So be sure to use lowercase.

JSP Scripting Elements

JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. There are three forms:

1. Expressions of the form <%= expression %> that are evaluated and inserted into the output,
2. Scriptlets of the form <% code %> that are inserted into the servlet's service method, and
3. Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods.

Each of these is described in more detail below.

Template Text: Static HTML

In many cases, a large percent of your JSP page just consists of static HTML, known as template text. In all respects except one, this HTML looks just like normal HTML, follows all the same syntax rules, and is simply "passed through" to the client by the servlet created to handle the page. Not only does the HTML look normal, it can be created by whatever tools you already are using for building Web pages. For example, I used Allaire's HomeSite for most of the JSP pages in this tutorial.

The one minor exception to the "template text is passed straight through" rule is that, if you want to have "<%" in the output, you need to put "<\%" in the template text.

OVERVIEW

JavaServer Pages (JSP) lets you separate the dynamic part of your pages from the static HTML. You simply write the regular HTML in the normal manner, using whatever Web-page-building tools you normally use. You then enclose the code for the dynamic parts in special tags, most of which start with "<%" and end with "%>". For example, here is a section of a JSP page that results in something like "Thanks for ordering Core Web Programming" for a URL of http://host/OrderConfirmation.jsp?title=Core+Web+Programming:

Thanks for ordering
<%= request.getParameter("title") %>

You normally give your file a .jsp extension, and typically install it in any place you could place a normal Web page. Although what you write often looks more like a regular HTML file than a servlet, behind the scenes, the JSP page just gets converted to a normal servlet, with the static HTML simply being printed to the output stream associated with the servlet's service method. This is normally done the first time the page is requested, and developers can simply request the page themselves when first installing it if they want to be sure that the first real user doesn't get a momentary delay when the JSP page is translated to a servlet and the servlet is compiled and loaded. Note also that many Web servers let you define aliases that so that a URL that appears to reference an HTML file really points to a servlet or JSP page.

Aside from the regular HTML, there are three main types of JSP constructs that you embed in a page: scripting elements, directives, and actions. Scripting elements let you specify Java code that will become part of the resultant servlet, directives let you control the overall structure of the servlet, and actions let you specify existing components that should be used, and otherwise control the behavior of the JSP engine. To simplify the scripting elements, you have access to a number of predefined variables such as request in the snippet above.

Note that this tutorial covers version 1.0 of the JSP specification. JSP has changed dramatically since version 0.92, and although these changes were almost entirely for the better, you should note that version 1.0 JSP pages are almost totally incompatible with the earlier JSP engines. Note that this JSP tutorial is part of a larger tutorial on servlets and JSP at http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/.