Docstoc

Introduction-to-JavaServer-Pages

Document Sample
Introduction-to-JavaServer-Pages Powered By Docstoc
					Introduction to JavaServer Pages
Server-Side Scripting the Java Way
By

JavaServer Pages™ (JSP) is a web-scripting technology similar to Netscape server-side
JavaScript (SSJS) or Microsoft Active Server Pages (ASP). However, it's more easily extensible
than SSJS or ASP, and it isn't proprietary to any one vendor or any particular web server.
Although the JSP specification has been managed by Sun Microsystems, any vendors can
implement JSP in their own systems.

If you're working with Netscape technologies today or are planning to in the future, you should
start learning about JSP, because Netscape will soon be introducing products that use it. They've
already announced that the next version of Netscape Application Server (NAS) will use JSP as a
presentation layer technology. In this article, I'll introduce you to JSP: its features, target users,
and intended use. I'll compare JSP to some current Netscape technologies, such as SSJS and
NAS's presentation markup language.

JSP BASICS

JSP is a presentation layer technology that sits on top of a Java Servlets model and makes
working with HTML easier. Like SSJS, it allows you to mix static HTML content with server-side
scripting to produce dynamic output. By default, JSP uses Java as its scripting language;
however, the specification allows other languages to be used, just as ASP can use other
languages (such as JavaScript and VBScript). While JSP with Java will be more flexible and
robust than scripting platforms based on simpler languages like JavaScript and VBScript, Java
also has a steeper learning curve than simple scripting languages.

To offer the best of both worlds - a robust web application platform and a simple, easy-to-use
language and tool set - JSP provides a number of server-side tags that allow developers to
perform most dynamic content operations without ever writing a single line of Java code. So
developers who are only familiar with scripting, or even those who are simply HTML designers,
can use JSP tags for generating simple output without having to learn Java. Advanced scripters
or Java developers can also use the tags, or they can use the full Java language if they want to
perform advanced operations in JSP pages.

Pages Are Passé, Components Are Cool

To understand how JSP can accomplish the magic act of ease of use combined with "unlimited"
power, you must first understand the difference between component-centric and page-centric
web development.

Both SSJS and ASP were designed years ago when the web was young and no one knew any
better than to dump all their business, data, and presentation logic into scripted web pages. This
page-centric model was easy to learn and allowed for fairly rapid development. However, over
time people realized that this wasn't the way to build large, scalable web applications. The logic
written for the scripted environments was locked inside pages and was reusable only through cut
and paste. Presentation logic was regularly mixed with business and data logic, making
application maintenance an exercise in walking on eggshells, as programmers attempted to
modify the look and feel of an application without breaking the tightly coupled business logic.
Sophisticated, reusable components already existed in the enterprise, and no one wanted to
rewrite that logic for their web applications. HTML and graphics designers handed over the
implementation of their designs to web scripters, who had to duplicate the work - often by hand,
because no decent tools existed for combining server-side scripting with HTML content
generation. In short, web application complexity increased steadily and the limitations of the
page-centric model became obvious.

Around the same time that people were looking around for better ways to build web applications,
components were all the rage in the client-server world. JavaBeans and ActiveX were being
pushed to Java and Windows application developers by rapid application development (RAD)
tools vendors as the way to develop complex applications quickly. These technologies also
enabled domain experts to write components for vertical applications, which developers could
then use without having significant domain expertise. For example, the developer of a Java
application that charts the mating habits of lemmings need not know anything about lemmings;
she can just invoke the LemmingsInLove JavaBeans component to obtain the relevant domain-
specific information, and focus instead on making the application easy to use. It was only a matter
of time before a technology emerged to bring component-centric programming to the world of
server-side Web applications.

JSP comes out of the gate as a component-centric platform. It's based on a model in which
JavaBeans and Enterprise JavaBeans (EJB) components contain the business and data logic for
an application, and it provides tags and a scripting platform for exposing the content generated or
returned by the beans in HTML pages. Because of the component-centric nature of JSP, it can be
used by non-Java and Java developers alike. Non-Java developers can use the JSP tags to work
with beans that experienced Java developers created. Java developers can not only make and
use beans but also use Java in JSP pages for finer-grained control over presentation logic that's
based on underlying beans.

JSP Request Model

Now let's take a look at how HTTP requests are processed under the JSP model. In the basic
request model, a request is sent directly to a JSP page. Figure 1 illustrates the flow of information
in this model. JSP code controls interactions with JavaBeans components for business and data
logic processing, and then displays the results in dynamically generated HTML mixed with static
HTML code.



The beans depicted can be JavaBeans or EJB components. Other, more complicated request
models include calling out to other JSP pages or Java Servlets from the requested JSP page.

TAG, YOU'RE IT

Before learning how to go about scripting your JSP pages with Java, you need to know about the
server-side JSP elements, called actions, that perform server-side tasks without requiring Java
coding. Action tags can be employed by advanced content designers or by scripters who might
not be familiar with Java but still want to display values held in JavaBeans components. As
mentioned earlier, most of the tags are based on the component-centric web development model.
First I'll describe some of the action tags provided, and then I'll show you an example JSP page
that uses only tags to display information from a bean - no Java coding required.

Loading a Bean - <jsp:usebean>
Remember, the JSP model revolves around beans, so most of the JSP tags assume you'll be
working with information that resides in a bean. Before you can use a bean in a JSP page, you
must declare that you're about to use it by invoking the <jsp:usebean> action tag. As you'll
learn later, depending on the scope (life cycle) that you declare for the bean, the tag may or may
not generate a new instance of the bean for use within the page (the instance may have been
generated earlier in the session or application).

The <jsp:usebean> tag takes arguments that specify:

       The JavaBeans class
       The name of the bean instance
       The scope for the bean, as I'll discuss shortly

For example:

<jsp:usebean ID="myBeanInstance" CLASS="com.myPackage.myBeanClass"
SCOPE="request">
   ...body...
</jsp:usebean>

Here the <jsp:usebean> tag is followed by a body section that's invoked when the bean is
created, and then an ending </jsp:usebean> tag. If the body is empty, you can alternatively
use this simpler form:

<jsp:usebean ID="myBeanInstance" CLASS="com.myPackage.myBeanClass"
SCOPE="request"/>

This example will generate an instance of the bean defined in the
com.myPackage.myBeanClass class and will name the reference myBeanInstance in the
page; this instance will exist only for the life cycle of a single HTTP request for the JSP page. The
bean can now be used in the page.

Initializing a Bean - <jsp:setProperty>

Not all beans can simply be created and then used; some require initialization before use. In the
body section within the <jsp:useBean> and </jsp:useBean> tags, you can initialize
properties of the bean with the <jsp:setProperty> tag. You can set bean properties either to
values that you specify or to values passed in from an HTTP request, such as from a form
submission.

To initialize a bean property named myProperty with a value that you specify, you could use
this format:

<jsp:usebean ID="myBeanInstance" CLASS="com.myPackage.myBeanClass"
SCOPE="request">
    <jsp:setProperty NAME="myBeanInstance" PROPERTY="myProperty"
