JavaRanch Home    
 
This page:         last edited 28 November 2006         What's Changed?         Edit

Package Your Beans   

Even though the Java/JVM specifications have never allowed classes in the default package (classes with no stated package declaration) to be imported by classes in a specific package, compilers prior to Java 1.4.1 allowed this. Beginning with Java 1.4.1, Sun has tightened up the implementation of the JVM and compiler and no longer allows it. (The Sun bug report can be found here).

This has led to some confusion for developers of Servlets and JSP pages.

It has always been a good idea to package all of your classes for all but the most trivial of applications, and it's much easier to tell someone to package all of their servlet and bean classes (all of the time) than to try and explain this behavior. That is why most of the seasoned developers on JavaRanch will tell people to be sure that all of their classes are packaged before making any other debugging suggestions.

On occasion, someone will balk and tell us that we are wrong because they created an unpackaged servlet and it ran fine. But this only worked for them because their servlet was never imported by any other class, and was loaded by the container's custom class loader. It's not a generally accepted way to do things, but most containers seem to have the ability to load unpackaged classes (though this may lead to other problems down the road if you need to import the classes for any reason).

JSP pages, on the other hand, get compiled into servlet classes, and the beans used by the JSP (either with an import directive or with the < jsp:useBean > action) are referenced by import statements in the generated servlet source code. So while unpackaged servlets, listeners, and filters may be found by your container, unpackaged beans referenced from a JSP will not.

These nuances are too confusing to deal with when trying to debug something that's not working -- especially in code that someone else has written. To simplify everybody's lives, follow accepted best practices and eliminate any chance of this issue becoming a problem by packaging all of your java classes; always, right up front.

Many people on JavaRanch, including those most prone to answering questions, will quickly lose patience with someone who isn't willing to package all of their classes before trying to debug an issue (any issue), even if packaging doesn't seem to be related to their current problem.

The bottom line: package your classes. Always. It's just good practice, and it will eliminate one possible source of problems.


JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton