:: Basics of
JavaScripts ::
Choosing a server-side
language used to be easy. Way back when, CGI was pretty much the only
scripting option out there. Intrepid developers could write their own server
extensions, but few were up to the challenge, and the gap between these two
options (inefficient CGI scripts and extremely complex server extension
development) was huge.
Microsoft tried to fill
this hole with Active Server Pages (ASP), which allow developers to use
simple scripting to access the server and its extensions. But while ASP
gives you an efficient way to return dynamic content, it essentially limits
you to Microsoft platforms, and even the simplest of scripting mistakes can
cause the server to crash or hang, effectively bringing down your website.
Apparently in response
to ASP, Sun Microsystems gave the world JavaServer Pages (JSP) technology,
which is based entirely upon Sun's popular Java programming language and
gives developers the advantages of developing in Java in a more relaxed,
script-like environment. Behind the scenes, JSP pages are dynamically
assembled into Servlets, which are simply Java classes. This means JSP
supports the same modularity, reusability, platform-independence, and access
to Java APIs that Java programming supports.
Thanks to its
foundation in Java and its use of Java threads to handle incoming requests,
JSP is a great deal more efficient than many other scripting languages, such
as CGI. Its threading model and error handling also help prevent server
hangs and crashes. And when the underlying Java Virtual Machine (JVM) makes
use of Just In Time (JIT) compilation, the performance of well-written JSP
can approach that of C++.
JSP also bests ASP by
supporting the definition of tags that abstract functionality within a page,
so tags can be defined in a tag library and then used within any JSP page.
This makes for a better separation of page content from its code, which is
one of Web development's prime directives. The less code scattered
throughout the pages of a website, the easier the site is to maintain.
Global changes need only be made to the tags defined in a central library,
making time-consuming, page-by-page fixes things of the past.
For those XML lovers
among us, good news: JSP pages can be written in well-formed, valid XML by
using XSLT. (For those of you who aren't XML-spawn, this simply means that
JSP can make full use of a very powerful and widely accepted data format and
all the tools and support that go with it.)
And unlike ASP, JSP is
a lot less platform-specific and it doesn't rely as heavily on the company
that created it for support or performance improvements. That said, there
are some similarities between JSP and ASP. Here, let's closer look at how
the two compare.
JSP versus ASP
JSP and ASP do have
some basic concepts in common. They both make use of simple sever-side
scripting to provide access to Web server information and functionality.
They both do so using object oriented scripting. And they both started out
with similar styles of delimiting this scripting from a page's content. In
fact, Microsoft is replacing ASP with ASP+ (or the .NET architecture), which
is even more like JSP than ASP in that its pages are compiled upon request
and run in a "virtual machine" (which supports multiple languages and is
written in C#).
Yet while ASP primarily
supports two scripting languages -- JScript and VBScript -- JSP actually
supports real Java code, not a new scripting language. The difference is
that the Java code inside a JSP page is more script-like because it doesn't
require Java class and package definitions. As you will see, the Java code
inside JSP is added to methods of a Java Servlet that are generated the
first time the JSP is requested. Of course, JScript, VBScript, and Java are
all object oriented to some degree, or maybe to avoid getting into a
political argument with those of you would dispute this claim I should refer
to them as "Quasi-Object-Oriented." Whatever we choose to call them, we can
at least agree that the scripting languages used by JSP and ASP are all
provided with a set of pre-established objects by the Web server that they
use to generate a dynamic Web page.
The following table
lists some of the pre-established (instantiated, for the purist) objects
that are available in both ASP and JSP.
ASP |
JSP |
Definition |
Request |
request |
Access to request
information. This includes such items as input/form parameters, HTTP
request header information, etc. |
Response |
response |
Access to response
information and construction. This includes output MIME type and other
HTTP response headers as well as the output stream itself. |
Session |
session |
Access to session
information. |
Application |
application |
Access to
application information. |
Response.Write |
out |
Access to the
response output stream. JSP provides a convenience object for direct
output to this stream, whereas ASP uses a Response object method. |
Note that JSP is Java,
so it is case sensitive. But capitalization doesn't matter in VBScript, so
if you stick to lowercase, there really isn't any difference in the names.
These are the main
objects we have to work with when creating dynamic content in either ASP or
JSP, so it's a good idea to become familiar with their methods. I'll use
some of them in the examples that follow, but I can't go into every method
available within the limits of this article.
As I mentioned earlier,
both ASP and JSP support a similar way of delimiting scripting from content
on a page. <% and %> are used to set of sections of script, '<%=' and '%>'
are used to return a value within content, and <%@ and %> are used to
delimit page directives. Here is a brief example using both ASP and JSP:
ASP (using
JScript) |
<%@ LANGUAGE = JScript %>
<TITLE>Simple Scripting Tricks</TITLE>
Anyone can count like this:<BR>
<%
for (i = 1; i < 6; i++) {
Response.Write(i + "<BR>");
}
i = 1000000;
%>
It would take a long time, however, to count to <%= i %>.
|
JSP |
<%@ page language="java" %>
<TITLE>Simple Scripting Tricks</TITLE>
Anyone can count like this:<BR>
<%
for (int i = 1; i < 6; i++) {
out.println(i + "<BR>");
}
i = 1000000;
%>
It would take a long time, however, to count to <%= i %>.
|
HTML Output (from
either JSP or ASP) |
<TITLE>Simple Scripting Tricks</TITLE>
Anyone can count like this:<BR>
1<BR>
2<BR>
3<BR>
4<BR>
5<BR>
It would take a long time, however, to count to 1000000.
|
As you can see, there
are some basic similarities between ASP and JSP. In fact, in this simple
example, there's almost no difference. When we look deeper into JSP,
however, fundamental differences will appear.
JSP Syntax
JSP supports two basic
styles of delimiting its scripting elements from page content. The first
looks a great deal like ASP, whereas the second can be used to create JSP
that is fully XML compliant. Here, let's take a look:
Base Style |
XML Style |
Description |
<%@ directive
%> |
<jsp:directive.directive/> |
Directives are used
to specify page information, include other files, and specify tag
libraries being used. |
<%! declarative
code %> |
<jsp:declaration>
declarative code
</jsp:declaration> |
This code is placed
as a declaration in the servlet that is generated. This is the only
place that new methods can be declared. |
<% code fragment
%> |
<jsp:scriptlet>
code fragment
</jsp:scriptlet> |
This code is placed
within a base method of the generated servlet. |
<%= code
expression %> |
<jsp:expression>
code expression
</jsp:expression>
Some versions use
<jsp:expr/> |
This code is placed
within the base method of the generated servlet, where it is appended to
the output stream being returned for the page. |
To utilize the XML
Style delimiters, you have to format your JSP as an XML document. This
requires some additional modification, like using <jsp:root/> as your the
root XML node and making sure your page is well-formed XML. This conversion
and the use of the XML Style are outside the scope of this article, but if
XML is important to you or your project, you should definitely investigate
them further on your own time.
If you're interested in
learning more about XML and JSP, the book Professional Java XML
Programming with Servlets and JSP is an excellent investment -- though
if you're not quite ready to roll out the dough, JavaSoft's PDF about the
matter is free for the downloading.
The most important
things to know as you create your JSP website are the four basic types of
delimeters: directives, declarations, fragments, and expressions. The
following example is a complete JSP page that uses the base style of each
delimiter:
Line |
Complete JSP |
1
2
3
4
5
6
7
8
9
10
11
12
|
<%@ page info="Example"
import="java.io.*,java.util.*" %>
<%! String title = "Example JSP Page" %>
<%@ include file ="header.inc" %>
Anyone can count like this:<BR>
<%
for (int i = 1; i < 6; i++) {
out.println(i + "<BR>");
}
i = 1000000;
%>
It would take a lifetime, however to count to <%= i %>.
<%@ include file ="footer.inc" %>
|
In line 1, the page
directive sets the generated servlet info to "Example" and makes sure that "java.io.*"
and "java.util.*" are imported for use in the servlet. The import is, well,
important, since without these imports there would be no access to
additional Java APIs.
Line 2 declares
title as a class variable. This variable can now be used in any
following code. Most likely, it is used by the code in header.inc,
which is included in place on line 3.
Line 4 is plain page
content. This is sent to the output stream.
Lines 5 through 10
define a code fragment that writes out the numbers 1 to 5, with breaks in
between, to the output stream.
Line 6 is page content
that includes an expression. This content is sent to the output stream with
the expression inserted.
Line 7 includes the
footer.inc file, which presumably has some more content we want to place
at the bottom of this file.
If you followed all
that, then you now have a basic understanding of JSP syntax and are armed
with enough knowledge to do some small amount of damage to your website. One
gotcha that you should know about is that when included files are changed,
the servlet generated by the JSP is not usually regenerated. So if you make
a change to an included file, make sure to tell your server to regenerate
the servlet for the including JSP. Another way to do this is to re-save the
including JSP. This changes the file modification timestamp, which is
supposed to cause the servlet to regenerate.
Now that we've taken a
look at the basic syntax, let's take a look at how we can use the access
objects that JSP provides us to detect the incoming browser and respond
appropriately.
JSP
Browser Detection
JSP provides us with
access objects that we can use to get information from the incoming request
and modify the resulting response. This makes it possible for us to do
things like identify what type of browser is making the request. We can then
set up a different type of request based upon what that browser supports.
The following example
determines whether the incoming browser is Internet Explorer, Netscape, or a
WML client (like a cell phone). Depending on the browser it finds, it
returns an appropriate greeting. Let's take a gander at an example of this
at work. (Note: I'm going to use line numbering here because it makes the
explanation of the example so much easier, but it isn't part of the code --
it's just there for reference.)
Browser
Detection in JSP |
<%@ page
info="Greetings" errorPage="err.jsp" %>
|
This first line simply
adds some arbitrary information to the generated servlet and tells the Web
server to redirect any Java errors encountered on the page to the err.jsp
page. Other things that can be done in this page directive include importing
various Java APIs.
<%!
public final static int IE = 0;
public final static int NETSCAPE = 1;
public final static int WML = 2;
public int getBrowser(HttpServletRequest request) {
String accept = request.getHeader("ACCEPT");
if (null != accept && -1 !=
accept.indexOf("wml")) {
return WML;
}
String agent = request.getHeader("USER-AGENT");
if (null != agent && -1 !=
agent.indexOf("MSIE")) {
return IE;
}
return NETSCAPE;
}
%>
|
This section of code
declares three static values that represent the different browser types we
are detecting. It also defines the getBrowser() method that accepts
the request object and uses it to determine what browser has made the
request. It does so by looking at the ACCEPT HTTP request header to
see if the browser will accept wml. If it doesn't, it then looks at the
USER-AGENT HTTP request header to see if it contains "MSIE." If it does,
then the browser making the request is IE. Otherwise, we assume it's a
Netscape browser.
<%
switch (getBrowser(request)) {
case WML:
response.setContentType("text/vnd.wap.wml");
%>
<?xml version="1.0"?>
<wml>
<card id="index" title="Browser Greeting">
<p align="center">Hello, Wireless Fan!</p>
</card>
</wml>
<%
break;
case IE:
%>
<HTML><BODY><H1>Hello, IE
Fan!</H1></BODY></HTML>
<%
break;
default:
%>
<HTML><BODY><H1>Hello, Netscape
Fan!</H1></BODY></HTML>
<%
}
%>
|
In the last section of
code, we used the declared getBrowser() method in a Java switch
statement to determine what should be returned to the browser. For IE and
Netscape browsers, a simple HTML document is returned. For WML-accepting
browsers, the content type of the response is set to text/vnd.wap.wml and a
WML document is returned.
In these very
meaningful forty-two lines of code, we have a simple page that will serve up
a pleasant greeting to three different browsers. If all has gone well,
creating this code should have whetted your appetite for more. If you're
interested in pushing JSP even further, then read on for a list of
additional resources you can use to expand your JSP horizons.
Digging Deeper
So far, I've touched on
creating JSP as a well-formed XML document. I also mentioned the concept of
creating a tag library for use throughout your website. But as you dive even
further into JSP development, you'll find that there is quite a bit more to
learn:
There are a number of
servers that support JSP on the market. The two I am most familiar with are
JRun and Tomcat. I've also used Enhydra, which is an open source application
server that uses Tomcat's technology internally. Try one and see how you
like it.
If you're looking at
doing a large-scale project in JSP, I strongly recommend that you create
your own tag library because it will make supporting your website a whole
lot simpler. For more information about tag libraries, check out JSPtags.com
or JSP Insider.
Another powerful
feature of JSP that we haven't covered yet is its ability to utilize
JavaBeans with special tags defined in JSP. For more information about this,
peruse Sun's JavaBean overview.
If you're looking to
push your JSP envelope further, the best place to start is at the source,
Sun Microsystems. Their support pages include the JSP specification and
documentation of the supporting Java classes. As you explore, make sure you
get a good idea about the underlying Java Servlet technology, since this is
what all JSP must become behind the scenes.
You'll find that Sun's
site also gives you an extra helping of propaganda. As a rule, you should
never believe anyone's marketing department, but in this case, Sun's
information to be generally accurate. It is true, for instance, that you can
re-use JSP on multiple platforms without much trouble. In my experience, the
difficulty of moving from one JSP platform to another lies with the Java
APIs that are imported by default. On some platforms you must specifically
import java.io.* and on others you don't. It doesn't hurt to import anything
that doesn't come from java.lang.*, so do it. It will make your life easier
in the future.
As you open up JSP and
really see what it can do, you'll soon find that, with practice, anyone (not
just Java developers) can make use of the powerful set of tools that JSP
provides.
|