VALUE="123"/>
</jsp:usebean>
The following format initializes the same bean property with a value passed in from an HTML
form element or in a URL query string:
<jsp:usebean ID="myBeanInstance" CLASS="com.myPackage.myBeanClass"
SCOPE="request">
    <jsp:setProperty NAME="myBeanInstance" PROPERTY="myProperty"
        PARAM="myFormElementName"/>
</jsp:usebean>
Note that you cannot use both the VALUE and the PARAM attributes in the same
<jsp:setProperty> tag.

In addition to using <jsp:setProperty> in the body of a <jsp:useBean> action, you can use
it by itself within a JSP page. Before doing so, you must first have defined a bean with the proper
scope using the <jsp:useBean> tag.

Scope of a Bean

The SCOPE attribute of the <jsp:useBean> tag performs a very simple function: it sets the
scope, or life cycle, of the associated bean to one of four possible values, as described in Table
1. You can use beans of different scopes to maintain state within your JSP applications.

                         Table 1. Scope and state maintenance in JSP
                    Scope                           Description
                Page             Object is accessible only by a single client from
                                 the page on which it is created.
                Request          Object is accessible by a single client for the
                                 lifetime of a single client request.
                Session          Object is accessible by a single client from
                                 anywhere in the application for the lifetime of an
                                 entire user session.
                application Object accessible is by any client from any page
                            within the application for the lifetime of the
                            application.



The various object scopes affect how the <jsp:useBean> tag creates or retrieves instances of
beans. Page and request beans are destroyed by the time the client request has been fulfilled
and output has been sent back to the browser. Therefore the <jsp:useBean> tag must create a
new instance of a page or request bean with every new request. However, once you create a
session bean, that bean instance remains for the lifetime of the session or until you explicitly
destroy it. Thus the <jsp:useBean> tag creates a new instance of the bean if it does not
already exist for the current session; otherwise, it simply retrieves the current instance of the
bean. The same rules apply for application beans except that they expire when an application is
reloaded or when the server is restarted.

If you're an SSJS developer, it's helpful to draw some paralells to SSJS session management. In
SSJS terms, a page bean would have the same scope as a property of the request object, a
session bean the same scope as a property of the client object, and an application bean the
same scope as a property of the project object. For example, if you store values in a session
bean, you can access those values from any JSP page thereafter for a single user just as you
could do from SSJS pages for properties that you store in the client object. However, JSP
provides a more flexible state maintenance mechanism than SSJS, because you can define any
number of page, request, session, and application beans. In SSJS, the request, client and
project objects are all singletons.
Note that a request bean has no direct counterpart in SSJS. That's because unlike SSJS, JSP
allows you to execute more than one page during a single client request. I'll talk more about this
feature later.

Displaying Dynamic Content - <jsp:getProperty>

Once you've created a bean, you can use it to generate content dynamically within a JSP page.
JSP defines a <jsp:getProperty> tag for displaying a property of a bean that has been
defined on the page by a <jsp:useBean> tag, or that was defined as a session or application
bean earlier in the application. The <jsp:getProperty> tag has two attributes: NAME and
PROPERTY. NAME indicates the source object previously defined in a <jsp:useBean> tag, and
PROPERTY indicates the object property value to display. For example:
<jsp:usebean ID="myBeanInstance" CLASS="com.myPackage.myBeanClass"
SCOPE="request"/>
<H2> myProp=<jsp:getProperty NAME="myBeanInstance" PROPERTY="myProp">
</H2>
As you can see, you can mix HTML tags with JSP <jsp:getProperty> tags to dynamically
generate and format HTML content.

Redirecting to an External Page - <jsp:request>

JSP defines a tag, <jsp:request>, that you can use to redirect to an external page in one of
two ways, as specified by the FORWARD attribute or the INCLUDE attribute.

With the FORWARD attribute, you can redirect to any valid URL. This effectively halts processing of
the current page at the point where the redirect occurs, although all processing up to that point
will still take place. This is exactly analogous to a typical redirect using CGI, SSJS, ASP, or
JavaScript.

With the INCLUDE attribute, you can not only redirect to another page but also come back to the
calling page upon completion of processing in the called page. For instance, you could actually
call out to another JSP page that generates some HTML dynamically and have that page
generate its HTML; upon returning, that HTML would be inserted into the calling page at the point
where your <jsp:request> tag occurs. In fact, the called page has no idea that it's being called
from another JSP page. It simply sees an HTTP request and responds by returning HTML text.

Keep in mind that you can use the INCLUDE method of redirection to access static HTML pages,
JSP pages, servlets, SSJS pages, ASP pages - just about any resource that responds to HTTP
requests and generates a response that you want to include in your page. But note that if the
resource you access returns a complete HTML page, including <HTML> and <BODY> tags, you
may not get the result you intended.

A Simple Example

In Example 1 I instantiate a bean of type jsp.beans.samples.SuperSimpleBean and name
it ssb. Because I've set its scope to session, this bean will be available for the rest of the user
session. In other words, I'll be able to access it by name from any page in the application after it
has been instantiated here. I go on to initialize the counter property to 1. Then I use the
<jsp:getProperty> action tag to display the value of counter in the HTML page. This code
is simple enough for an HTML designer to write, given the names of some relevant bean
properties.
Example 1

<HTML>
<HEAD>
<META NAME="GENERATOR" Content="NetObjects ScriptBuilder 2.01">
<TITLE>Counter Page</TITLE>
</HEAD>
<BODY>

<jsp:useBean ID="ssb" SCOPE="session"
CLASS="jsp.beans.samples.SuperSimpleBean"/>
<jsp:setProperty NAME="ssb" PROPERTY="counter" VALUE="2"/>

<h2>Counter: <jsp:getProperty NAME="ssb" PROPERTY="counter"/></h2>

</BODY>
</HTML>




CAFFEINATED SCRIPTING

If you work with straight Java servlets, you have to deal with HTTP input and HTML output from
within Java classes, and you need significant Java experience to build complex applications. With
JSP thrown into the mix, you can separate your HTML presentation logic from the more complex
business logic embedded in servlets. This means that developers who are experienced with
scripting can write the presentation code while more experienced Java developers can focus on
solving complex problems in servlets and beans.

JSP can be used with or without Java programming knowledge. In fact, JSP contains a few
server-side tags that make it possible to display dynamic data without writing a single line of Java
code. You can access beans directly to perform operations and then use JSP tags to display
results as dynamic content. You can also use servlets that generate beans which hold results of
the servlet operations, and again use JSP tags to display the results without requiring Java
coding in the JSP page.

There are three ways to include Java code in your page:

       Using declarations, you can define either global variables for the page or Java methods
        that can be accessed from anywhere within the page. Declarations are enclosed between
        <%!...%>.
       With scriptlets, you can write just about any logic you need for in-page processing
        between <%...%>.
       Expressions between <%=...%> provide a simple way to display the results of Java
        expressions. The enclosed expression will be evaluated and displayed on the page as if
        you had explicitly written out the resulting value in code.

