荔园在线

荔园之美,在春之萌芽,在夏之绽放,在秋之收获,在冬之沉淀

[回到开始] [上一篇][下一篇]


发信人: georgehill (毕业生【一个人的精彩】), 信区: Java
标  题: [转载] [DOC] JSP best practices (转寄)
发信站: 荔园晨风BBS站 (Mon Dec 17 22:57:33 2001), 站内信件

【 以下文字转载自 georgehill 的信箱 】
【 原文由 georgehill@smth.org 所发表 】
发信人: finger (肉猫), 信区: Java
标  题: [DOC] JSP best practices
发信站: BBS 水木清华站 (Mon Dec 17 17:28:00 2001)

来源:http://www.javaworld.com/javaworld/jw-11-2001/jw-1130-jsp.html


Follow these tips for reusable and easily maintainable JavaServer
Pages

Summary
This article discusses simple approaches and best practices that, when
used correctly, facilitate JavaServer Pages (JSPs) development. These
tips ensure reusable and easily maintainable JSPs, JSPs that allow
developers to focus on their programming strengths. (3,000 words;
November 30, 2001)
By Dustin Marx






avaServer Pages (JSPs) technology is an extension of Java servlet
technology and combines HTML and Java code into a single file. While
Java servlet technology focuses on Java classes capable of generating
HTML output with PrintWriter.println() statements, JSP technology
abstracts this concept to a higher level. With JavaServer Pages, a Web
developer can write static HTML pages and simply add Java code in
those sections of the page that need to be dynamically generated.
While this flexibility enables rapid development of simple Web
applications, it can be abused, resulting in unnecessarily complex
applications that are difficult to maintain, reuse, and enhance.

To avoid needlessly complex applications, follow the practices I present
 in this article:


Separate HTML from Java
Place business logic in JavaBeans
Factor general behavior out of custom tag handler classes
Favor HTML in Java handler classes over Java in JSPs
Use an appropriate inclusion mechanism
Use a JSP template mechanism
Use stylesheets
Use the MVC pattern
Use available custom tag libraries
Determine the appropriate level of XML compliance
Use JSP comments in most cases
Follow HTML best practices
Utilize the JSP exception mechanism
These tips will help you write JSPs that are reusable and easy to
maintain.

Separate HTML from Java
It can be tempting to throw all Java and HTML code necessary for a
Webpage into a single JSP file. In simple system development, such an
approach makes it easy for someone new to the system to locate all
relevant code in one place and understand how it all interacts. However,
 this approach becomes burdensome and costly when the application
grows more complex and more developers become involved.

Combining HTML and Java in the same source code can make the code
significantly less readable. To enhance software readability, developers
 often use indentation; but mixing HTML and Java scriptlets in the
same file can make useful indentation extremely difficult to maintain.


Many Web development methodologies and architectures now emphasize the
separation of HTML from Java code so different developers can focus on
their strengths. Properly separating Java and HTML, including
HTML-like JSP tags and custom tags, allows Web designers and HTML coders
 to work on the HTML (presentation) aspects, while Java developers
work on the application's Java (processing logic) portions. Java
developers focus on business logic as they implement the behavior behind
 the custom tags; Web designers then use these custom tags just as
they use ordinary HTML tags.

Applications with Java properly separated from HTML are more reusable
because the Java components are not tied to a Web browser and can be
used by other parts of the application. In addition, maintainability
is enhanced because of the increased modularization that comes from
Java/HTML separation.

Placing business logic in JavaBeans also promotes stronger applications.
 I'll explain how next.

Place business logic in JavaBeans
Java code included directly inside a JSP is not as readily accessible to
 other JSPs as Java code contained within a JavaBean. Common behavior
and business logic placed in JavaBeans can not only be used by other
JSPs but also by other portions of the application. That is because
JavaBeans are merely Java classes that satisfy some basic conventions
(such as a constructor with no arguments and public get/set methods
for private data members) and can be used as any other Java class.
Note that Enterprise JavaBeans (EJBs) are also useful for storing
behaviors and data common to all components of the application.

