Sunday, April 26, 2009

JSP Tutorial 6 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 Tutorial 5 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 Tutorial 4 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.

JSP Tutorial 3 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.

JSP Tutorial 2 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

JSP Tutorial 1 Getting Familiar with your JSP server

Getting Familiar with your JSP serverIf you do not have a JSP capable web-server or application server, the first step is to download one. There are many such servers available, most of which can be downloaded for free evaluation and/or development. Some of them are:
Blazix from Desiderata Software (1.5 Megabytes, JSP, Servlets and EJBs) TomCat from Apache (Approx 6 Megabytes) WebLogic from BEA Systems (Approx 40 Megabytes, JSP, Servlets and EJBs) WebSphere from IBM (Approx 100 Megabytes, JSP, Servlets and EJBs)
To take the best advantage of this tutorial, it recommended that all the material should be tried out with a real server.
Once you have a JSP capable web-server or application server, you need to know the following information about it:
Where to place the files
How to access the files from your browser (with an http: prefix, not as file:) You should be able to create a simple file, such as

<HTML>
<BODY>
Hello, world
</BODY>
</HTML>


know where to place this file and how to see it in your browser with an http:// prefix.
Since this step is different for each web-server, you would need to see the web-server documentation to find out how this is done. Once you have completed this step, proceed to the next tutorial