In your blocks of custom code, you can make use of several implicit variables - predefined Java
objects provided by JSP. Additionally, you can include blocks of non-JSP code, such as HTML or
text from other files, using JSP directives.

We'll now look at each of these scripting elements more closely, because you'll use them
frequently if you write your own JSP scripts.
Directives

JSP defines three in-page directives that either configure JSP parameters or extend the code on
your page. These directives - page, include, and taglib - must be specified as the first line of
a JSP page. The syntax is as follows:

<%@ directive attribute="value" ... %>

The page directive allows you to set several attributes that essentially configure a page. This
includes attributes for setting the scripting language of the page (the default being Java),
importing Java classes for use in your scriptlets, configuring output buffering, and so forth. See
section 2.8.1 of the JSP Specification Version 1.0 for a complete list of page directive attributes.

With the include directive, you can include content from other files, such as HTML headers and
footers that are stored in separate files. The taglib directive is used for extending the set of
valid JSP tags, and is beyond the scope of this article. However, it's good to know that JSP
defines a way to extend its set of tags, especially if you're a software vendor who would like to
extend JSP's native functionality without breaking compatibility.

Declarations

With declarations, you can define methods or variables in a JSP page that will be accessible to
other code within the same page. In most cases, you'll probably define methods within custom
beans. However, occasionally it may be more convenient to define methods within the page itself,
especially if the code applies to only a single page. Whether you're defining methods or variables,
declarations are enclosed between <%! %>.

Note that declarations do not produce any output in a JSP page. They're simply for defining
things, not for generating output. To generate output, you use JSP expressions or scriptlets.
Expressions
                                                                      UNDER THE HOOD
Expressions are very simple JSP tags that convert the value
of a valid JSP expression defined between <%= %> into a          Just how does JSP work? The
                                                                 JSP engine actually transforms
string and emit that value as dynamically generated text.
                                                                 JSP tags, Java code in a JSP
Expressions are really just shortcuts for generating text so
                                                                 page, and even static HTML
that you don't have call the println() method every time
                                                                 content into chunks of Java code.
you want to display a piece of dynamic text. Typically you'll
                                                                 These chunks are automatically
use expressions to display simple values of variables or
                                                                 organized by the JSP engine into
return values of bean methods. For example, the following
                                                                 an underlying Java servlet, which
code will generate the return value of the getName()             site visitors never see, and the
method:                                                          servlet is then automatically
                                                                 compiled into Java bytecodes.
<H2>Welcome, <%= mybean.getName() %></H2>                        Thus, when a site visitor requests
                                                                 a JSP page, unbeknownst to him
JSP must actually translate the return value of methods into     a generated, precompiled servlet
Java String objects before generating the output. The JSP        actually does all the work. Very
specification describes which Java types and classes JSP         sneaky - and efficient. Because
will convert to strings in JSP expressions.                      the servlet is compiled, the JSP
                                                                 code in a page does not need to
                                                                 be interpreted every time a page
Scriptlets                                                       is requested. The JSP engine only
                                                                 needs to compile the generated
So far you've learned that you can use directives to import      servlet once after the last code
any Java class or package, you can define page-level             change was made; thereafter the
methods and variables for use throughout the page, and you       compiled servlet is executed.
have access to some implicit variables that provide common       Because the JSP engine, and not
web processing functionality. The rest of what you can do        the JSP programmer, generates
inside a JSP page is up to you, because you can write just       and compiles the servlet
about any Java code that your heart desires in scriptlets, as    automatically, JSP gives you both
follows:                                                         efficient performance and the
                                                                 flexibility of rapid development
<% ...code... %>                                                 with no need to manually compile
                                                                 code.
By using the IMPORT attribute of the page directive, you
have access to all Java APIs from within your scriptlet code.    If you download the JSP reference
Because the JSP code you write is really compiled into code      implementation from Sun's site
that makes up a Java servlet, which is just a Java class, the    and write any applications with it,
language you're writing in is straight Java, not a modified or   you'll be able to see the .java
trimmed-down version of it. Just as in SSJS, you can write       and .class files generated by
any code you want. Unlike in SSJS, you have complete             the JSP engine. If you want to
access to the rich set of Java APIs, so the sky's the limit.     learn more about the generated
                                                                 code, just open up the .java file
Implicit Variables                                               in a text editor to examine the
                                                                 generated Java servlet.
As mentioned earlier, JSP defines several implicit variables
(Java objects) that you can use within expressions or scriptlets. Table 2-2 of the JSP
Specification Version 1.0 lists the implicit objects available in JSP 1.0. Here are a few of the more
commonly used objects:

       The out object, of type javax.servlet.jsp.JspWriter, provides access to
        methods, such as println(), for generating output within scriptlets.
       The request object corresponds directly to the Java
        javax.servlet.http.HttpServletRequest class and has all of the same
        properties and methods as any object of that class. For instance, to get a value passed in
        from an HTML form or URL query string, you can call the request.getParameter()
        method and get the parameter by name.
       The response object corresponds directly to the Java
        javax.servlet.http.HttpServletResponse class and provides access to
        parameters associated with the HTML responses your page will generate. So, to add a
        value to the response header of the HTML page returned by your JSP page, you could
        call the response.setHeader() method to add the value to the header.

ANOTHER SIMPLE EXAMPLE

For this next example, we'll look at the interaction between a form and its JSP form handler.
Using some of the scripting elements just discussed, I've implemented a simple web site
feedback form (Figure 2) and a JSP form handler that validates the input and conditionally
generates output based on the feedback.



The form handler will validate the name and comment fields of the form to make sure they aren't
blank. If either one or both of them are blank, the form handler will generate an error message;
otherwise, it will next see if the comment matches a predefined string. If so, it will print a special
message; otherwise, it will print a standard thank-you note.


Example 2

<HTML>
<HEAD>
<META NAME="GENERATOR" Content="NetObjects ScriptBuilder 2.01">
<TITLE>Feedback Results</TITLE>
</HEAD>

<%!
// The name and comment aren't allowed to be blank,
// so check their values and return a result.
  boolean validateInput(String name, String comment) {
  boolean result = true;

  // If the name or comment are blank, return false
  // to indicate the input is invalid
  if (name.length() == 0)
     result = false;
  if (comment.length() == 0)
     result = false;

  return result;
} // end validateInput


// Write out a result based on the comment from the form
String getStringCheese (String comment) {
     String cheese = "I like cheese.";
     String result;

     if (comment.compareTo(cheese) == 0)
       result = "We like cheese too!";
     else
       result = "We hope someday you'll learn to like cheese.";

  return result;
} // end getStringCheese

%>

<BODY BGCOLOR="#F0F0E0">

<%

     // Get   form fields passed in from the form submission
     String   name = request.getParameter("name");
     String   age = request.getParameter("age");
     String   comment = request.getParameter("comment");

     boolean isValid;
     isValid = validateInput(name, comment);

     // Conditional output based on whether the user left
     // the name or comment fields blank

     if (isValid) {
%>

<H2>Thank you for your feedback!</H2>

<H3>
<%
       // Write out the result of the comment check
       out.println(getStringCheese(comment));
     } // end if block
     else {
       out.println("You didn't give us your name or a comment.");
%>
</H3>

Please <a href="feedback_form.html">try again</a>

<%
     } // end else block
