As JavaServer Pages (JSP) technology is becoming widely adopted in web-based applications, many JSP programmers and web developers embarking on developing and maintaining these applications face a dilemma like that of many Java programmers: "How do we structure JSP code that is easier to read, write and maintain consistently?" In this article, we propose a set of standard conventions for writing JSP pages (versions 1.1 and 1.2) that should be followed on a typical software project using web components. The article draws on the Code Conventions for the Java Programming Language as a template to identify various important elements that should be addressed in a coding conventions specification (relevant to JSP technology). In particular, it addresses file names and organization, indentation, comments, directives, declarations, scriptlets, expressions, white space, naming conventions, and programming practices. As this is our first attempt at presenting a set of JSP coding conventions, we're quite interested in any feedback you may have on these recommendations. Please send all feedback to jsp-codeconv-comments@sun.com. The JavaServer Pages 2.0 Specification, while fully backwards compatible with version 1.2, allows for a script-free programming style (without declarations, scriptlets and expressions) and has a number of new features that are expected to evolve these conventions. Where possible, this article chooses conventions that will leverage the new JSP 2.0 technology features.
Finally, we assume that you are familiar with JSP technology, Java technology and Java code conventions as already adopted by your organization for your projects. If not, we recommend that you start with Java technology here and JSP technology here. Why Have Code Conventions?Code conventions are important to programmers and web content developers for a number of reasons:
File Names and LocationsFile naming gives tool vendors and web containers a way to determine file types and interpret them accordingly. The following table lists our recommended file suffixes and locations.
There are a few things to keep in mind when reading the table above. First, <context root> is the root of the context of the web application (the root directory inside a
Third, we use the term JSP fragment to refer to a JSP page that can be included in another JSP page. Note that in the JSP 2.0 Specification, the term "JSP segment" is used instead as the term "JSP fragment" is overloaded. JSP fragments can use either
Finally, it is in general a good practice to place tag library descriptor files and any other non-public content under
An optional welcome file's name, as declared in the
When internationalizing JSP files, we recommend that you group JSP pages into directories by their locale. For example, the US English version of File OrganizationA well-structured source code file is not only easier to read, but also makes it quicker to locate information within the file. In this section, we'll introduce the structures for both JSP and tag library descriptor files. JSP File / JSP Fragment FileA JSP file consists of the following sections in the order they are listed:
Opening CommentsA JSP file or fragment file begins with a server side style comment:
This comment is visible only on the server side because it is removed during JSP page translation. Within this comment are the author(s), the date, and the copyright notice of the revision, an identifier and a description about the JSP page for web developers. The combination of characters " In some situations, the opening comments need to be retained during translation and propagated to the client side (visible to a browser) for authenticity and legal purposes. This can be achieved by splitting the comment block into two parts; first, the client-side style comment:
and then a shorter server side style comment: <%-- - @(#) - Description: --%> JSP Page Directive(s)A JSP page directive defines attributes associated with the JSP page at translation time. The JSP specification does not impose a constraint on how many JSP page directives can be defined in the same page. So the following two Code Samples are equivalent (except that the first example introduces two extra blank lines in the output): Code Sample 1: <%@ page session="false" %> <%@ page import="java.util.*" %> <%@ page errorPage="/common/errorPage.jsp" %> If the length of any directive, such as a page directive, exceeds the normal width of a JSP page (80 characters), the directive is broken into multiple lines: Code Sample 2:
<%@ page session="false"
import="java.util.*"
errorPage="/common/errorPage.jsp"
%>
In general, Code Sample 2 is the preferred choice for defining the page directive over Code Sample 1. An exception occurs when multiple Java packages need to be imported into the JSP pages, leading to a very long
In this scenario, breaking up this page directive like the following is preferred:
Note that in general the <%@ page import="com.mycorp.bank.savings.*" %> <%@ page import="com.thirdpartycorp.cashmanagement.*" %> <%@ page import="com.mycorp.bank.foreignexchange.*" %> ... In the latter case, the written JSP page is neater but it is harder to locate classes. In general, if a JSP page has too many import directives, it is likely to contain too much Java code. A better choice would be to use more JSP tags (discussed later in this article). Optional Tag Library Directive(s)A tag library directive declares custom tag libraries used by the JSP page. A short directive is declared in a single line. Multiple tag library directives are stacked together in the same location within the JSP page's body: <%@ taglib uri="URI1" prefix="tagPrefix1" %> <%@ taglib uri="URI2" prefix="tagPrefix2" %> ... Just as with the page directive, if the length of a tag library directive exceeds the normal width of a JSP page (80 characters), the directive is broken into multiple lines:
<%@ taglib
uri="URI2"
prefix="tagPrefix2"
%>
Only tag libraries that are being used in a page should be imported. From JSP 1.2 Specification, it is highly recommended that the JSP Standard Tag Library (JSTL) be used in your web application to help reduce the need for JSP scriptlets in your pages. Pages that use JSTL are, in general, easier to read and maintain. Optional JSP Declaration(s)
JSP declarations declare methods and variables owned by a JSP page. These methods and variables are no different from declarations in the Java programming language, and therefore the relevant code conventions should be followed. Declarations are preferred to be contained in a single <
HTML and JSP CodeThis section of a JSP page holds the HTML body of the JSP page and the JSP code, such JSP expressions, scriptlets, and JavaBeans instructions. Tag Library DescriptorA tag library descriptor (TLD) file must begin with a proper XML declaration and the correct DTD statement. For example, a JSP 1.2 TLD file must begin with:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
This is immediately followed by a server-side style comment that lists the author(s), the date, the copyright, the identification information, and a short description about the library:
The rules and guidelines regarding the use of these elements are the same for those defined for JSP files/fragment files. The rest of the file consists of the following, in the order they appear below:
It is recommended that you always add the following optional sub-elements for the elements in a TLD file. These sub-elements provide placeholders for tag designers to document the behavior and additional information of a TLD file, and disclose them to web component developers.
IndentationIndentations should be filled with space characters. Tab characters cause different interpretation in the spacing of characters in different editors and should not be used for indentation inside a JSP page. Unless restricted by particular integrated development environment (IDE) tools, a unit of indentation corresponds to 4 space characters. Here is an example:
<myTagLib:forEach var="client" items="${clients}">
<myTagLib:mail value="${client}" />
</myTagLib:forEach>
A continuation indentation aligns subsequent lines of a block with an appropriate point in the previous line. The continuation indentation is in multiple units of the normal indentation (multiple lots of 4 space characters):
Indentation of Scripting Elements
When a JSP scripting element (such as declaration, scriptlet, expression) does not fit on a single line, the adopted indentation conventions of the scripting language apply to the body of the element. The body begins from the same line for the opening symbol of the element
The lines within the body not containing the opening and the enclosing symbols are preceded with one unit of normal indentation (shown as Compound Indentation with JSP, HTML and Java
Compound indentation, for JSP elements intermingled with Java scripting code and template text (HTML), is necessary to reduce the effort of comprehending a JSP source file. This is because the conventional normal indentation might make seeing the JSP source file difficult. As a general rule, apply an extra unit of normal indentation to every element introduced within another one. Note that this alters the indentations of the final output produced for the client side to render for display. The additional indentations, however, are usually ignored (by the browser) and have no effect on the rendered output on the browser. For instance, adding more space characters before a
than this:
CommentsComments are used sparingly to describe additional information or purposes of the surrounding code. Here we look at two types for JSP files: JSP and client-side comments. JSP CommentsJSP comments (also called server-side comments) are visible only on the server side (that is, not propagated to the client side). Pure JSP comments are preferred over JSP comments with scripting language comments, as the former is less dependent on the underlying scripting language, and will be easier to evolve into JSP 2.0-style pages. The following table illustrates this:
Client-Side Comments
Client-side comments ( The use of client-side comments is generally discouraged, as a client / user does not need or read these kinds of comments directly in order to interpret the received responses. An exception is for authenticity and legality purposes such as the identification and copyright information as described above. Another exception is for HTML authors to use a small amount of HTML comments to embody the guidelines of the HTML document structures. For example:
Multiline Comment BlockA multiline comment block, be it JSP or client-side, is decorated with the dash character "-". In the XML specification, the double-dash string "--" is not allowed within an XML comment block. Thus, for compatibility and consistency with this specification, no double-dash string is used to decorate comment lines within a multiline comment block. The following table illustrates this preference using a client-side comment block:
JSP DeclarationsAs per the Java code convention, declarations of variables of the same types should be on separate lines:
JavaBeans components should not be declared and instantiated using JSP declarations but instead should use the In general, JSP declarations for variables are discouraged as they lead to the use of the scripting language to weave business logic and Java code into a JSP page which is designed for presentation purposes, and because of the overhead of managing the scope of the variables. JSP ScriptletsWhere possible, avoid JSP scriptlets whenever tag libraries provide equivalent functionality. This makes pages easier to read and maintain, helps to separate business logic from presentation logic, and will make your pages easier to evolve into JSP 2.0-style pages (JSP 2.0 Specification supports but deemphasizes the use of scriptlets). In the following examples, for each data type representation of the customers, a different scriptlet must be written:
customers as an
However, if a common tag library is used, there is a higher flexibility in using different types of customers. For instance, in the JSP Standard Tag Library, the following segment of JSP code will support both array and
In the spirit of adopting the model-view-controller (MVC) design pattern to reduce coupling between the presentation tier from the business logic, JSP scriptlets should not be used for writing business logic. Rather, JSP scriptlets are used if necessary to transform data (also called "value objects") returned from processing the client's requests into a proper client-ready format. Even then, this would be better done with a front controller servlet or a custom tag. For example, the following code fetches the names of customers from the database directly and displays them to a client:
The following segment of JSP code is better as it delegates the interaction with the database to the custom tag
In summary:
JSP ExpressionsJSP Expressions should be used just as sparingly as JSP Scriptlets. To illustrate this, let's look as the following three examples which accomplish equivalent tasks: Example 1 (with explicit Java code):
<%= myBean.getName() %>
Example 2 (with JSP tag):
<jsp:getProperty name="myBean" property="name" />
Example 3 (with JSTL tag):
<c:out value="${myBean.name}" />
Example 1 assumes that a scripting variable called
Of the three examples, the JSTL tag example is preferred. It is almost as short as the JSP expression, it is just as easy to read and easier to maintain, and it does not rely on Java scriptlets (which would require the web developer to be familiar with the language and the API calls). Furthermore, it makes the page easier to evolve into JSP 2.0-style programming, where the equivalent can be accomplished by simply typing Finally, JSP expressions have preference over equivalent JSP scriptlets which rely on the syntax of the underlying scripting language. For instance,
<%= x %>
is preferred over
<% out.print( x ); %>
White SpaceWhite space further enhances indentation by beautifying the JSP code to reduce comprehension and maintenance effort. In particular, blank lines and spaces should be inserted at various locations in a JSP file where necessary. Blank Lines
Blank lines are used sparingly to improve the legibility of <strike>the</strike>a JSP page, provided that they do not produce unwanted effects on the outputs. For the example below, a blank line inserted between two JSP expressions inside an HTML
Blank Spaces
A white space character (shown as
<%= customer.getName() %>
is preferred over
<%=customer.getName()%>
There should also be space characters separating JSP comment tags and comments:
Naming ConventionsApplying naming conventions makes your web component elements easier to identify, classify and coordinate in projects. In this section, we will look at these conventions specific to JSP technology. JSP NamesA JSP (file) name should always begin with a lower-case letter. The name may consist of multiple words, in which case the words are placed immediately adjacent and each word commences with an upper-case letter. A JSP name can be just a simple noun or a short sentence. A verb-only JSP name should be avoided, as it does not convey sufficient information to developers. For example:
perform.jsp
is not as clear as
performLogin.jsp
In the case of a verb being part of a JSP name, the present tense form should be used, since an action by way of backend processing is implied:
showAccountDetails.jsp
is preferred over
showingAccountDetails.jsp
Tag NamesThe naming conventions for tag handlers and associated classes are shown below:
In addition, tag names must not violate the naming conventions of class and interface as specified in the relevant code convention for Java technology. To further distinguish a tag-relevant class from other classes, a package suffix, tags, or taglib can be applied to the package name of the class. For example:
com.mycorp.myapp.tags.XXXTag
Tag Prefix NamesA tag prefix should be a short yet meaningful noun in title case, and the first character in lower-case. A tag prefix should not contain non-alphabetic characters. Here are some examples:
JSP Pages in XML SyntaxJSP provides two distinct syntaxes: a "standard syntax" for writing JSP pages and an "XML syntax" for writing JSP pages as an XML document. JSP pages that are written using the standard syntax are referred to as "JSP pages." JSP pages that are written using the XML syntax are referred to as "JSP documents". This article primarily addresses JSP pages, but many of the concepts can be applied to JSP documents as well. Use of JSP documents is expected to increase as XML becomes more prevalent, and to address this the JSP 2.0 specification will introduce a much friendlier XML syntax. It should be noted that the XML syntax used to author JSP pages is distinct from and is often confused with the XML view of a JSP page. The page author uses either the standard or the XML syntax to author a JSP page. The container then translates the JSP page into its XML view, which is exposed to Tag Library Validators. JSP Document StructureJSP documents have the following basic structure:
The first line is an optional XML Prolog that defines the page as an XML document. After the optional prolog comes the comments for the document. The element
A JSP document must be a well-formed XML document, so some elements, such as XML Comments
The JSP Specification is unclear about whether XML-style comments are stripped on output, so to be safe if a comment is intended to reach the client, it should be enclosed in a
Java Code in JSP DocumentsWhen writing Java code inside declarations, scriptlets, and expressions, a CDATA element should be used only when necessary to ensure your code does not break the document structure.
Unlike those in the standard syntax, XML indentation rules should be followed regardless of the contents of an element. Programming PracticesIn general, avoid writing Java code (declarations, scriptlets and expressions) in your JSP pages, for the following reasons:
See the Enterprise section of Java BluePrints for more guidelines and details. JavaBeans Component Initialization
JSP technology provides a convenient element to initialize all
<jsp:setProperty name="bankClient" property="*"/>
However, this should be used with caution. First, if the bean has a property, say,
If you still prefer to use <%-- - requires firstName and lastName from the ServletRequest --%> <jsp:setProperty name="bankClient" property="*" /> JSP Implicit ObjectsDirect use of JSP implicit objects to gain references to these objects rather than API calls is preferred. So, instead of using
getServletConfig().getServletContext().getInitParameter("param")
to access the initialization parameter as provided by the
application.getInitParameter("param")
In the case that only the value of an initialization parameter is outputted, it would be even better to use a JSTL tag to access the initialization parameter:
<c:out value="${initParam['param']}" />
QuotingThe uniform use of quoting is adopted. Quotations should be bound by two double-quote characters " instead of two apostrophe characters ' .
An exception is when apostrophes are needed, for example when double-quote characters are required within the scripting language:
<jsp:include page='<%= getFoodMenuBar("Monday") %>' />
Using Custom TagsIf a custom tag does not have a body content, the content should be declared explicitly with empty (rather than defaulting to the word "JSP") like this in the tag library descriptor:
This tells the JSP container that the body content must be empty rather than containing any JSP syntax to be parsed. The effect is to eliminate unnecessarily allocation of resources for parsing of empty body contents. Empty tags should be in short XML elements, rather than using opening-closing XML element pairs to improve readability. So,
<myTag:hello />
is preferred over
<myTag:hello></myTag:hello>
Use of TagExtraInfo and TagLibraryValidator
Sometimes, the valid ways to use a tag library cannot be expressed using the TLD alone. Then, a Use of JavaScript TechnologyJavaScript technology should be independent of particular features of browser types in order for the scripts to run properly. Where it makes sense, it is a good idea to keep JavaScript code in individual files separate from JSP bodies, and use a statement like the following to import the JavaScript code into the JSP bodies:
<script language=javascript src="/js/main.js">
This improves the chance for the JavaScript code to be reused, maintains the consistent behavior of the JavaScript code across multiple JSP pages, and reduces the complexity of JSP pages. Cascading Style SheetsUse cascading style sheets to centralize control of common characteristics of headings, tables, and so on. This improves the consistency of presentation to the users and reduces maintenance effort and the code size of the JSP pages. So, instead of embedding the style information in the HTML tags like the one below: <H1><FONT color="blue">Chapter 1</FONT></H1> ... <H1><FONT color="blue">Chapter 2</FONT></H1> ...
Define the style information in a single style sheet H1 { color: blue }
And apply the style sheet to the JSP page:
Use of Composite View PatternsWhen a JSP page requires a certain and complex structure which may also repeat in other JSP pages, one way to handle this is to break it up into pieces, using the Composite View pattern (the Patterns section of Java Blueprints). For instance, a JSP page sometimes has the following logical layout in its presentation structure:
In this manner, this composite JSP page can be divided into different modules, each realized as a separate JSP fragment. Constituent JSP fragments can then be placed in appropriate locations in the composite JSP page, using translation-time or request-time include JSP tags. In general, when static include directives are used to include a page that would not be requested by itself, remember to use the
Other RecommendationsIn this article, we presented a set of recommended code conventions to produce JSP code and web component artifacts that are more maintainable and consistent. There are many other best practices if you choose to pursue this subject further. For instance, the JSP 1.2 specification has recommendations for:
In addition, Java BluePrints offers best practices on a broader scale, such as the use of Model-View-Controller pattern (found in the Patterns section). We're interested in your input on the conventions presented in this article and we'd like you to share what other recommendations you might have for JSP coding conventions. Please send your feedback to jsp-codeconv-comments@sun.com. Below, we present the source code to a full web application that demonstrates the code conventions presented above. You can download the a WAR file for this application here. Code ExamplesAn example web application is presented here to demonstrate the conventions as outlined in this document. It consists of the following source code files and directory structures bundled in a .war file:
The index.jsp page uses a custom tag library (as identified by The example requires JSP 1.2 and JSTL 1.0 technologies.
AcknowledgmentsAcknowledgments are given to Gregory Murray (Java BluePrints Team), Damian Fauth (Sun Java Center) and Kate Morris (Sun Java Center) who provided invaluable comments on earlier drafts of this document. References
Share your feedback and join our online discussion! Have a question about programming? Use Java Online Support. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
| ||||||||||||