Factor general behavior out of custom tag handler classes
Java classes known as custom tag handlers implement custom tags.
Unlike JavaBeans, custom tag handler classes are not readily used like
ordinary Java utility classes. Instead, custom tag handler classes
implement specific interfaces -- or extend classes that provide these
interfaces' basic implementations. Because they are not readily reused
outside JSPs, custom tag handlers should contain only specific
behavior that would not be useful outside that custom tag -- that is,
outside the JSP. Custom tags often require support for common
behaviors or business logic and can utilize JavaBeans or EJBs that
perform those common behaviors.

Favor HTML in Java handler classes over Java in JSPs
Sometimes cleanly separating HTML, JSP tags, and HTML-like custom tags
from Java requires unnecessarily convoluted code. In these cases, you
either include Java scriptlets and expressions in the JSP or put some
HTML code in the Java tag handler class. I'd rather see a small amount
of HTML code in the Java class than see Java, such as scriptlets and
expressions, in the JSP. Since custom tag handlers are specific to the
custom tags they implement (and not reusable outside JSPs), placing
necessary HTML there is not troublesome. Sun's Java 2 Platform,
Enterprise Edition (J2EE) Blueprints documentation discusses this
issue further.

There are exceptions to this standard: if including one or two lines
of Java code as scriptlets in the JSP solves the same problem that would
 require many more lines of HTML in the Java handler class, allowing
Java code to exist in the JSP page might be prudent.

Use an appropriate inclusion mechanism
It is rarely good design to reproduce code commonly used by different
application pieces each time another piece of that application needs
that functionality. Factoring common JSP or HTML code out of multiple
pages and into a single file improves maintainability (you need to
make changes in only one location) and reusability.

Two JSP include mechanisms reduce code redundancy and promote
reusability; to ensure that you use the appropriate include mechanism,
it is important to know the differences between the two. Generally, I
use the include directive unless I can justify a need for the include
action. Question 7 in the Blueprints' "Web Tier" section provides a good
 resource for understanding the differences between the two include
mechanisms and determining which to use in a particular situation.

Include directive
A JSP's include directive includes the content of a specified file in
that JSP. Use the include mechanism for situations when text, such as
ASCII or HTML, needs to be included in multiple JSPs. For example, I
commonly use the include directive to include footer information, such
as company name or copyright date, on every JSP in a company's
application.

Since you include the content of any file specified by the include
directive in the calling JSP before it compiles, variables and other
values specified in the calling JSP can also be utilized in the included
 content. However, I try not to rely on variables defined in the calling
 JSP, since this dependency reduces the included file's reusability.

Include action
The include action executes the specified JSP first and then places
the generated response in the calling JSP. Because the include action
includes the generated response rather than the source content itself,
variables and other values specified in the calling JSP are not
available to the page included with the include action.

One disadvantage of the include action as currently implemented by the
JSP implementations with which I am familiar relates to the flush="true"
 attribute. In the JSP implementations I have used, this attribute is
required and must be set to true. The true value indicates that the
buffer will always flush before a target page specified by the include
action executes. This can prove problematic if the forward mechanism
is invoked either explicitly or implicitly later in the JSP. In the
recently released JSP specification (1.2), however, the include action's
 flush attribute can be set to false. Tomcat 4.0 provides a reference
implementation of this specification and supports this new include
action argument.

Use a JSP template mechanism
A template mechanism allows for a common file to control Webpage, or
JSP, layout. Then, when you want to change the layout, you need to
modify only one file, and all the other pages will reflect the layout
change. This doesn't just make for more maintainable code; using
templates to control layout also makes Webpages more aesthetically
pleasing to users who see consistent layouts for all an application's
pages.

I use Struts' custom tag template library as a template mechanism. David
 Geary's article "JSP Templates" provides a good starting point for
looking at using templates with your JSPs.