%>

</BODY>
</HTML>
For this example, assume the user enters the comment "I like cheese." As you can see from the
code, the response is customized for people who make this comment. The form handler should
return a page like the one shown in Figure 3.




The example is fairly straightforward; even if you're only a JavaScript programmer you can
probably follow it. I'll point out a few features that it illustrates that might not be obvious from the
JSP specification. First, note that in the declarations section (the section between <%!...%>) I
defined some methods just as I would define methods in a Java class. That's because under the
hood JSP translates these methods into methods of the underlying Java servlet that's actually
executed by the server when the page is requested by a browser. Therefore, any variables and
methods that you declare must follow standard Java syntax.

Also note that I actually split up an if..else statement in my scriptlet code across two different
scriptlet blocks. This is perfectly legal! Not only is it legal, but interleaving scriptlet code and static
HTML is a great way to conditionally generate HTML, as I've done in this example.

Finally, you can see that I accessed the form element values by calling the
request.getParameter() method and assigning the values to temporary variables. This is
the standard way to handle input values from forms and query strings.

JSP, SSJS, AND NAS

JSP doesn't replace or necessarily threaten SSJS as a web development platform; each has a
place in the market. While JSP is generally more powerful and flexible than SSJS, if you want to
write scripted code you have to learn Java - at least until other vendors support simpler
languages such as JavaScript. Meanwhile, SSJS still provides the simple yet powerful JavaScript
language, which has a shorter learning curve than Java and in some ways is more flexible, since
it's loosely typed.

As far as NAS is concerned, it's clear that JSP can never replace the robust functionality that
NAS provides, nor was it intended to. Instead, JSP is a front-end, presentation layer technology
that would fit well with the NAS architecture. NAS currently uses a proprietary markup language
for constructing presentation templates. This markup language is somewhat inflexible and doesn't
allow for in-page scripting, so it's definitely less flexible than JSP. In NAS 4.0, Netscape will
introduce JSP as an alternative to the previous markup language that works with the underlying
NAS servlet model, which will also be introduced in NAS 4.0. Indeed, JSP is good news for NAS
developers.

JSP AND XML

JSP and XML have an interesting relationship. On the one hand, you can mix XML and JSP, just
as you can mix HTML and JSP, such that you can use JSP to dynamically generate XML pages.
In other words, you can script XML documents with JSP. This isn't a special ability that only JSP
provides through some kind of special classes; theoretically, you can use any scripting
environment, including CGI, SSJS and ASP, to dynamically generate XML in the same way you
generate HTML. However, the JSP specification explicitly states that generating XML documents
is supported by JSP, and it's gone so far as to make sure that the way the dynamic content is
generated doesn't violate any XML rules.

On the other hand, JSP pages themselves can be expressed as XML documents. The JSP
specification defines XML-compliant tags as alternatives to some of the JSP tags that are not
XML-compliant. For example, scriptlets (between <%...%>) can equivalently be written between
the XML-compliant tags <jsp:scriptlet> and </jsp:scriptlet>. Clearly, the first form is
easier to write than the XML form when you're writing JSP code by hand. However, the XML
format makes it easier to generate and validate JSP pages within IDEs or other development
tools designed to build JSP pages. See the JSP specification for more details on the relationship
between JSP and XML.

FINAL THOUGHTS

JSP is sure to receive a great deal of much-deserved attention from all kinds of web developers,
due to its supporting not only less sophisticated programmers through the use of simple tags, but
also advanced scripters and Java developers. In fact, a few vendors other than Netscape already
provide JSP implementations in one form or another. Although the final JSP 1.0 specification has
not yet been released by Sun (as of this writing, the published 1.0 spec is only a draft), IBM, BEA
WebLogic, and Live Systems have implemented JSP in their application servers. And because
JSP is an open standard that allows other languages, such as JavaScript, to be used instead of
Java, JSP may gain even broader support in the industry. As mentioned at the beginning of this
article, Netscape has also announced that it will support JSP and Java servlets in its 4.0 version
of NAS.

I'm very excited that Netscape is supporting JSP. Its inherent flexibility, its support for component-
centric programming, and its cross-platform nature make it a perfect complement to Netscape's
line of cross-platform servers. Because NAS is itself a component-centric application server that
already supports Java, JSP seems to be a perfect match as the presentation layer technology in
future versions of NAS. If you're an NAS programmer today or will be in the near future, I'd highly
recommend that you download the JSP reference implementation published by Sun and start
learning about it now. This implementation is not for production use, but you can use it to
familiarize yourself with JSP by building and running sample applications. It also comes with a
number of small sample applications that, along with this article, will help you on your way to
developing JSP applications.




                                   JSP Tutorial

Your first JSP
JSP simply puts Java inside HTML pages.You can take any existing HTML page and
change its extension to ".jsp" instead of ".html". In fact, this is the perfect exercise for
your first JSP.

Take the HTML file you used in the previous exercise. Change its extension from
".html" to ".jsp". Now load the new file, with the ".jsp" extension, in your browser.

You will see the same output, but it will take longer! But only the first time. If you
reload it again, it will load normally.
What is happening behind the scenes is that your JSP is being turned into a Java file,
compiled and loaded. This compilation only happens once, so after the first load, the file
doesn't take long to load anymore. (But everytime you change the JSP file, it will be re-
compiled again.)

Of course, it is not very useful to just write HTML pages with a .jsp extension! We now
proceed to see what makes JSP so useful.

Adding dynamic content via expressions
As we saw in the previous section, any HTML file can be turned into a JSP file by
changing its extension to .jsp. Of course, what makes JSP useful is the ability to embed
Java. Put the following text in a file with .jsp extension (let us call it hello.jsp), place
it in your JSP directory, and view it in a browser.
<HTML>
<BODY>
Hello! The time is now <%= new java.util.Date() %>
</BODY>
</HTML>
Notice that each time you reload the page in the browser, it comes up with the current
time.

The character sequences <%= and %> enclose Java expressions, which are evaluated at run
time.

This is what makes it possible to use JSP to generate dyamic HTML pages that change in
response to user actions or vary from user to user.

Exercise: Write a JSP to output the values returned by System.getProperty for various
system properties such as java.version, java.home, os.name, user.name,
user.home, user.dir etc.



Scriptlets
We have already seen how to embed Java expressions in JSP pages by putting them
between the <%= and %> character sequences.

But it is difficult to do much programming just by putting Java expressions inside
HTML.

JSP also allows you to write blocks of Java code inside the JSP. You do this by placing
your Java code between <% and %> characters (just like expressions, but without the = sign
at the start of the sequence.)
This block of code is known as a "scriptlet". By itself, a scriptlet doesn't contribute any
HTML (though it can, as we will see down below.) A scriptlet contains Java code that is
executed every time the JSP is invoked.

