Tomcat can't find class that is placed directly under classes folder
I have the following JSP:
<%@ page import="foo.*" %>
<html>
<body>
The page count is:
<%=Counter.getCount()%>
</body>
</html>
I have a Counter
class in package fo开发者_Python百科o
which is stored in:
C:\apache-tomcat-6.0.32\webapps\God\WEB-INF\classes
And the container could find the class from its package foo
.
But when I try to add some other class file directly under \WEB-INF\classes
and not in any specific package such as foo
, then container can't find that class.
How is this caused and how can I solve it?
Classes in the default package are not visible to classes which are by itself inside a package. You must put the class in a package whenever you want to import it in another class which is by itself inside a package. Technically, when JSP files are compiled, the container will autogenerate a .class
file which is by itself inside a package. So you cannot import classes from the default package in the JSP.
So, whenever you want to be able to reuse a class anywhere, it has to be placed in a concrete package, not in the default package. As an exercise, create two classes yourself, one which is inside a package and other which is not inside a package. Now, inside the one with package, try to import
and use the one without package. You'll see that it's not possible and the code won't compile. The servletcontainer encounters exactly the same problem "under the hoods".
See also:
- The Java Tutorial - Lesson: Packages
Unrelated to the concrete problem: writing raw Java code in JSP files is a poor practice. Consider learning and using servlets.
精彩评论