Must beans be part of a package to be found?

I have bean class named User. It’s not in a named package so I try to use this bean in a JSP page like this:

   <jsp:useBean id="user" class="User" />

This doesn’t work. I get a message about class User not being found. Just to test, I replaced my class name with “java.util.Date”, and then the page was accepted.

Do I have to put the class in a package?

Answer:
JDK 1.4 update: In Sun’s JDK 1.4 compiler, you can no longer import any type from the unnamed package into a class in a named package. In other words, your beans really must be part of a package. For details, see Sun’s Bug Parade. The rest of this answer is valid for previous versions of Sun JDKs and possibly for other compilers such as Jikes.The reason the JSP container can not find your bean when it’s not part of a package has to do with how Java in general resolves references to classes references through their short name. I describe this in an article at the O’Reilly site:

http://java.oreilly.com/news/jsptips_1100.html

6. Using Packages for Bean Classes

When you develop a bean to be used in a JSP page, I recommend that you make it part of a named package. A Java class that does not use a package statement ends up in the so-called unnamed package. The servlet class generated from the JSP page is, however, typically assigned to a named package. If you try to refer to a class in the unnamed package from a class in a named package, Java cannot find the class unless you use an import statement to import it. In a JSP page that means you must use both a page directive to import the class, and the <jsp:useBean> action to make it available:

   <%@ page import="UserInfoBean" %>
   <jsp:useBean id="userInfo" class="UserInfoBean" />

If the bean is part of a named packed, the action is all you need:

   <jsp:useBean id="userInfo"
     class="com.mycompany.UserInfoBean" />

There are other tips in this article that you may find useful, so please read it when you get a chance.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>