Here is a modified version of our JSP from previous section, adding in a scriptlet.

<HTML>
<BODY>
<%
    // This is a scriptlet. Notice that the "date"
    // variable we declare here is available in the
    // embedded expression later on.
    System.out.println( "Evaluating date now" );
    java.util.Date date = new java.util.Date();
%>
Hello! The time is now <%= date %>
</BODY>
</HTML>
If you run the above example, you will notice the output from the
"System.out.println" on the server log. This is a convenient way to do simple
debugging (some servers also have techniques of debugging the JSP in the IDE. See your
server's documentation to see if it offers such a technique.)

By itself a scriptlet does not generate HTML. If a scriptlet wants to generate HTML, it
can use a variable called "out". This variable does not need to be declared. It is already
predefined for scriptlets, along with some other variables. The following example shows
how the scriptlet can generate HTML output.

<HTML>
<BODY>
<%
    // This scriptlet declares and initializes "date"
    System.out.println( "Evaluating date now" );
    java.util.Date date = new java.util.Date();
%>
Hello! The time is now
<%
    // This scriptlet generates HTML output
    out.println( String.valueOf( date ));
%>
</BODY>
</HTML>
Here, instead of using an expression, we are generating the HTML directly by printing to
the "out" variable. The "out" variable is of type javax.servlet.jsp.JspWriter.

Another very useful pre-defined variable is "request". It is of type
javax.servlet.http.HttpServletRequest

A "request" in server-side processing refers to the transaction between a browser and the
server. When someone clicks or enters a URL, the browser sends a "request" to the
server for that URL, and shows the data returned. As a part of this "request", various data
is available, including the file the browser wants from the server, and if the request is
coming from pressing a SUBMIT button, the information the user has entered in the form
fields.

The JSP "request" variable is used to obtain information from the request as sent by the
browser. For instance, you can find out the name of the client's host (if available,
otherwise the IP address will be returned.) Let us modify the code as shown:

<HTML>
<BODY>
<%
    // This scriptlet declares and initializes "date"
    System.out.println( "Evaluating date now" );
    java.util.Date date = new java.util.Date();
%>
Hello! The time is now
<%
    out.println( date );
    out.println( "<BR>Your machine's address is " );
    out.println( request.getRemoteHost());
%>
</BODY>
</HTML>
A similar variable is "response". This can be used to affect the response being sent to the
browser. For instance, you can call response.sendRedirect( anotherUrl ); to send
a response to the browser that it should load a different URL. This response will actualy
go all the way to the browser. The browser will then send a different request, to
"anotherUrl". This is a little different from some other JSP mechanisms we will come
across, for including another page or forwarding the browser to another page.

Exercise: Write a JSP to output the entire line, "Hello! The time is now ..." but use a
scriptlet for the complete string, including the HTML tags.

Mixing Scriptlets and HTML
We have already seen how to use the "out" variable to generate HTML output from
within a scriptlet. For more complicated HTML, using the out variable all the time loses
some of the advantages of JSP programming. It is simpler to mix scriptlets and HTML.

Suppose you have to generate a table in HTML. This is a common operation, and you
may want to generate a table from a SQL table, or from the lines of a file. But to keep
our example simple, we will generate a table containing the numbers from 1 to N. Not
very useful, but it will show you the technique.

Here is the JSP fragment to do it:

<TABLE BORDER=2>
<%
    for ( int i = 0; i < n; i++ ) {
           %>
           <TR>
           <TD>Number</TD>
           <TD><%= i+1 %></TD>
           </TR>
           <%
    }
%>
</TABLE>
You would have to supply an int variable "n" before it will work, and then it will output
a simple table with "n" rows.

The important things to notice are how the %> and <% characters appear in the middle of
the "for" loop, to let you drop back into HTML and then to come back to the scriptlet.

The concepts are simple here -- as you can see, you can drop out of the scriptlets, write
normal HTML, and get back into the scriptlet. Any control expressions such as a "while"
or a "for" loop or an "if" expression will control the HTML also. If the HTML is inside a
loop, it will be emitted once for each iteration of the loop.

Another example of mixing scriptlets and HTML is shown below -- here it is assumed
that there is a boolean variable named "hello" available. If you set it to true, you will
see one output, if you set it to false, you will see another output.

<%
     if ( hello ) {
         %>
         <P>Hello, world
         <%
     } else {
         %>
         <P>Goodbye, world
         <%
     }
%>
It is a little difficult to keep track of all open braces and scriptlet start and ends, but with a
little practice and some good formatting discipline, you will acquire competence in doing
it.
Exercise: Make the above examples work. Write a JSP to output all the values returned
by System.getProperties with "<BR>" embedded after each property name and value.
Do not output the "<BR>" using the "out" variable.


JSP Directives
We have been fully qualifying the java.util.Date in the examples in the previous
sections. Perhaps you wondered why we don't just import java.util.*;
It is possible to use "import" statements in JSPs, but the syntax is a little different from
normal Java. Try the following example:

<%@ page import="java.util.*" %>
<HTML>
<BODY>
<%
    System.out.println( "Evaluating date now" );
    Date date = new Date();
%>
Hello! The time is now <%= date %>
</BODY>
</HTML>
The first line in the above example is called a "directive". A JSP "directive" starts with
<%@ characters.

This one is a "page directive". The page directive can contain the list of all imported
packages. To import more than one item, separate the package names by commas, e.g.

<%@ page import="java.util.*,java.text.*" %>
There are a number of JSP directives, besides the page directive. Besides the page
directives, the other most useful directives are include and taglib. We will be covering
taglib separately.

The include directive is used to physically include the contents of another file. The
included file can be HTML or JSP or anything else -- the result is as if the original JSP
file actually contained the included text. To see this directive in action, create a new JSP

<HTML>
<BODY>
Going to include hello.jsp...<BR>
<%@ include file="hello.jsp" %>
</BODY>
</HTML>
View this JSP in your browser, and you will see your original hello.jsp get included in
the new JSP.

Exercise: Modify all your earlier exercises to import the java.util packages.


JSP Declarations
The JSP you write turns into a class definition. All the scriptlets you write are placed
inside a single method of this class.

You can also add variable and method declarations to this class. You can then use these
variables and methods from your scriptlets and expressions.
To add a declaration, you must use the <%! and %> sequences to enclose your
declarations, as shown below.

<%@ page import="java.util.*" %>
<HTML>
<BODY>
<%!
    Date theDate = new Date();
    Date getDate()
    {
        System.out.println( "In getDate() method" );
        return theDate;
    }
%>
Hello! The time is now <%= getDate() %>
</BODY>
</HTML>
The example has been created a little contrived, to show variable and method
declarations.

Here we are declaring a Date variable theDate, and the method getDate. Both of these
are available now in our scriptlets and expressions.

But this example no longer works! The date will be the same, no matter how often you
reload the page. This is because these are declarations, and will only be evaluated once
when the page is loaded! (Just as if you were creating a class and had variable
initialization declared in it.)

