Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

java - 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 foo which is stored in:

C:apache-tomcat-6.0.32webappsGodWEB-INFclasses

And the container could find the class from its package foo.

But when I try to add some other class file directly under WEB-INFclasses 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


Unrelated to the concrete problem: writing raw Java code in JSP files is a poor practice. Consider learning and using servlets.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...