Java Pitfalls (Wiley, 2000) Book, Is As Follows: “A Pitfall Is Code That Compiles Fine but When Executed Produces Unintended and Some- Times Disastrous Results.”
Total Page:16
File Type:pdf, Size:1020Kb
Y L F M A E T Team-Fly® The WILEY Dear Valued Customer, advantage We realize you’re a busy professional with deadlines to hit. Whether your goal is to learn a new technology or solve a critical problem, we want to be there to lend you a hand. Our primary objective is to provide you with the insight and knowledge you need to stay atop the highly competitive and ever- changing technology industry. Wiley Publishing, Inc., offers books on a wide variety of technical categories, including security, data warehousing, software development tools, and networking — everything you need to reach your peak. Regardless of your level of expertise, the Wiley family of books has you covered. • For Dummies® – The fun and easy way® to learn • The Weekend Crash Course® –The fastest way to learn a new tool or technology • Visual™ – For those who prefer to learn a new topic visually • The Bible – The 100% comprehensive tutorial and reference • The Wiley Professional list – Practical and reliable resources for IT professionals The book you now hold, More Java™ Pitfalls: 50 New Time-Saving Solutions and Workarounds, shows experienced Java programmers how to avoid hidden pitfalls in the Java language and related J2EE™ technologies. The authors expose tricky problems even experienced Java developers encounter with EJBs, JSPs, servlets, and other core components of J2EE, and tackle more complex topics, including networking, XML and Java programming, and the Java Virtual Machine. This book is the result of thousands of hours of collective experience, both in Java programming and training. The result is a wealth of practical solutions to tough, real-world programming problems. Our commitment to you does not end at the last page of this book. We’d want to open a dialog with you to see what other solutions we can provide. Please be sure to visit us at www.wiley.com/compbooks to review our complete title list and explore the other resources we offer. If you have a comment, suggestion, or any other inquiry, please locate the “contact us” link at www.wiley.com. Finally, we encourage you to review the following page for a list of Wiley titles on related topics. Thank you for your support and we look forward to hearing from you and serving your needs again in the future. Sincerely, Richard K. Swadley Vice President & Executive Group Publisher Wiley Technology Publishing more information on related titles The Next Step in Java™ Programming Available from Wiley Publishing Helton/Java Security Marinescu/EJB Solutions Design Patterns 0764549286 0471208310 Real-world Advanced patterns, application of Java processes, and security technologies, idioms for EJB design including JAAS, JSSE, and development and Kerberos Rajagopalan/Java Servlet Programming INTERMEDIATE/ADVANCED Bible Broemmer/J2EE Best 0764548395 Practices Tap into the 0471228850 performance, Apply robust extensibility, and application design to security advantages your J2EE projects of servlets Available at your favorite bookseller or visit www.wiley.com/compbooks BEGINNER Wiley, For Dummies, The Fun and Easy Way, Weekend Crash Course, Visual and related trademarks, logos and trade dress are trademarks or registered trademarks of Wiley. Java and J2EE are trademarks of Sun Microsystems, Inc. All other trademarks are the property of their respective owners. More Java™ Pitfalls 50 New Time-Saving Solutions and Workarounds More Java™ Pitfalls 50 New Time-Saving Solutions and Workarounds Michael C. Daconta Kevin T. Smith Donald Avondolio W. Clay Richardson Publisher: Joe Wikert Executive Editor: Robert M. Elliott Assistant Developmental Editor: Emilie Herman Managing Editor: Micheline Frederick New Media Editor: Angela Denny Text Design & Composition: Wiley Composition Services This book is printed on acid-free paper. ∞ Copyright 2003 by Michael C. Daconta, Kevin T. Smith, Donald Avondolio, and W. Clay Richardson. All rights reserved. Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rose- wood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8700. Requests to the Pub- lisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, E-mail: [email protected]. Limit of Liability/Disclaimer of Warranty: While the publisher and author have used their best efforts in preparing this book, they make no representations or warranties with respect to the accuracy or completeness of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a particular purpose. No warranty may be created or extended by sales representatives or written sales materials. The advice and strategies contained herein may not be suitable for your situation. You should consult with a professional where appropriate. Neither the publisher nor author shall be liable for any loss of profit or any other commercial damages, including but not limited to special, inci- dental, consequential, or other damages. Wiley, the Wiley Publishing logo and related trade dress are trademarks or registered trade- marks of Wiley Publishing, Inc., in the United States and other countries, and may not be used without written permission. Java is a trademark or registered trademark of Sun Microsystems, Inc.. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. For general information on our other products and services please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Library of Congress Cataloging-in-Publication Data: ISBN: 0-471-23751-5 Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 This book is dedicated to the memory of Edsger W. Dijkstra who said, “I mean, if 10 years from now, when you are doing something quick and dirty, you suddenly visualize that I am looking over your shoulders and say to yourself, ‘Dijkstra would not have liked this’, well that would be enough immortality for me.” We humbly disagree: 10 years of Dijkstra is just not long enough; may he happily haunt our consciousness for 1010 years. Such an increase is more befitting his stature. Contents Introduction xi Acknowledgments xvii Part One The Client Tier 1 Item 1: When Runtime.exec() Won’t 4 Item 2: NIO Performance and Pitfalls 17 Canonical File Copy 20 Little-Endian Byte Operations 21 Non-Blocking Server IO 26 Item 3: I Prefer Not to Use Properties 34 Item 4: When Information Hiding Hides Too Much 39 Item 5: Avoiding Granularity Pitfalls In java.util.logging 44 Item 6: When Implementations of Standard APIs Collide 53 Item 7: My Assertions are Not Gratuitous! 59 How to Use Assertions 59 Item 8: The Wrong Way to Search a DOM 66 Item 9: The Saving-a-DOM Dilemma 73 Item 10: Mouse Button Portability 80 Item 11: Apache Ant and Lifecycle Management 88 Item 12: JUnit: Unit Testing Made Simple 100 vii viii Contents Item 13: The Failure to Execute 108 Deploying Java Applications 109 The Java Extension Mechanism 110 Sealed Packages 111 Security 112 Item 14: What Do You Collect? 112 Item 15: Avoiding Singleton Pitfalls 117 When Multiple Singletons in Your VM Happen 119 When Singletons are Used as Global Variables, or Become Non-Singletons 120 Item 16: When setSize() Won’t Work 122 Item 17: When Posting to a URL Won’t 126 Connecting via HTTP with the java.net Classes 126 An Alternative Open Source HTTP Client 137 Item 18: Effective String Tokenizing 140 Item 19: JLayered Pane Pitfalls 146 Item 20: When File.renameTo() Won’t 151 Item 21: Use Iteration over Enumeration 157 Item 22: J2ME Performance and Pitfalls 162 Part Two The Web Tier Y 199 L Item 23: Cache, It’s Money F 200 Item 24: JSP Design Errors 208 Request/ResponseM Paradigm 208 Maintaining State 209 JSP the AOld Way 210 JSPE Development with Beans (Model 1 Architecture) 214 TJSP Development in the Model 2 Architecture 220 Item 25: When Servlet HttpSessions Collide 220 Item 26: When Applets Go Bad 227 Item 27: Transactional LDAP—Don’t Make that Commitment 235 Item 28: Problems with Filters 244 Item 29: Some Direction about JSP Reuse and Content Delivery 255 Item 30: Form Validation Using Regular Expressions 261 Team-Fly® Contents ix Item 31: Instance Variables in Servlets 269 Item 32: Design Flaws with Creating Database Connections within Servlets 279 Item 33: Attempting to Use Both Output Mechanisms in Servlets 291 Item 34: The Mysterious File Protocol 297 Item 35: Reading Files from Servlets 302 Web Application Deployment Descriptors 308 Item 36: Too Many Submits 312 Preventing Multiple Submits 314 Handling Multiple Submits 316 Part Three The Enterprise Tier 327 Item 37: J2EE Architecture Considerations 329 Item 38: Design Strategies for Eliminating Network Bottleneck Pitfalls 335 A Scenario 336 General Design Considerations