Use stylesheets
Just as templates enable developers to place layout control in a
single location, stylesheets enable developers to place appearance
control in a single location. I use Cascading Style Sheets (CSS) to
control such items as font families, font sizes, and table
characteristics. Like templates, stylesheets allow the developer to make
 changes in one location; those changes immediately reflect on all
appropriate pages, resulting in increased maintainability and consistent
 appearance to users.

Use the MVC pattern
While other design patterns can be used effectively with JSPs, I often
use the Model-View-Controller (MVC) architecture with JSP technology.
MVC enables the development of applications that are easier to create,
test, maintain, and enhance. In JSP terminology, implementation of an
MVC architecture is often referred to as Model 2 (from an early JSP
specification). The J2EE Blueprints samples are based on MVC.

See "E++: A Pattern Language for J2EE Applications, Part 1" by Bin Yang,
 and "Understanding JavaServer Pages Model 2 Architecture" by Govind
Seshadri, for more information on JSPs and MVC.

Struts
Struts is an open source MVC implementation (it's a Jakarta subproject
available through the Apache license) that provides base controller
functionality that you can extend and enhance in your own applications.
 The base controller is implemented as a Java servlet, and its
configuration is controlled by an XML file called struts-config.xml.
When a Struts-based JSP Web application is created correctly, most
changes in flow control are made in the struts-config.xml file rather
than in the code itself.

Implementing an application that is MVC-compliant involves extra initial
 effort, but the investment in time up front is worth the rewards of
more maintainable and reusable code. Plus, Struts significantly
reduces the preliminary work involved in implementing MVC.

Besides supporting MVC implementations, Struts also provides some
valuable custom tag libraries, such as the template tag library
mentioned previously. The logic tag library has custom tags for
iteration and tags for if-then-else structures. The HTML tag library
features many useful custom tags, including custom tags for FORM tags
and form item tags used in Struts' form handling and validation. See the
 Struts documentation for more details on these libraries and other
Struts custom tag libraries. I'll discuss the advantages of using
these libraries next.

Use available custom tag libraries
Why should developers spend time reinventing the wheel and worrying
about testing and debugging when custom tag libraries are readily
available for many different purposes? Some vendors provide custom tag
libraries to their customers for free or for individual purchase, but
many custom tags can be found online. Resources provides a good starting
 point for locating potentially useful tag libraries.

While these third-party custom tag libraries occasionally have bugs,
most likely such problems will be discovered, since many developers
use these libraries and test them in their own applications. Also,
many custom tags are open source, so you can edit them to meet your
needs.

I find it well worth my time to keep informed of available custom tags,
 since these libraries often provide functionality common to most Web
applications. While learning about available custom tag libraries
requires a small time investment, reusing already-available custom
tags saves the time of writing, testing, and debugging my own custom
tags. As mentioned above, many tag libraries are also open source; in
these cases, I can readily adapt general behavior to my specific
project's situation.

Determine the appropriate level of XML compliance
Most JSP developers use shorthand syntax for JSP tags rather than XML
syntax. This is partially evidenced by Sun's JavaServer Pages Syntax
Reference, which lists only the tags' shorthand form.

An advantage to using a 100 percent XML-compliant JSP, including
syntax for JSP tags, is that XML validation tools can validate the JSP.
 XML tools can validate the JSP against a DTD (document type definition)
 that enforces standard JSP syntax rules.

However, at present writing and maintaining JSPs with XML tag syntax
often involves far more effort than the rewards justify. As tools are
developed that automatically convert shorthand syntax to XML syntax, the
 benefits of XML-compliant JSPs will likely make the reduced effort
worthwhile. I have waited for the JSP specification and its
implementations to mature in relation to XML-compliant JSPs before fully
 utilizing XML-compliant tags. See the sidebar below, "XML in the JSP
Specifications," for more information on how XML compliance is handled
in the latest JSP specification.

I am not implying that you cannot currently use XML with JavaServer
Pages technology. I simply prefer to wait for better tools to manage the
 JSP-to-XML mapping as outlined in the 1.2 specification before pursuing
 XML-compliant JSPs (also called JSP documents). There are, however,