Exercise: Modify the above example to add another function computeDate which re-
initializes theDate. Add a scriptlet that calls computeDate each time.

Note: Now that you know how to do this -- it is in general not a good idea to use
variables as shown here. The JSP usually will run as multiple threads of one single
instance. Different threads would interfere with variable access, because it will be the
same variable for all of them. If you do have to use variables in JSP, you should use
synchronized access, but that hurts the performance. In general, any data you need should
go either in the session objet or the request objectc (these are introduced a little later) if
passing data between different JSP pages. Variables you declare inside scriptlets are fine,
e.g. <% int i = 45; %> because these are declared inside the local scope and are not
shared.


JSP Tags
Another important syntax element of JSP are tags. JSP tags do not use <%, but just the <
character. A JSP tag is somewhat like an HTML tag. JSP tags can have a "start tag", a
"tag body" and an "end tag". The start and end tag both use the tag name, enclosed in <
and > characters. The end starts with a / character after the < character. The tag names
have an embedded colon character : in them, the part before the colon describes the type
of the tag. For instance:
<some:tag>
body
</some:tag>
If the tag does not require a body, the start and end can be conveniently merged together,
as
<some:tag/>
Here by closing the start tag with a /> instead of > character, we are ending the tag
immediately, and without a body. (This syntax convention is the the same as XML.)

Tags can be of two types: loaded from an external tag library, or predefined tags.
Predefined tags start with jsp: characters. For instance, jsp:include is a predefined
tag that is used to include other pages.

We have already seen the include directive. jsp:include is similar. But instead of
loading the text of the included file in the original file, it actually calls the included target
at run-time(the way a browser would call the included target. In practice, this is actually
a simulated request rather than a full round-trip between the browser and the server).
Following is an example of jsp:include usage

<HTML>
<BODY>
Going to include hello.jsp...<BR>
<jsp:include page="hello.jsp"/>
</BODY>
</HTML>
Try it and see what you get. Now change the "jsp:include" to "jsp:forward" and see
what is the difference. These two predefined tags are frequently very useful.

Exercise: Write a JSP to do either a forward or an include, depending upon a boolean
variable (hint: The concepts of mixing HTML and scriptlets work with JSP tags also!)


JSP Sessions
On a typical web site, a visitor might visit several pages and perform several interactions.

If you are programming the site, it is very helpful to be able to associate some data with
each visitor. For this purpose, "session"s can be used in JSP.

A session is an object associated with a visitor. Data can be put in the session and
retrieved from it, much like a Hashtable. A different set of data is kept for each visitor to
the site.

Here is a set of pages that put a user's name in the session, and display it elsewhere. Try
out installing and using these.
First we have a form, let us call it GetName.html

<HTML>
<BODY>
<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
The target of the form is "SaveName.jsp", which saves the user's name in the session.
Note the variable "session". This is another variable that is normally made available in
JSPs, just like out and request variables. (In the @page directive, you can indicate that
you do not need sessions, in which case the "session" variable will not be made
available.)
<%
     String name = request.getParameter( "username" );
     session.setAttribute( "theName", name );
%>
<HTML>
<BODY>
<A HREF="NextPage.jsp">Continue</A>
</BODY>
</HTML>
The SaveName.jsp saves the user's name in the session, and puts a link to another page,
NextPage.jsp.

NextPage.jsp shows how to retrieve the saved name.

<HTML>
<BODY>
Hello, <%= session.getAttribute( "theName" ) %>
</BODY>
</HTML>
If you bring up two different browsers (not different windows of the same browser), or
run two browsers from two different machines, you can put one name in one browser and
another name in another browser, and both names will be kept track of.

The session is kept around until a timeout period. Then it is assumed the user is no
longer visiting the site, and the session is discarded.

Exercise: Add another attribute "age" to the above example.


Beans and Form processing
Forms are a very common method of interactions in web sites. JSP makes forms
processing specially easy.
The standard way of handling forms in JSP is to define a "bean". This is not a full Java
bean. You just need to define a class that has a field corresponding to each field in the
form. The class fields must have "setters" that match the names of the form fields. For
instance, let us modify our GetName.html to also collect email address and age.

The new version of GetName.html is

<HTML>
<BODY>
<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR>
What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
To collect this data, we define a Java class with fields "username", "email" and "age"
and we provide setter methods "setUsername", "setEmail" and "setAge", as shown. A
"setter" method is just a method that starts with "set" followed by the name of the field.
The first character of the field name is upper-cased. So if the field is "email", its
"setter" method will be "setEmail". Getter methods are defined similarly, with "get"
instead of "set". Note that the setters (and getters) must be public.
public class UserData {
    String username;
    String email;
    int age;

     public void setUsername( String value )
     {
         username = value;
     }

     public void setEmail( String value )
     {
         email = value;
     }

     public void setAge( int value )
     {
         age = value;
     }

     public String getUsername() { return username; }

     public String getEmail() { return email; }

     public int getAge() { return age; }
}
The method names must be exactly as shown. Once you have defined the class, compile
it and make sure it is available in the web-server's classpath. The server may also define
special folders where you can place bean classes, e.g. with Blazix you can place them in
the "classes" folder. If you have to change the classpath, the web-server would need to
be stopped and restarted if it is already running. (If you are not familiar with
setting/changing classpath, see notes on changing classpath.)

Now let us change "SaveName.jsp" to use a bean to collect the data.

<jsp:useBean id="user" class="UserData" scope="session"/>
<jsp:setProperty name="user" property="*"/>
<HTML>
<BODY>
<A HREF="NextPage.jsp">Continue</A>
</BODY>
</HTML>
All we need to do now is to add the jsp:useBean tag and the jsp:setProperty tag!
The useBean tag will look for an instance of the "UserData" in the session. If the
instance is already there, it will update the old instance. Otherwise, it will create a new
instance of UserData (the instance of the UserData is called a bean), and put it in the
session.

The setProperty tag will automatically collect the input data, match names against the
bean method names, and place the data in the bean!

Let us modify NextPage.jsp to retrieve the data from bean..

<jsp:useBean id="user" class="UserData" scope="session"/>
<HTML>
<BODY>
You entered<BR>
Name: <%= user.getUsername() %><BR>
Email: <%= user.getEmail() %><BR>
Age: <%= user.getAge() %><BR>
</BODY>
</HTML>
Notice that the same useBean tag is repeated. The bean is available as the variable
named "user" of class "UserData". The data entered by the user is all collected in the
bean.

We do not actually need the "SaveName.jsp", the target of GetName.html could have
been NextPage.jsp, and the data would still be available the same way as long as we
added a jsp:setProperty tag. But in the next tutorial, we will actually use
SaveName.jsp as an error handler that automatically forwards the request to
NextPage.jsp, or asks the user to correct the erroneous data.

Exercise: 1) Write a JSP/HTML set that allows a user to enter the name of a system
property, and then displays the value returned by System.getProperty for that property
name (handle errors appripriately.) 2) Go back to the exercises where you manually
modified boolean variables. Instead of a boolean variable, make these come from a
HIDDEN form field that can be set to true or false.
Tag libraries
JSP 1.1 introduces a method of extending JSP tags, called "tag libraries". These libraries
allow addition of tags similar to jsp:include or jsp:forward, but with different
prefixes other than jsp: and with additional features.

