Developing JSP Web Applications
John B Moore
Micro-Phyla Systems
Introduction
Java Server Pages (JSP) encompass a broad and complex web development platform. A typical, "basics only" book on the topic can be from 300 to 500 pages. Some of the sub-components of the platform, for example Custom Tag Libraries, can be covered by another 400 pages. Given this, it is understandable that this paper of 15+ pages needs to focus on a very small subset of what JSP is and can do. Therefore, the intention is to take you from what is covered in all those hundreds of pages and provide some practical guidelines for using this platform for developing web applications.
When developing applications in a new technology, the first challenge is the determination of what aspects of a given platform will be really useful for a given need and what is generally better to avoid, or at the least, minimize. In my web development, there are several basic guiding questions I always ask, in this order:
Interestingly, the shortest question is the most complex to answer, but answering all of these questions could easily consume many more pages than allowed for in this paper. Therefore, I will center my primary focus on the first question with frequent nods to the issues surrounding the other two questions. I have found that maintainability has a tremendous impact on the ability to answer the last two questions which therefore, are often dependent on, or related to, maintenance issues.
The Game Plan
It is not uncommon that having read all of those introduction JSP books, a feeling of being overwhelmed sets in, with all the choices and possibilities. Our game plan then is to sort out those possibilities and zero in on a narrower subset that can make you productive, and a bit less "overwhelmed". This is not to suggest that other options are not of value to learn, but that within the "filter" of maximizing maintainability, they can be more problematic. All of these points will be illustrated with real world examples (often simplified for emphasis and clarity). To do this, the following sub-topics will be covered:
This organization is a bit artificial because most of these components and issues intermingle. It is mostly organized in this fashion to make it a bit easier to insure that each of these points are covered. Each section will have example code to illustrate the ideas.
JBuilder Setup for a JSP Project
JBuilder adds a fair amount of support for JSP development and it gets better with every release. So a good start is to do a quick overview in setting up for developing a JSP application. To a large degree this is covered in the tutorials ("Working with WebApps and War files", "Creating Servlets", "Developing JSPs", "Working with web applications in JBuilder", and "Deploying your web application" to name a few that would support material in this paper ). In past versions of JBuilder, I have often find those tutorials fragmented, missing the critical "gotchas" and missing more practical examples that make a difference. Fortunately in JBuilder6, they have improved considerably over JBuilder5 and earlier versions, but still weak in some isolated areas. For example, I do not find the JSP wizard of any regular value, mostly because in serious websites, the design of the web page is done buy a web designer, not the Java programmer. Next, you don't generally have the JavaBeans that you might need finished, such that you can just plug them in during the wizard process. A more useful wizard would be one that "imports" and HTML file and does some useful "conversions" (i.e. Add the usebean tag..etc.) Also, "use JavaBean" command would be a nice practical touch for this "after the fact" inclusion. That being said, typically, the necessary steps are:

JBuilder will manage the rest, by adding classes and libraries to WEB-INF as you add then to the project. Your servlet classes will be added to the "classes" branch and any .jar's you add are added to the "lib" directory. One last step is to "make" the current project. Click the "make" button and JBuilder will proceed to configure the rest of the project (adding any needed libs you have defined in your project) It will also make the WAR file, set the default directory, and move into the lib directory any jar files that have been configured in the Project Properties. If you examine the WAR file by double clicking it, it should look something like following figure.

