ebook img

JSP Examples and Best Practices PDF

295 Pages·2002·5.225 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview JSP Examples and Best Practices

JSP Examples and Best Practices by Andrew Patzer ISBN: 1590590201 This useful resource covers JSP, Servlets, JUnit, JMeter, Ant, CVS, Customer Tags, and JavaBeans, and provides plenty of source code. 1 Table of Contents JSP Examples and Best Practices Introduction Chapter 1 JSP Foundations Chapter 2 Using JSP Chapter 3 Role Separation with Javabeans Chapter 4 Role Separation with Custom Tags Chapter 5 Development Using Patterns Chapter 6 The Decorating Filter Pattern Chapter 7 The Front Controller Pattern Chapter 8 The View Helper Pattern - Chapter 9 Testing Techniques - Chapter 10 Deployment Techniques - Chapter 11 Application Frameworks Chapter 12 Putting it all Together Index List of Figures List of Tables List of Listings 2 JSP Examples and Best Practices ANDREW PATZER Copyright ?2002 by Andrew Patzer All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN (pbk): 1-59059-020-1 Printed and bound in the United States of America 12345678910 Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. Technical Reviewer: David Czarnecki Editorial Directors: Dan Appleman, Peter Blackburn, Gary Cornell, Jason Gilmore, Karen Watterson, John Zukowski Managing Editor: Grace Wong Project Manager: Alexa Stuart Copy Editor: Kim Wimpsett Production Editor: Kari Brooks Compositor: Impressions Book and Journal Services, Inc. Indexer: Carol Burbo Cover Designer: Tom Debolski Marketing Manager: Stephanie Rodriguez Distributed to the book trade in the United States by Springer-Verlag New York, Inc., 175 Fifth Avenue, New York, NY, 10010 and outside the United States by Springer-Verlag GmbH & Co. KG, Tiergartenstr. 17, 69112 Heidelberg, Germany. In the United States, phone 1-800-SPRINGER, email <[email protected]>, or visit http://www.springer- ny.com. Outside the United States, fax +49 6221 345229, email <[email protected]>, or visit http://www.springer.de. For information on translations, please contact Apress directly at 2560 9th Street, Suite 219, Berkeley, CA 94710. Phone 510-549-5930, fax: 510-549-5939, email <[email protected]>, or visit http://www.apress.com. The information in this book is distributed on an "as is" basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. The source code for this book is available to readers at http://www.apress.com in the Downloads section. About the Author Andrew Patzer is a web architect for the Centare Group, a consulting firm located in the Midwest. His first book, Professional Java Server Programming (Wrox Press, 1999), is a best seller and one of the first books to cover J2EE technologies. Andrew recently served as a lead systems architect for a leading application service provider in the insurance industry, and he was 3 directly involved in designing and building a J2EE development framework upon which the company's key product was built. Andrew has delivered several presentations over the years to local user groups as well as national conferences. I'd like to dedicate this book to my wife, Beth, and our daughters, Ashley and Emily. Once again, they've been very supportive of me as I took on another book. I know it's been difficult at times to put up with me not being around because I had more writing to do. Thank you for your love and continued support. I'd like to give special thanks to both my mother and my mother-in-law. They've both had to deal with cancer this past year and continue to fight. I've learned a great deal personally from both of them about courage and strength. I pray they continue to enjoy life to its fullest each and every day. Acknowledgments I BELIEVE STRONGLY that a person can only go so far unless they surround themselves with good people. Over the years, I've had the pleasure of working with some outstanding people. I'd like to specifically mention a few that I worked with at Workscape (now Riverwood Solutions). Mike Schenk, Mike Connor, and Craig Wohlfeil are each extremely talented architects who not only taught me a great deal, but also pushed me to achieve more than I could have on my own. Dave Glyzewski, owner of the Centare Group, has always been a friend and has done his best to support me over the years as my career has taken me many different places. I'd like to thank Dave for being in my corner and always believing in me. Thanks, Smithers! John Carnell, my perpetual coworker, has been there to keep my competitive juices flowing. We always seem to push each other to new heights (although I can't seem to push you past that five-foot mark—sorry, I couldn't help myself). Seriously, thank you for being a friend, as well as competitor, throughout my career. I'd also like to thank my friend Scott Borth. Scott is the only person I've found who will laugh at my jokes and find humor in the same things I do. When your job has you sitting in front of a computer screen all day, it helps to talk to someone who not only allows you to be yourself, but actually encourages it. About the Technical Reviewer David Czarnecki is a computer scientist in the Advanced Computing Technologies lab at the GE Global Research Center in Niskayuna, New York. He's involved with various projects ranging from the development of application frameworks to the use of natural language processing techniques. He's the coauthor of Java Internationalization (O'Reilly, 2001), and he regularly provides expertise on how to properly internationalize software. David is also a speaker at national conferences such as JavaOne. 4 Introduction When I wrote my first book covering JavaServer Pages and Java Servlet technology, there was a great deal of uncharted territory to cover. Today, much of what I wrote is not only outdated, but completely obsolete. The technology has grown tremendously fast and, with it, a legion of Java developers eager to stay on the cutting edge of Java development. Although this is certainly a good thing, it does however create a problem. Quite often, in a rush to implement the latest technology, little thought is given to good design and architecture. This book attempts to provide a framework for developing quality software using JavaServer Pages technology. Chapters 1 and 2 lay the groundwork for using JSP. Chapters 3 and 4 explore the separation of roles between page designer and Java developer using both JavaBeans and custom tag extensions. Chapters 5, 6, 7, and 8 present several design patterns for the presentation tier. These patterns are applied using JavaServer Pages and Java Servlets. Chapters 9 and 10 walk through the basics of testing and deploying web applications using open-source tools. The book concludes with the development of an application framework along with a complete reference implementation in Chapters 11 and 12. I hope you enjoy this book as much as I've enjoyed writing it! 5 Chapter 1: JSP Foundations Overview Developers have seen great improvements in server-side web development in the past few years. We've gone from complex, non-scalable Common Gateway Interface (CGI) scripts to some elegant enterprise-class solutions using technologies such as Active Server Pages (ASP), Java Servlets, and JavaServer Pages (JSP). Unfortunately, with this explosion of new technology come a lot of misguided efforts by well-intentioned developers. It's easy to simply learn the skills you need to accomplish a specific task and then move on to something else. When you revisit that same task, you may learn a little bit more to make necessary modifications, but it's still not quite right. What eventually happens is that you end up with a system of "patchwork" that needs to be supported and maintained. Wouldn't it be nice to do things right up front and avoid creating this mess in the first place? This book's purpose is to educate those of you who may have developed several JSP applications but have never really thought about concepts such as role separation, frameworks, and enterprise development patterns. Having developed several server-side Java applications over the past few years, I'd like to share with you some of my ideas as well as some best practices that I've arrived at while working alongside some of the best and brightest developers around. This chapter will lay down the basics of developing a web application using JSP. It'll explain the fundamental concepts behind web development, J2EE (Java 2 Enterprise Edition) applications, and simple JSP development. If you're already a JSP expert, then you may still want to skim over the chapter. It'll include information helpful for setting up a particular JSP environment and laying the groundwork for the book's examples. Developing Web Applications It may seem a bit trivial to discuss the elements of a basic web application in an advanced JSP book, but I think it warrants attention when I see numerous people claiming to be web developers who know nothing about HyperText Transfer Protocol (HTTP) or even web servers. It reminds me of my client/server days, when I was surrounded by Visual Basic developers who had no understanding of the Windows operating system. They were certainly capable of producing a working application, but they could have done so much more had they understood the basic foundation upon which they were developing. Web developers, for the most part, tend to get caught up in their specific technology and then do exactly what they need to do to get their programs to work. Quite often, there just isn't any time to learn anything more about it. With aproper foundation, developers can make better decisions before diving into development. So, let's start this book by reviewing HTTP and how each component of a web application plays a part in the overall interaction with the user. Understanding HTTP HTTP defines the way in which web browsers interact with web servers. HTTP uses TCP/IP, the network protocol of the Internet, to communicate standard messages between machines across the Internet. By using standard protocols such as these, you're able to communicate with any web server from a variety of different web browsers and expect similar behavior. 6 At the heart of HTTP lies a request message and a response message. This is the fundamental way in which a web browser communicates with a web server (see Figure 1-1). The user types in the location of a document in the URL box, the browser issues a standard HTTP request for the document, and the document is located and returned to the browser as a standard HTTP response. Figure 1-1: Basic HTTP exchange The HTTP request consists of a series of standard headers along with any parameters, or form data, necessary to fulfill the request. The web server, for which the request is intended, is able to read these headers and respond accordingly. There are two common types of HTTP requests, GET and POST. A GET request will append form data to the requested URL and send it as one packet. A POST request will first send a packet containing header information and then send a separate packet containing the form data. A common question I'm asked is, "Which type of request should I use in certain situations?" A good rule of thumb is that you should use POST requests to modify a resource on the server and GET requests to simply retrieve information from the server. You may find that this doesn't always apply in every situation, though. The HTTP response consists of standard response headers such as content-type and content- length, along with an HTTP version number and an HTTP status code. In addition to the header, chunks of data are sent immediately following the response message. The browser uses the response headers to determine the best way to render the data and then displays it accordingly. Most of the time, the response consists of HTML content, along with a few images. Sometimes, however, the content-type may be something like application/pdf, which is known as a MIME type. The browser will match this against its own list of MIME types and determine which helper application to load. In this case, the Adobe Acrobat Reader would render the response data. Table 1-1 shows the log file of an HTTP tracer program that tracks every HTTP message sent between your browser and the Internet. You can see how the POST request issues two separate messages. What you can't see in this particular log is that the second message contains all of the form data (notice the size of the message). The response that is generated contains a header of HTTP/1.1 200. The first part (HTTP/1.1) is the version number. The last part is the status code (200, which means OK). This also contains any response headers such as content-type and content-length (not shown in this log). The remaining lines show how the browser receives the response data. The browser will take this data, along with its content-type and content-length, and render it appropriately for the user to view. Table 1-1: Example of a Single POST Request and Subsequent Response TYPE ID1 ID2 BYTES RESPONSE TIME DATA SEND 735 1 741 0.000 POST /marketplace/default.html SEND 735 2 1489 2.799 POST /marketplace/default.html RECEIVE 735 3 172 2.720 HTTP/1.1 200 7 Table 1-1: Example of a Single POST Request and Subsequent Response TYPE ID1 ID2 BYTES RESPONSE TIME DATA RECEIVE 735 4 2048 0.005 2048 bytes RECEIVE 735 5 7680 0.035 7680 bytes RECEIVE 735 6 512 0.002 512 bytes RECEIVE 735 7 2560 0.019 2560 bytes RECEIVE 735 8 63 0.018 63 bytes Components of a Web Application A typical web application involves a web server, an application server, and a database server. Each of these servers listens to a specific TCP/IP port for incoming messages containing requests to carry out. These listeners are sometimes called daemons. They're threads of execution that wait for TCP/IP messages to appear for a specific port. For instance, the web server will, by default, listen to requests addressed to port 80. Because web servers default to this port, there's no need to specify it in the URL, it's just implied. If you were to request http://www.apress.com, the request would be sent to port 80 of the machine on which the web server is running. To specify a different port, let's say port 7100, you would add it to the URL like this: http://www.apress.com:7100. Ports provide an easy way in which a company can limit access to its network resources. A network administrator can simply shut off outside access to all ports other than port 80. This ensures that the only way someone will get in is through the web server. Application servers listen on a port that is typically private to the outside world. The web server is configured to forward specific requests to that particular port. Database servers operate in a similar fashion. The database server may be listening on port 3306 for requests. The application server would then establish a database connection with that port. Figure 1-2 shows this chaining of servers through port mappings. It's important to note that each of these servers can be running on the same machine or multiple ones. If they're running on separate machines, then you would need to specify the machine name in front of the port name (machine_name:port). Figure 1-2: Web application architecture The typical flow of handling a request starts with the browser issuing arequest for a specific resource. The web server picks up this request off of port 80 and determines that the application server should handle the request. The application server receives the request and executes some code to handle the request. Within the code, the database may be called by 8 making a connection to whatever port to which the database server is listening. Once a response has been assembled, it's sent back to the browser from where it originated. Developing J2EE Web Applications You've seen how HTTP has made it possible for various web servers and web browsers to communicate with each other regardless of the underlying technologies. In a similar fashion, the J2EE specification has made it possible for applications to be deployed in a wide variety of environments with little or no modifications necessary. An application server that is said to be J2EE compliant can fulfill a "contract" between the application itself and the services the application server provides. Popular J2EE-compliant application servers are BEA WebLogic and IBM WebSphere. Some open-source options are Enhydra and JBoss. The J2EE specification defines the use of several services with which a typical enterprise application is concerned. These services include transaction management (JTA), naming services (JNDI), messaging (JMS, JavaMail), distributed object handling (RMI-IIOP), and database management (JDBC). In addition to these services, a J2EE-compliant application server provides both a web container and an Enterprise JavaBean (EJB) container (see Figure 1-3). Figure 1-3: J2EE architecture Understanding Web Containers A J2EE application server provides a standard container that can handle the execution of both Java Servlets and JSP, along with any services that may be needed by these components. This container is the web container because the components within it are responsible for page navigation and presentation. Java Servlets A few years ago, there were not many options for delivering dynamic content through the Web. Most people had to write Perl scripts to be used through CGI. Although this approach worked reasonably well, it was not very scalable (a new process is required to service each request). Sun introduced Java Servlets to provide a scalable solution that brought with it the many advantages of the Java platform. Servlets are nothing more than Java classes that implement the HttpServlet interface of the Java Servlet API. This interface defines a set of lifecycle methods that can be overridden to provide dynamic responses to HTTP requests. A J2EE-compliant application server provides an environment for servlets to reside and handle incoming requests. 9 TEAM FLY PRESENTS The web container can load and manage multiple servlets within the same Java Virtual Machine (JVM). Once a servlet is loaded, it handles each incoming request by spawning a new lightweight thread to perform its task. This enables the application server to service a great number of requests without significant degradation of performance. JavaServer Pages The biggest problem with servlets was that they required the Java developer to assemble the HTML-formatted output from within the Java code using a series of out.println() statements. This not only created some ugly code, but it also made it difficult to create a decent user interface. If you wanted to use a tool to visually design a page, you needed to copy the HTML into your Java code and wrap the out.println() method calls around each line. In short, there was no clear separation between the application code and the user interface. To change one, you invariably changed the other. JSP was introduced as a way to separate the content from the presentation of the content. A JSP page is typically an HTML page with special tags for including Java code. The page dynamically compiles into a servlet behind the scenes and executes as such. This makes it possible to write pure HTML (and use HTML tools) without regard to the Java code in the page. There are many ways to further separate content from presentation using both servlets and JSP pages. Chapters 3 and 4 discuss these techniques in depth. Understanding EJB Containers In addition to a web container, J2EE-compliant application servers provide an EJB container. The web container will typically communicate with the EJB container to access business logic contained within one or more EJBs. It's often through EJBs that the web container accesses enterprise resources such as databases, message queues, and distributed objects. EJB containers provide an environment to host EJBs as well as a set of system-level services such as transaction management and security. An EJB makes itself known to its container by publishing a home and remote interface. It's through these interfaces that client objects communicate with the EJB and invoke the business logic contained within them. Structure of a J2EE Application All J2EE-compliant applications must follow a specific deployment structure. This structure helps to minimize the differences in deploying an application to different application servers (in other words, WebLogic vs. WebSphere). The directory structure is as follows: app-name (.html & .jsp files, along with any subdirectories required by html) web-inf (web application deployment descriptor, web.xml) classes (application classes, servlets) lib (3rd-party jar files) tlds (Tag library descriptors) The web.xml file contains configuration information for the web container to use. For a complete description of this file, see the Java Servlet specification at http://java.sun.com/products/servlet/download.html. 10 TEAM FLY PRESENTS

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.