To introduce you to tag libraries, in this tutorial we use the Blazix tag library as an
example. This tag library comes bundled with the Blazix server, which you can
download free for learning and evaluation. (The material you learn about using tag
libraries will work with any other tag libraries also.)

Each tag-library will have its own tag-library specific documentation. In order to use the
tag library, you use the "taglib" directive to specify where your tag library's "description"
resides. For the Blazix tag library, the (recommended) directive is as follows

<%@ taglib prefix="blx" uri="/blx.tld" %>
The "uri" specifies where to find the tag library description. The "prefix" is unique for
the tag library. This directive is saying that we will be using the tags in this library by
starting them with blx:

The Blazix tag library provides a blx:getProperty tag. This tag can be used to allow the
user to edit form data. In our GetName.jsp file, we will now add a jsp:useBean and place
the form inside blx:getProperty.

The new GetName.jsp is

<%@ taglib prefix="blx" uri="/blx.tld" %>
<jsp:useBean id="user" class="UserData" scope="session"/>
<HTML>
<BODY>
<blx:getProperty name="user" property="*">
<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR>
What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>
<P><INPUT TYPE=SUBMIT>
</FORM>
</blx:getProperty>
</BODY>
</HTML>
Note that the blx:getProperty doesn't end with /> but is instead terminated by a separate
</blx:getProperty> line. This puts all the form input fields inside the blx:getProperty so
they can be appropriately modified by the tag library.

Try putting a link to GetName.jsp from the NextPage.jsp, and you will see that the bean's
data shows up automatically in the input fields.

The user can now edit the data.
We still have a couple of problems. The user cannot clear out the name field. Moreover,
if the user enters a bad item in the "age" field, something which is not a valid integer, a
Java exception occurs.

We will use another tag from the Blazix tag library to take care of this. Blazix offers a
blx:setProperty tag that can be used to take care of these problems. blx:setProperty
allows us to define an exception handler method. If an exception occurs, we can collect
an error message for the user and continue processing.

Following is a version of SaveName.jsp that processes any errors, and either shows the
user GetName.jsp again to user can enter the data correctly, or automatically forwards to
NextPage.jsp.

<%@ taglib prefix="blx" uri="/blx.tld" %>
<%!
    boolean haveError;
    StringBuffer errors;

     public void errorHandler( String field,
                                String value,
                                Exception ex )
     {
         haveError = true;
         if ( errors == null )
              errors = new StringBuffer();
         else
              errors.append( "<P>" );
         errors.append( "<P>Value for field \"" +
                       field + "\" is invalid." );
         if ( ex instanceof java.lang.NumberFormatException )
              errors.append( " The value must be a number." );
     }
%>
<%
     // Variables must be initialized outside declaration!
     haveError = false;
     errors = null;
%>
<HTML>
<BODY>
<jsp:useBean id="user" class="UserData" scope="session"/>
<blx:setProperty name="user"
     property="*"
     onError="errorHandler"/>
<%
    if ( haveError ) {
        out.println( errors.toString());
        pageContext.include( "GetName.jsp" );
    } else
        pageContext.forward( "NextPage.jsp" );
%>
</BODY>
</HTML>
Note that haveError and errors must be re-initialized each time, therefore they are
being initialized outside of the declaration.

[Also notice the use of pageContext.include and pageContext.forward. These are
like jsp:include and jsp:forward, but are more convenient to use from within Java
blocks. pageContext is another pre-defined variable that makes it easy to do certain
operations from within Java blocks.]

Here, if an error occurs during the processing of blx:setProperty, we display the error
and then include the GetName.jsp again so user can correct the error. If no errors occur,
we automatically forward the user to NextPage.jsp.

There is still a problem with the forms, the "age" shows up as zero initially rather than
being empty. This can be fixed by adding "emptyInt=0" to both the blx:getProperty
and blx:setProperty tags (bean fields should be initialized to 0.) It happens that "0" is
not a valid value for age, so we can use "0" to mark empty strings. If "0" were a valid
value for age, we could have added "emptyInt=-1" (and made sure to initialize the bean
fields to -1.)

Another small problem is that the "<HTML>" tag gets doubled if there is an error and we
end up including "GetName.jsp". A more elegant solution is to remove the out.println,
and pass back the error as shown

<%
     if ( haveError ) {
         request.setAttribute( "errors",
                  errors.toString());
         pageContext.forward( "GetName.jsp" );
     } else
         pageContext.forward( "NextPage.jsp" );
%>
We can then do a "request.getAttribute" in the GetName.jsp, and if the returned
value is non-null, display the error. This is left as an exercise.

Exercise: Read the documentation on Blazix or another tag library, and use some tags
from this library.


Techniques for form editing
A tag library such as the one that comes with the Blazix server, may not be available in
your environment. How can you allow similar features without using a tag library?

It is a little tedious, but it can be done. Basically, you must edit each HTML tag yourself,
and put in a default value. The following examples shows how we modify GetName.jsp
to provide features similar to blx:getProperty but with manual HTML tag editing:
<jsp:useBean id="user" class="UserData" scope="session"/>
<HTML>
<BODY>
<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username
         SIZE=20 VALUE="<%= user.getUsername() %>"><BR>
What's your e-mail address? <INPUT TYPE=TEXT
         NAME=email SIZE=20
         VALUE="<%= user.getEmail() %>"><BR>
What's your age? <INPUT TYPE=TEXT NAME=age
         SIZE=4 VALUE=<%= user.getAge() %>>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
As you can see, this simply involves adding a "VALUE" field in the INPUT tags, and
initializing the field with an expression!

To handle exceptions during input processing, a simple approach is to use "String"
fields in the bean, and do the conversion to the target datatype yourself. This will allow
you to handle exceptions.

Exercise: Modify the earlier example to do everything without the Blazix tag library
(you can restrict this to only one field.)


Protecting your website with a login page
Some sites require that all users log-in using a username and password, before being able
to visit any page.

This can be done using JSP sessions or servlets, and in fact this was a common technique
for a while. But starting with a new release of Servlets specifications (2.2) from Sun, this
feature is now very simple to implement.

It is no longer necessary to use JSP techniques to provide login/password protection, but
it is still a very common requirement of web-sites, therefore a brief overview is provided
here.

To password-protect your site, you just need to design a login page. This page can be as
simple or complicated as you need it to be. It must contain a <FORM> tag, with the
METHOD set to POST and the ACTION set to "j_security_check".

<FORM METHOD=POST ACTION=j_security_check>

The target j_security_check is provided by the application server, and does not need to
be coded.
The form must contain two <INPUT> fields, named j_username and j_password
respectively for the username and password. Typically, the username field will be a TEXT
input field, and the password field will be a PASSWORD input field.