other ways the two technologies can be used together. See Resources
for articles on using XML with JSPs.

Be sure to keep abreast of the latest JSP specification and the tools
your preferred vendors provide that implement that spec's new features,
 such as JSP-to-XML mapping. Apache provides Tomcat 4.0 as a reference
implementation of the JSP 1.2 Specification.

Use JSP comments in most cases
Appropriate commenting seems to challenge software developers. JSPs,
like other types of code, should include comments that describe
complex or extraordinary functionality, the pages' purpose, and other
general information typically commented out in source code.

Since JSPs allow developers to intermix Java, JSP tags, and HTML tags in
 the same page, there are multiple ways to comment a JSP page.
Developers should carefully consider which type of comment to employ
in the page. HTML comments will be viewable in the compiled JSP's HTML
source code, and both major browsers make viewing this source easy.
JSP comments, on the other hand, are not placed in the HTML document
created by the JSP compilation process. These comments cannot be
viewed as part of the page's source through the browser, and they do not
 increase the size of the rendered page's generated source. Java
comments can also occur in a JSP inside Java scriptlet sections. These
are not viewable in the browser either, but including Java comments in
the JSP page violates the principle of separating Java from the HTML.

Code comments are usually meant for developers who write and maintain
code. Therefore, use JSP comments unless there is a compelling reason to
 have the comments display in the browser upon request.

Note that you should not place sensitive data in JSP source code, not
even inside JSP comments. Although the text inside JSP comments is not
compiled into the source used to render the Webpage, Web servers might
allow users to view JSP source code. Place sensitive data in a database,
 where access to the data can be controlled and monitored using triggers
 or other database mechanisms.

Follow HTML best practices
When Java is factored out of the JSP and into JavaBeans and custom tag
handlers, the JSP consists mostly of JSP tags, including custom tags,
and HTML tags. To make the JSP easier to understand and maintain, follow
 best practices related to HTML development.

One HTML best practice I follow: include closing tags recommended by the
 HTML specification even when the browsers do not require them. Most
HTML generation tools will match opening tags with corresponding closing
 tags, but hand-typed HTML documents often lack closing tags (note
that there is a small set of HTML tags that lack closing tags). Browsers
 usually render the page despite missing closing tags, but don't count
on the browser to work correctly when standards are violated. Some
missing closing tags, such as </table>, can dramatically affect a page's
 rendering in the browser. In addition, you should avoid using
deprecated HTML tags, and use lowercase letters for all HTML tags.

The W3C (World Wide Web Consortium) has some resources related to HTML
best practices and validation.

Utilize the JSP exception mechanism
While a thrown exception's stack trace proves extremely useful for
developers when debugging their code, it is rarely desirable to share an
 entire exception stack trace with the software's users. Lengthy stack
traces are not aesthetically pleasing and can increase security risks by
 exposing information that does not need to be released. JSPs allow
developers to catch and handle exceptions in the code, resulting in more
 secure and aesthetically pleasing exception handling. See Resources for
 details on the mechanics of JSP exception handling.

Exception information is more useful if information besides the stack
trace is included. JSPs can use session variables to store information
about the current page and current operation being performed. Then, if
an exception does occur, the exception page will be called; it will have
 access to both the thrown exception and the information about the
original page that caused the exception. The exception page can
utilize underlying Java code, in JavaBeans or EJBs, to store in the
database the complete exception information, related session
information, and the exception's date and time.

To reduce the unsightly error messages printed to the screen and improve
 security, the exception page need only print out a simple error message
 and perhaps an identifying number that allows developers to locate more
 detailed exception information in the database. For aesthetic and
security reasons, I prefer storing most of the exception information
in a database or flat file rather than printing it all to the screen.
Storing the exception information in a database or flat file also allows
 the information to be persisted even when a user exits the application.
 Note that during development you should print full exception
information to the screen for regular testing and debugging.