Notice in above figure that JBuilder assembled all the pieces and placed them in the correct locations for deployment. As you work on the project, adding and removing files, JBuilder will keep this up to date. (Remember that if your project gets really big, you can turn off "auto WAR" creation, so that the WAR file is only created when you right click on the WAR file and select "Make". In large projects, this can be a real time saver, but generally JBuilder is so fast at this that you will hardly notice it is happening)
Our web application is now ready for serious work. JBuilder will maintain the files and keep everything in the right place. Added Servlets, JavaBeans, and JSPs (via the wizards) will be placed in the correct locations and added (or removed) to the WAR file as you work. You can now focus on the actual business solution at hand.
Maintenance Issues and JSP
One of the first impressions many get when viewing the source code for a JSP page is the mixing of HTML, Java, and special JSP tags. It does not take long to realize that, if done improperly, this is a recipe for "nightmares in maintenance". Aside from the many proprietary schemes that have been developed from various vendors, there are only two basic components and a number of strategies to simplify this mix of languages in one document. The fundamental maintenance goal is to focus on keeping the HTML presentation layer separated from any logic, data access, and other bookkeeping chores. This is done by using:
In addition to Custom Tag libraries and JavaBeans, there are number of architectural patterns that can define the relationship between JSP, JavaBeans, HTML and Servlets. These architectural patterns also provide maintenance benefits and should be seriously investigated. These patterns, such as "Model-View-Controller", "Dispatcher", and "Service to Workers", to name a few, came about to solve problems and provide structure and maintenance features . Using Servlets as a controller or dispatcher factors out considerable amounts of java code that would be needed to authenticate users and route requests based on special conditions or business logic. Another approach is to utilize an existing framework or develop your own framework. Examples of such frameworks are: Cocoon, Resin and Struts, to name a few of the more common framework projects (see links provided at the end of this paper). Even if you feel like rolling your own, it is quite valuable to study these frameworks for ideas.
Why is it that keeping the Java out of the HTML is so important? Following is a brief list of some of the more important reasons:
As we work on the examples in the rest of this paper, I will point out most of these issues.
Useful JSP Components (The Short List)
The criteria for a "useful" JSP component is one that minimizes the exposure of Java to the web designer and maximizes maintainability and re-usability. The ultimate component for this task is the Custom Tag. The downside in developing ONLY with Custom Tags is the learning curve and the back-end investment. (We cover this in more detail under the Custom Tag section). For expediency, and especially for smaller projects, we will also focus on another team of components that provide some of the same benefits, if used properly, and are well documented.
Default JSP Tags
By default, the JSP framework provides a number of default tags. These tags provide direct access to their environment. Again you should consult a standard JSP book for an exhaustive list. I will only cover those that I have found the most useful.
The basic syntax for all the tags to follow come in two "flavors". The first flavor is enclosed only in <% %>. The second flavor, often referred to as the "xml" style, follows the general pattern of <jsp:tagname attribute=value> </jsp:tagname>. In some cases only the first or second flavor is available, but generally both are available. Personally, I tend to lean toward the first flavor, whenever available, because of its simplicity.
There are three types of default tags: expression, scriptlets, and declarations. Of the three, expressions will be the most useful. The expression syntax can be used to embed direct information from the servlet environment. Some Examples:
| <%= request.getParameter("formvalue") %> | Acquiring a value directly from a previously posted form |
| <%= new java.util.Date() %> | Placing today's date in text or at the bottom of the page |
At this point, expressions are limited and can still appear confusing to a non-Java person. The real value of the expression syntax comes into play when combined with JavaBeans. The important information at this point is that we will be able to leverage this single simple JSP construct in "HTML Designer" friendly ways.
Scriptlets
Scriptlets are blocks of Java code embedded in the HTML document, a maintenance red flag! That is not the worst of it. That Java code is exactly what we want to avoid.
Java Beans
JavaBeans are standard java classes that utilize a specific API. Basically that is defined as a class that has a zero-argument constructor, no public instance variables, and persistent variables can only be accessed via getter and setter methods. Combining JavaBeans with expression JSP tags is a quick and powerful combination. We'll explore that in more depth, next.
JavaBeans and JSP
Web JavaBeans, like their counter parts elsewhere in the Java world, are used to contain reusable functionality. These ideas sound simple, but the devil is in the details - as doing this in one way can create more work, another, minimizes work. JavaBeans for the web provide plugable units of logic in which either a method can be called within the JSP page, or from within a custom JSP tag. Properties and values can be accessed with standard JSP tags. We will review those aspects of using JavaBeans that can be leveraged to minimize that work, and point out which aspects might be counter-productive.
UseBean - Making the Bean Accessible
Before you can access any properties or methods from your JavaBean, the bean must first be loaded into your JSP page. The basic syntax is:
|
<jsp:useBean id="beanName" scope="page" class="package.Class" /> |
This can be thought of as equivalent to the Java code:
|
package.Class beanName = new package.Class(); |
Understanding Scope
Properly utilizing scope is critical to various design, memory efficiency, and coding considerations. In general, the bean should be only available where it is needed. The following reviews each scope, with examples of how this would be used. Remember, these are implicit objects created by the JSP container. You do not have to create them, but use accessors to obtain a handle to each of these scope objects.
Page (default)
The bean exists for the life of the page. This is the most restrictive state and the default. If you declare no scope in the useBean tag, then you get the page scope. When in doubt, leave the default setting. The access and instantiation of the bean will be limited to that page. Information is stored in the PageContext and is available using "this" keyword within the service methods. (See http://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/jsp/PageContext.html for details.)
Request
The bean's internal information is stored in the ServletRequest object and the bean will only be available for the current client request. This scope is handy for storing and making available information from page to "included" page, as well as available to other beans that receive the request object. Good uses of this scope are limited, but would include adding information to the request object that would be useful later in the request. An example of this might be a controller servlet that stuffs values into the request, that it then forwards to a JSP page for presentation. Generally, even this use would be better handled by the next scope type, Session. Though it is entirely possible that, in a particular situation, the information is only useful during that single request, this is generally rare. In those cases, the Request scope would be entirely appropriate.
(See http://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/http/HttpServletRequest.html for details.)
Session
The bean is available to all of your JSP pages for the entire session unless, of course, you cause the bean to be destroyed. Information is stored in the HttpSession object. This scope is probably the most useful of all scopes, in that it allows for communication between all the components of the web session. Via this scope, servlets and JSP can pass values and JavaBeans references to JSP pages and other servlets. This scope is very useful in the MVC design pattern of building a website.
(See http://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/http/HttpSession.html for details.)
Application
The bean will remain until the application is reloaded or the server is restarted. Information is available to all pages that share the same ServletContext. This scope is useful for making "application" beans available from all sessions, both servlets and JSP pages. Only information that would be of use application-wide should be set to this scope. An example might be a management JavaBean that tracks request and "hit" rates, measures performance, and global properties like a database connection pool, and servicing issues would be very useful.
( See http://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/ServletContext.html for details.)
Interfacing between the JavaBean and the JSP Document
Once the JavaBean is available there are several techniques by which the JavaBean can interact with the document. They are:
setProperty
This tag allows the developer to set values in the JavaBean. Unfortunately this often assumes that there was some logic in the JSP that generated a value that is needed somewhere else on the page, request, session or application (see Scope previously). This generally would not create a JSP page that is very maintainable. There are several versions that would be helpful in loading important values into a bean and minimizing the appearance of "code" in the document.
|
<jsp:setProperty name="id" property="*"/> |
This simple but powerful tag looks in the bean and calls all methods that match properties in the request object. The "name" is the name of the bean that has the "setters" to be searched. Therefore, in the above example the bean "id" is searched for setter methods that match the "name/value" pairs found in the incoming request object. Any property that lacks a "setter" will be ignored. Keep in mind that a method like "getValue()" will be available as "value" (note the lower case change). To be useful for the HTML designer, there would need to be documentation as to what properties would then be available. Planning and documentation is very important.
| Note: There are several other variations on this tag that I have intentionally omitted, they are of value, since they require increasingly more knowledge by the presentation designer. I would recommend avoiding these two versions in the beginning, because if you do use them, you will have increased your documentation and raised the "training bar" for the presentation designers. This note, in general, applies to many of the other tags discussed. |
getProperty
The other half of setProperty is accessing the property later in the page utilizing "getProperty". There will also be cases where the property is never directly accessed, but instead is needed internal to the bean to service values for other "methods".
Documenting the request properties for the HTML designer and later maintenance is the critical set. Following would be a simple example of the type of documentation:
|
SetPropertyExample.jsp |
| UseBean tag (place tag at beginning of page) |
|
<jsp:useBean id="example" scope="page" class="com.microps.jspbeans.propertyex" /> |
| Load Request Values (place tag after UseBean tag) |
|
<jsp:setProperty name="example" property="*"/> |
| Available Tags (use any of these tags as needed, there after) |
| <jsp:getProperty name="example" property="userID"/> |
| <jsp:getProperty name="example" property="pin"/> |
| <jsp:getProperty name="example" property="state"/> |
| <jsp:getProperty name="example" property="other"/> |
Both the HTML designer and later maintenance can use the above documentation. From the designer's perspective the tags can be simple "cut and paste" from the docs to the HTML where needed. From the maintenance perspective, the tags, their origin, and even their purpose could be added to the documentation. This documentation is provided by the JavaBean "builder" such that the documentation happens BEFORE rather then AFTER. (A novel concept on many projects). A sample page using these tags might look like:
<HTML>
<HEAD>
<jsp:useBean id="customer" scope="session" class="com.microps.jspbeans.customer" />
<jsp:setProperty name="customer" property="*"/>
<TITLE></TITLE>
</HEAD>
<BODY>
<DIV ALIGN="CENTER">
<H1>Customer Info</H1>
<TABLE WIDTH="100%" BORDER="2" CELLPADDING="0" CELLSPACING="0">
<TR>
<TD>Customer ID:<jsp:getProperty name="customer" property="custID"/> </TD>
</TR>
<TR>
<TD>Customer Name:<jsp:getProperty name="customer"
property="lastName"/></TD>
</TR>
<TR>
<TD>Address:<jsp:getProperty name="customer" property="address"/></TD>
</TR>
</TABLE></DIV> </BODY>
</HTML> |
| Reminder: Be careful. If the property is "lastName", the method that supports that property call must be "getLastName". Notice the difference in capitalization of the first letter of the property in the method. You could spend hours wondering why something is not working or throwing errors. |
Combining JavaBeans and Expression JSP Tags.
Though the bulk of the "code" is in the JavaBean, and very specific methods are surfaced as "tags" from the JavaBean for the designer to use in the HTML document, there are tasks that require a bit more "logic". In addition, the previous tag example is still a bit cumbersome. By combining the basic expression tag syntax with JavaBean methods, we have the flexibility of moving beyond "just properties" into calling methods that might do more serious work. For our purposes here, and for lack of a better name, I call these "Method Tags". Again, the documentation is the key to communicating the syntax from the bean developer to the presentation developer. The following is another simplified example of what that documentation might look like:
|
CustomerBean |
| UseBean (Place this tag at beginning of HTML page) |
|
<jsp:useBean id="customer" scope="session" class="com.mps.jspbeans.customer" /> |
| Useful Method Tags (paste these tags wherever these values are needed) |
| <%=customer.getLastName()%> |
| <%=customer.getCustID()%> |
| <%customer.getAddress()%> |
The HTML designer does not have to understand that these method tags are "Java" embedded in their HTML. The method names should be "self documenting" such that the designer needs little additional documentation (more documentation is NEVER a bad thing, though it is often not read). The simple kind of chart provided above should be all that is needed for the HTML designer, and later the maintenance person, to understand and manipulate the page. Taking the previous sample page and using these tags it might look like:
<HTML> <HEAD> <jsp:useBean id="customer" scope="session" class="com.microps.jspbeans.customer" /> <TITLE></TITLE> </HEAD> <BODY> <DIV ALIGN="CENTER"> <H1>Customer Info</H1> <TABLE WIDTH="100%" BORDER="2" CELLPADDING="0" CELLSPACING="0"> <TR> <TD>Customer ID:<%=customer.getCustID()%> </TD> </TR> <TR> <TD>Customer Name:<%=customer.getLastName()%></TD> </TR> <TR> <TD>Address:<%=customer.getAddress()%></TD> </TR> </TABLE></DIV> </BODY> </HTML> |
The JavaBean "com.microps.jspbeans.customer" might look like this:
package com.microps.jspbeans;
public class customer {
private String CustID;
private String LastName;
private String Address;
public customer() {}
public String getCustID() {
return CustID;
}
public String getLastName() {
return LastName;
}
public String getAddress() {
return Address;
}
} |
We have illustrated above, the minimal "get" methods required by the JSP page. In a more complete example, you would have the matching "set" methods that would be used by a control servlet. The values would be set by the servlet via other processes, possibly access to a database or via request parameters.
A more complex example of the use of this technique would be:
<%@ page errorPage="GenPageError.jsp" %> <HTML> <HEAD> <jsp:useBean id="TableId" scope="session" class="com.theomegagroup.cvportal.TableServiceBean" /> <jsp:useBean id="BreadId" scope="session" class="com.theomegagroup.cvportal.tools.BreadCrumbsBean" /> <TITLE>Data Summary -- CrimeView Internet Portal 1.0</TITLE> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> </HEAD> <BODY BGCOLOR="#FFFFFF" TEXT="#000000"> <FORM NAME="PostFrm"> <TABLE WIDTH="600" BORDER="0" CELLSPACING="0" CELLPADDING="0" ALIGN="center"> <TR> <TD><HR></TD></TR> <TR> <TD><%= TableId.getProblemMsg() %></TD></TR> <TR> <TD HEIGHT="1"> <%= BreadId.getCrumbGroup(0,4) %> </TD></TR> <TR> <TD HEIGHT="10"> <IMG SRC="/CVPortal/images/blackbox.gif" WIDTH="600" HEIGHT="10" BORDER="0"></TD></TR></TR> <TR> <TD> <TABLE WIDTH="600" BORDER="0" CELLSPACING="0" CELLPADDING="0"> <TR> <TD COLSPAN="4" HEIGHT="20"> </TD></TR> <TR> <TD COLSPAN="4" HEIGHT="20"> <DIV ALIGN="left"><B> <FONT FACE="Verdana, Arial, Helvetica, sans-serif" SIZE="3" COLOR="#39399C"> <%= TableId.getPageTitle()%> </FONT></B></DIV></TD> </TR> <TR> <TD COLSPAN="4" ALIGN="left" VALIGN="top"> </TD></TR> <TR ALIGN="left" VALIGN="top"> <TD COLSPAN="4"> <DIV ALIGN="CENTER"> <H4 ALIGN="LEFT"> <FONT FACE="Verdana, Arial, Helvetica, sans-serif" SIZE="2">Select the data you want to display by clicking the Row / Column Headers or Cell Data:</FONT></H4> <%= TableId.getXTableAsHTML()%> </DIV> </TD></TR> <TR> <TD ALIGN="left" VALIGN="top" COLSPAN="4"> <TABLE WIDTH="700" BORDER="0" CELLSPACING="0" CELLPADDING="0"> <TR> <TD WIDTH="55%"><B> <FONT FACE="Verdana, Arial, Helvetica, sans-serif" COLOR="#FF0066">Clicking on a cell in the table above will display:</FONT></B></TD> <TD WIDTH="15%"> <INPUT TYPE="RADIO" NAME="DisplayType" VALUE="map" CHECKED="CHECKED"> <FONT FACE="Verdana, Arial, Helvetica, sans-serif" SIZE="2">Map</FONT></TD> <TD WIDTH="15%"> <INPUT TYPE="RADIO" NAME="DisplayType" VALUE="report"> <FONT FACE="Verdana, Arial, Helvetica, sans-serif" SIZE="2">Report</FONT></TD> <TD WIDTH="15%"><INPUT TYPE="RADIO" NAME="DisplayType" VALUE="chart"> <FONT FACE="Verdana, Arial, Helvetica, sans-serif" SIZE="2">Bar Chart</FONT></TD></TR> </TABLE></TD></TR> <TR> <TD ALIGN="left" VALIGN="top" COLSPAN="4"> </TD></TR> <TR> <TD ALIGN="left" VALIGN="top" COLSPAN="4"><HR ALIGN="center" SIZE="1"></TD></TR> <TR> <TD ALIGN="LEFT" VALIGN="TOP" COLSPAN="3" WIDTH="50%"> <%= BreadId.getBackLink(3)%> <IMG BORDER="0" SRC="/CVPortal/images/back.gif" WIDTH="100" HEIGHT="35" ALT="next"></A></TD> <TD ALIGN="RIGHT" VALIGN="top" WIDTH="50%"> </TD></TR> </TABLE></TD></TR> <TR> <TD><HR></TD></TR> </TABLE> </FORM> </BODY> </HTML> |
This combination of the expression JSP Tag and JavaBeans provides a good simulation of an even more powerful component of the JSP framework, custom JSP tags.
Custom JSP Tags
A JSP Tag is specific collection of characters that tells a page compiler to stop and go out and perform some task at this location. A "Custom" Tag takes that basic framework and allows the developer to create new tags that have custom tasks to perform. Developing a custom Tag is a multi-step process. This is why, for small web applications, this may be overkill, with the use of the above described "Method Tags" being a viable alternative.
For a Custom Tag to work there has to be some "description" or road map for the page compiler by which to go and locate the "code" that it must process. There can be parts of that tag that modify the process in some way, and can be changed by the person using that tag. Most people that have ever used HTML have a basic understanding of tags. The HTML tag
| <font style="Ariel" size="2">Some text</font> |
tells the page processor to take the text enclosed and convert that text to Ariel and then change the size to "2". What we need to discover is how this can be done using the Custom JSP Tag API. This API is large and complex. Therefore, we will only introduce you to the very basics, focusing on a "first level" use of custom tags.
Tags have their own library package, javax.servlet.jsp.tagext, that contains an interface called Tag and a helper class called TagSupport. To enable Tag authoring, Sun provides a library that contains both interface definitions and helper classes.
Using our previous example and converting it to the use of a custom tag, it would look like the following:
<HTML>
<HEAD>
<%@ taglib url="http://www.microps.com/JSPDev/customer_taglib" prefix="mpsjsp" %>
<TITLE></TITLE>
</HEAD>
<BODY>
<DIV ALIGN="CENTER">
<H1>Customer Info</H1>
<TABLE WIDTH="100%" BORDER="2" CELLPADDING="0" CELLSPACING="0">
<TR>
<TD>Customer ID:<mpsjsp:customer fieldVal="custID"/> </TD>
</TR>
<TR>
<TD>Customer Name:<mpsjsp:customer fieldVal="lastName"/></TD>
</TR>
<TR>
<TD>Address:<mpsjsp:customer fieldVal="address"/></TD>
</TR>
</TABLE></DIV> </BODY>
</HTML> |
So how do we produce this magic? There are a number of minimal steps.
Create the Java Class
Open a new class and name it "CustTag". Input the following:
package com.microps.jsptags;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.microps.jspbeans.customer;
public class CustTag extends TagSupport {
private customer g_cust = null;
private HttpServletRequest g_request = null;
private HttpSession g_session = null;
private String g_sName = "error";
public CustTag() {
g_request = (HttpServletRequest) this.pageContext.getRequest();
g_session = g_request.getSession();
}
public int doStartTag() {
try {
JspWriter _out = this.pageContext.getOut();
//first retreive the service javabean
g_cust = (customer)g_session.getAttribute("custbean");
if (g_sName.equals("custID")) {
_out.print(g_cust.getCustID());
} else if (g_sName.equals("lastName")) {
_out.print(g_cust.getLastName());
} else if (g_sName.equals("address")) {
_out.print(g_cust.getAddress());
} else {
_out.print("Wrong Attribute value");
}
} catch (java.io.IOException ioex) {
//error handler here
}
return (SKIP_BODY);
}
public void setFieldVal(String arg_sVal) {
g_sName = arg_sVal;
}
} |
Our class must extend TagSupport, which implements all the background setup and default behaviors, so that we only have to deal with the primary task of the tag.
Next we need to get the "customerBean" from the session object. To do this, we get the request object from the pagecontext (which was loaded for you by the underlying TagSupport framework) and using the request object to get the session. Then just get the session attribute that was loaded by a controller Servlet. You might be wondering how the name field "g_sName" gets loaded? It is loaded by the JSP engine using the method "setFieldVal(..)" which is called by the JSP runtime before the doStartTag(). Therefore, all that needs to be done to load attribute values, is to create "setter" methods. This is very much like the JSP JavaBean syntax viewed earlier in:
| <jsp:setProperty name="example" property="*"/> |
which auto loads all request elements that have matching "setter" methods.
We finish up by checking the value of the field "g_sName" and ouput values from our JavaBean accordingly. Then lastly, we must return an "int" value to tell the JSP engine what to do next. These values are predefined in constants. The required constant in this case is SKIP_BODY. This tells the parser that you are finished handling this tag and to not deal with anything that might have been placed in the body of the tag. (There are a number of other constants, and several new constants have been added in the new 1.2 spec.)
Create a Tag Library Descriptor
In order for the JSP parser to understand what to do with your tag and also to validate the syntax of your tag, there must be some sort of a "description" of the elements and syntax required. In addition, later the JSP runtime must know what class to instantiate to handle this tag. The tag descriptor that supports our example:
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems,Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <!-- a tag library descriptor--> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>mpsjsp</shortname> <uri>http://www.microps.com/JSPDev/customer_taglib</uri> <info> Sample Tag Library Descriptor - Customer </info> <!-- Defines a tag that supplies a value based on the name attribute --> <tag> <name>customer</name> <tagclass>com.microps.jsptags.CustTag</tagclass> <bodycontent>empty</bodycontent> <info> Insert values based on attribute values </info> <attribute> <name>fieldVal</name> <required>true</required> </attribute> </tag> </taglib> |
Most of what is in this file is common to all tag descriptors. The custom portion is in bold. The "shortname" is used to identify the library in management and IDE tools. In this case we have one tag defined, but you could have dozens of tags defined in a single tag descriptor file. Following is a description of each "tag" entry:
The last thing that needs to do be done, is register this library with the web application. Then web.xml file found in the WEB-INF/web.xml file needs to be edited.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app> <taglib> <taglib-uri>http://www.microps.com/JSPDev/customer_taglib</taglib-uri> <taglib-location>/WEB-INF/customer_taglib.tld</taglib-location> </taglib> </web-app> |
JBuilder provides a GUI front end to edit and add entries to this file. Double click on the file "web.xml" under "Deployment Descriptors". Then, in the structure pane, click the "Tag Libraries" node and this will open up an entry form where you can "register" all of your tag libraries. Type in the exact same "uri" that you used in the TLD file. Then provide the actual physical location of that TLD file. You can then click the "source" tab and you should see something very similar to the above.
Now that we have all the pieces, let's tie them together in a consistent sequence. For simplicity and flow I have left out a lot of details, but it will provide a proper "feeling" for what is happening.
It seems like a lot to do in order to evaluate a single tag. Remember that the JSP parser for that vendor's Servlet engine can cheat by caching, parsing and pre-validating much of this in advance. It only has to "look" like it works this way.
The really valuable feature that JBuilder provides the developer is to do all of these validation steps for you when you click "make". This insures that all of these issues are resolved up front before you deploy your application to the production machine.
Some Quick Deployment Notes
In the previous discussions I have commented on various deployment issues as they were appropriate. A full treatment of deployment would take more time and paper than this session will allow. I have done an additional paper that covers this in much more detail. At this point, I am just going to summarize a few critical high points covered previously.
Fortunately, much of the basic deployment issues are managed for you by JBuilder. The key here is to make sure you have followed the proper "setup" steps for a web application. Therefore, it is important that you patiently setup your JBuilder environment before beginning to code. Let JBuilder manage most of the rest. There are a number of places you will need to help JBuilder with a few of the details it does not yet handle.
Wrap UP
It was a lot to cover in such a short time. Hopefully I have lowered the bar on the learning curve a bit, making your next steps a little less taunting. The JSP API, because of its size, can lead to a wide variety of "methodologies", all of which have merit. I have presented one view on this landscape. That view centers around the maintenance "filter".
In addition, JBuilder features used for developing web applications, was introduced. JBuilder provides a complete structure for the maintenance and deployment of a web project. One key feature is that it stays out of the way and handles the mundane tasks of managing the location of files, checking syntax, and insuring that your application will compile on the target servlet engine. Wizards provide beginners a chance to "get something going", and the tutorials also provide a valuable jump start. A WAR file is automatically and dynamically maintained.
For smaller projects, using JSP expression tags with JavaBeans keeps minimum exposure of Java code in the JSP file. For larger projects, the investment in custom JSP tags is worth the extra effort. Custom JSP tags provide the perfect separation between the HTML presentation layer and Java logic that the HTML designer will find easy to utilize.
JSP Resources
General Links
JDance - Good collection of JSP links and resources. http://www.jdance.com/jsp.shtm
JSP Introduction. The Java Developer ConnectionSM (JDC) presents a Short Course written by JavaTM Software licensee jGuru (formerly named the MageLang Institute). This short course provides an introduction to JavaServer PagesTM (JSPTM) technology.
http://developer.java.sun.com/developer/onlineTraining/JSPIntro/contents.html
FrameWork Links
Cocoon is a 100% pure Java publishing framework that relies on new W3C technologies (such as DOM, XML, and XSL) to provide web content.
Resin® serves the fastest servlets and JSP. With Java and JavaScript support, Resin gives web applications the flexibility to choose the right language for the task. Resin's leading XSL (XML stylesheet language) support encourages separation of content from formatting.
The Struts Framework. The goal of this project is to provide an open source framework useful in building web applications with Java Servlet and JavaServer Pages (JSP) technology. Struts encourages application architectures based on the Model-View-Controller (MVC) design paradigm, colloquially known as Model 2 in discussions on various servlet and JSP related mailing lists.
http://jakarta.apache.org/struts/
Books
There are a lot of books available now on JSP and Servlets. What I have listed here is what I consider the "Top Five" in my library of over a dozen books on this topic. I added a brief comment as to why I consider it a member of this group.
Core Servlets and JavaServer Pages, Marty Hall, ISBN 0-13-089340-4
Very good "basic" reference book with useful examples. (Some books have such trivial examples)
More Servlets and JavaServer Pages, Marty Hall, Sun Microsystems Press, ISBN 0-13-067614-4. This is a just released book that covers material that most other Servlet and JSP pages do not cover in much detail. I consider it a "must have" book.
JavaServer Pages, Larne Pekowsky, ISBN 0201704218
If you want to "read a book from beginning to end" on JSP, this would be the one. Simple, clear and well organized. A good place to start.
Professional JSP, Karl Avedal, et. al., ISBN 1-861003-62-5
Some great code examples, the best I have found. More of a reference, though some chapters are worth reading if that is a area you are working.
Java Developer's Guide to Servlets and JSP, Bill Brogden, ISBN
Good code examples that are not found in most other books. Good XML examples using SAX and DOM parsers.