After this, you must tell your application server to password protect your pages using the
login page you have provided. The details will vary from server to server, but a good
implementation will provide you hooks that you can use, for example, to match
usernames and passwords against a database. (E.g., in Blazix you can supply an
implementation of the interface desisoft.deploy.AuthCheck to check usernames and
passwords against a database or other sources.)

Exercise: Read your application server's documentation and add login/password
protection to some of your JSPs.

Database access in JSPs
Database access is very common in JSPs. Most database access these days is done using
SQL. Therefore, if you do not know SQL, the first step is to learn SQL. Teaching SQL
is outside the scope of this tutorial, but there are many excellent references available on
the web. (See the further reading page if you need some pointers.)

Once you know how to write SQL queries, all you then need is to be able to execute SQL
query strings from Java programs or JSP pages, and to be able to examine and manipulate
any returned values.

In Java, SQL access is provided via JDBC (the java.sql.* package.) One approach to
database access in JSP is simply to use JDBC, by putting JDBC calls in Java scriptlets.

Because of tag libraries, in JSP it is typically a little easier to use SQL. Therefore it is not
necessary to do the full JDBC setup. In this page, we will see how to use the Blazix tag
library for SQL access. (The sample file is only for Windows computers, users of other
systems would need to create test databases on their systems with advice from someone
familiar with doing this on their system.)

The first step is to download the provided sample database file jspsqlsample.mdb, and
configure an ODBC connection to it named "jspsql". If you do not know how to
configure ODBC connections, visit the setting up ODBC connections page.

Once you have your ODBC connection configured, add the following lines to your web
configuration (web.ini) file:

dataSource.name: myDataSource
dataSource.myDataSource.odbc:            jspsql

This tells the server to use the ODBC connection named "jspsql".
The sample database file contains a table SingleItem which contains a single row of data.
(If you have Microsoft Access available on your machine, you should be able to open and
look at the database file.)

The following query will retrieve a single item from this table.

SELECT Goal FROM SingleItem

Write and try out the following JSP.

<%@ taglib prefix="blx" uri="/blx.tld" %>
<HTML>
<BODY>
<P>
<blx:sqlConnection jndiName="myDataSource">
<P>The goal is <blx:sqlGet query="SELECT Goal FROM SingleItem"/>
</blx:sqlConnection>
</BODY>
</HTML>

Here, the blx:sqlConnection tag is specifying the "myDataSource" datasource, so the
tag library will know that we want to access our jspsqlsample.mdb file. The
blx:sqlGet is retrieving the result of our query.

Often queries will return multiple rows, and will contain multiple items in each row. For
such queries, the tag blx:sqlQuery can be utilized. Try the following JSP.

<%@ taglib prefix="blx" uri="/blx.tld" %>
<HTML>
<BODY>
<P>
<blx:sqlConnection jndiName="myDataSource">

<blx:sqlQuery id="sampleQuery">
SELECT DayNumber,TaskLearned FROM Jsptut
</blx:sqlQuery>

<TABLE>
<TR><TD>Day Number</TD><TD>Task Learned</TD></TR>
<blx:sqlExecuteQuery resultSet="rs" queryRef="sampleQuery">
<TR>
<TD><%= rs.getInt("DayNumber") %></TD>
<TD><%= rs.getString("TaskLearned") %></TD>
</TR>
</blx:sqlExecuteQuery>
</TABLE>
</blx:sqlConnection>
</BODY>
</HTML>
The blx:sqlQuery tag is being used here to write out the query itself. Then the
blx:sqlExecuteQuery is being used to retrieve the rows of the query. Everything
between <blx:sqlExecuteQuery> and </blx:sqlExecuteQuery> will be repeatedly
executed, once for each row of the query. Therefore there will be many rows in the table,
once for each row in the database. Within the body of the blx:sqlExecuteQuery, we
have access to the Java variable "rs", which is of type java.sql.resulSet. We can
retrieve the items from the row using either the column number or the name. We could
also have used the following to retrieve the items:

<TD><%= rs.getInt(1) %></TD>
<TD><%= rs.getString(2) %></TD>

To execute queries that do not return any values (such as INSERT, DELETE and
UPDATE statements,) use the blx:executeUpdate tag.

Exercise: 1) Write a page to execute and display the result of the following query thar
returns a single item:

SELECT DayNumber FROM Jsptut WHERE TaskLearned='Scriptlets'

2) The Jsptut table has a third column named Url. Modify the table sample above to
display this column as well. Make the URLs come out as hyperlinks.
3) Write a set of JSP pages that lets a user update the day number for any given task, and
then displays the updated table. (Hint: You will need a WHERE clause to compare the
task name, like in exercise 1 above. You will also need the form processing skills you
learned in earlier lessons.)
4) Modify your JSP pages so users can add rows to the Jsptut table.
5) Add a facility to delete rows also.


Sending e-mail from JSP
To be able to send e-mail, you need access to an "SMTP server". SMTP stands for
"Simple Mail Transfer Protocol". Most of the email on the internet is sent using SMTP
servers.

If your email address is "you@yourhost.com", then there is a good chance your SMTP
server is either "yourhost.com" or something like "mail.yourhost.com" or
"smtp.yourhost.com". You need to find out exactly what it is. Your email program
should have a "Settings" page which shows you the name of your SMTP server (perhaps
shown as "mail server" or "outgoing mail server".)

(If you have web-based email, you probably won't be able to send email out directly.)
Once you have the SMTP server information, you are ready to send email out from your
JSP pages. Following is a small sample that uses the Blazix Tag library to send an email
with an attachment.

First of all, let us write an HTML page to start things off.

<HTML>
<BODY>
<FORM METHOD=POST ACTION="SendMail.jsp">
Please enter name: <INPUT TYPE=TEXT NAME=username SIZE=20><BR>
Please enter email address: <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>

Now let us write the target JSP, SendMail.jsp. Replace "yoursmtphost.com" by your
SMTP server, and "you@youremail.com" by your email address. Before testing it, also
create a file "C:\contents.txt" which will be sent as an attachment.

<%@ taglib prefix="blx" uri="/blx.tld" %>
<HTML>
<BODY>
<%
   // Get username.
   String email = request.getParameter( "email" );
%>
<% if ( email == null || email.equals( "" )) { %>
Please enter an email address.
<% } else { %>
<blx:email host="yoursmtphost.com" from="you@youremail.com">
<blx:emailTo><%= email %></blx:emailTo>
Thank you for registering with us. You registered the
following name: <%= request.getParameter( "username" ) %>

Your registration was received at <%= new java.util.Date() %>

Attached, please find a contents file.
<blx:emailAttach file="C:\\contents.txt"
      contentType="text/plain" name="contents.txt/>
</blx:email>
<!-- Also write out some HTML -->
Thank you. A confirmation email has been sent to <%= email %>
<% } %>
</BODY>
</HTML>

Exercise: 1) Send an HTML file as an attachment, changing the contentType to
"text/html" instead of "text/plain".
2) Send the HTML file as an attachment, without using any other text. In the "blx:email"
tag, also set "noText=true".

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:94
posted:11/2/2011
language:English
pages:31