Now start developing JSPs
If abused, many JSP conveniences can lead to unnecessary complexity.
This article summarizes some JSP practices that allow developers to take
 advantage of these conveniences without triggering unnecessary
complexity. By following the best practices discussed here, you will
increase your software's maintainability and reusability as well as
its aesthetic qualities.

Situations might arise where the overhead of some of these recommended
JSP practices is not worth the cost, such as in extremely simple
applications. However, my experience is that even the simplest
applications often evolve into more complex systems. In most cases,
the sooner you follow best practices such as these, the better.




About the author
Dustin Marx is a senior software engineer at Raytheon Systems Company in
 Aurora, Colo. He has a bachelor's degree in electrical engineering
and a master's degree in business administration. He has been writing
software for more than 10 years and, for the last five years, has been
concentrating on object-oriented software using C++ and Java. Although
he typically prefers processing and database-related development over
GUI work (especially HTML pages), he has found JavaServer Pages
technology to be appealing when the practices recommended in this
article are followed.



Resources

The JavaServer Pages Syntax Reference provides a quick summary of
basic JSP tags:
http://java.sun.com/products/jsp/tags/11/tags11.html

"Hans's Top Ten JSP Tips," Hans Bergsten (O'Reilly, November 2000)
contains 10 useful tips for JSP development, including discussions on
the two include mechanisms and when to use forward and when to use
redirect:
http://java.oreilly.com/news/jsptips_1100.html

Aurora Information Systems' "JSP Design Notes" discusses using EJBs with
 JavaServer Pages:
http://www.aurorainfo.com/wp8/

These excerpts from Professional JSP, Simon Brown et al. (Wrox Press,
April 2001; ISBN: 1861004958) provide useful information on JSPs, the
relationship of JSPs to the rest of J2EE, and architectural
considerations when using JSPs:
http://www.enterprisedeveloper.com/wrox/profjsp/contents.htm

The Sun J2EE Blueprints documentation presents some best practices and
architectural considerations for developing J2EE applications. JSP
developers often find the "Web Tier" portion most useful:
http://java.sun.com/blueprints/enterprise/

This section of Sun's J2EE Blueprints answers common questions related
to J2EE applications' Web tiers. This section also discusses the
differences between the two JSP include mechanisms and offers
suggestions for deciding which mechanism to use for a given situation:

http://java.sun.com/j2ee/blueprints/web_tier/qanda/index.
html#directive

This Blueprints description of the Model-View-Controller architecture is
 helpful for understanding MVC:
http://java.sun.
com/j2ee/blueprints/design_patterns/model_view_controller/index.html

I highly recommend using and extending Struts to facilitate MVC
architectures with JSPs:
http://jakarta.apache.org/struts/index.html

Part of Struts, the template custom tag library is a subproject under
Apache's Jakarta Project:
http://jakarta.apache.org/struts/struts-template.html

"Strut Your Stuff with JSP Tags," Thor Kristmundsson (JavaWorld,
December 2000) describes how to use and extend the open source Struts
JSP tag library:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1201-struts.html

"Encapsulate Reusable Functionality in JSP Tags," Simon Brown
(JavaWorld, August 2000) shows how to build your own custom JSP tags
with Tomcat:
http://www.javaworld.com/javaworld/jw-08-2000/jw-0811-jsptags.html

"JSP Templates," David Geary (JavaWorld, September 2000) discusses using
 templates to encapsulate Web design and encourage modularization:
http://www.javaworld.com/javaworld/jw-09-2000/jw-0915-jspweb.html

"Understanding JavaServer Pages Model 2 Architecture," Govind Seshadri
(JavaWorld, December 1999) discusses the Model 2 architecture and MVC:

http://www.javaworld.com/javaworld/jw-12-1999/jw-12-ssj-jspmvc.html

In "E++: A Pattern Language for J2EE Applications, Part 1" (JavaWorld,
April 2001), Bin Yang overviews the E++ pattern language and explains
how MVC and JSPs fit into the J2EE framework process described by E++:

http://www.javaworld.com/javaworld/jw-04-2001/jw-0420-eplus.html

Core J2EE Patterns: Best Practices and Design Strategies, Deepak Alur,
John Crupi, and Dan Malks (Prentice Hall PTR, 2001; ISBN: 0130648841)
discusses several design patterns related to application presentation
tiers:
http://www.amazon.com/exec/obidos/ASIN/0130648841/javaworld

Here's a good starting point for locating publicly available custom
tag libraries:
http://jsptags.com/

Taglibs is an Apache subproject that focuses on JSP custom tag libraries
 (note that this subproject is different from Struts, which has its
own custom tag libraries):
http://jakarta.apache.org/taglibs/index.html

The JSP specifications (currently 1.1 Final Release and 1.2 Final
Release) are available for download. They are highly recommended reading
 for understanding the steps needed to convert traditional shorthand
JSPs to XML-compliant JSP documents:
http://java.sun.com/products/jsp/download.html#specs

Although the JavaServer Pages specifications are straightforward, Hans
Bergsten provides a nice overview of 1.2's features in this two-part
series:
"JSP 1.2: Great News for the JSP Community, Part 1" (OnJava.com, October
 2001)
"JSP 1.2: Great News for the JSP Community, Part 2" (OnJava.com,
November 2001)
"JSP Syntax and Semantics," a chapter from Professional Java XML
Programming with Servlets and JSP, Tom Myers and Alexander Nakhimovsky
(Wrox Press, 1999; ISBN: 1861002858), discusses in detail the
differences between XML syntax and shorthand JSP syntax:
http://www.perfectxml.com/wp/2858/28581002.htm

"Developing XML Solutions with JavaServer Pages Technology" discusses
ways that XML and JSPs can be used together for effective Web solutions:

http://java.sun.com/products/jsp/html/JSPXML.html

"Using XML and JSP Together," Alex Chaffee (JavaWorld, March 2000)
discusses building a dynamic Website with XML and JSPs:
http://www.javaworld.com/javaworld/jw-03-2000/jw-0331-ssj-jspxml.html

The HyperText Markup Language Home Page contains links to many useful
sites related to the World Wide Web Consortium's markup languages and
specifications:
http://www.w3.org/MarkUp/

The W3C's HTML 4.01 Specification covers the latest HTML specification:

http://www.w3.org/TR/html4/

The W3C's HTML Validation Service is useful for validating your HTML:
http://validator.w3.org/

The W3C's recommendation on the Extensible HyperText Markup Language
explains the direction HTML is taking to create JSPs that will work well
 with future HTML developments:
http://www.w3.org/TR/xhtml1/

The mechanics of using the JSP exception-handling capability:
http://java.sun.com/products/jsp/html/exceptions.fm.html

Java Specification Request (JSR) 127 on JavaServer Faces relates
directly to GUIs built for Java server applications and is something JSP
 developers should be aware of as it progresses:
http://jcp.org/jsr/detail/127.jsp

To read more articles about JavaServer Pages, browse our Topical Index:

http://www.javaworld.com/channel_content/jw-jsp-index.shtml

To share your JSP best practices, log in to JavaWorld's Enterprise
Java discussion:
http://forums.idg.net/webx?50@@.ee6b80a

Sign up for the free JavaWorld This Week's Enterprise Java newsletter:

http://www.idg.net/jw-subscribe

You'll find a wealth of IT-related articles from our sister publications
 at IDG.net



--

                          Your Friend
                        ^_^ finger  ^_^
                             肉猫



※ 修改:·finger 於 Dec 17 19:30:47 修改本文·[FROM: 166.111.120.103]
※ 来源:·BBS 水木清华站 smth.org·[FROM: 166.111.120.103]
--
※ 转载:·荔园晨风BBS站 bbs.szu.edu.cn·[FROM: 192.168.1.238]


[回到开始] [上一篇][下一篇]

荔园在线首页 友情链接:深圳大学 深大招生 荔园晨风BBS S-Term软件 网络书店