Classes not seeing each other in JSP

后端 未结 4 1508
醉话见心
醉话见心 2021-01-28 09:27

In a tomcat JSP application I have this directory layout:

webapps/
    myProjectName/
        index.jsp
        WEB-INF/
            classes/
                myp         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-28 09:44

    There are some other errors apart from not recognizing classes, but when it comes to your question:

    • do not add anything to classpath, it's irrelevant,
    • do not change any system settings, they are irrelevant,
    • do not worry about packaging just yet - you are still learning the basics,
    • do not use the javac line by Zeki, it won't work (*.java would only compile files in the classes/ directory, and you want to compile classes under mypackage).

    And most important of all: do not think it's hard or that it requires a complicated setup. It's really easy, and it's very important to get right once you start studying Java.

    When javac compiles a class and it finds that it uses some other class, it looks for it in two places, called classpath (for a compiled version) and sourcepath (for sources). Both of them, by default, include the current working directory. Note that it is not the same as the directory that contains the .java file.

    The exact location of .java or .class file inside the classpath always depends on the package (but you knew that already). In your case, if you do:

    cd WEB-INF/classes/mypackage
    javac class1.java
    

    your sourcepath is WEB-INF/classes/mypackage, the needed class is mypackage.class2, so, against intuition, javac will look for file WEB-INF/classes/mypackage/mypackage/class2.java. Such file does not exist, and you get an error.

    On the other hand, imagine:

    cd WEB-INF/classes
    javac mypackage/class1.java
    

    now your sourcepath is WEB-INF/classes, the needed class is mypackage.class2, javac will look for file WEB-INF/classes/mypackage/class2.java - and it will find it without problems.

    The moral: when you compile, always write javac in the top directory of your sources, above all the packages. This way your packages align with directories, as seen by javac, and the compilation is flawless.

    After you manage to exactly understand everything happening, by all means - switch to Netbeans (and, in a parallel thread, learn ant, then maven). It installs with it's own copy of tomcat 6, which you can use to develop your app; tomcat 7 is downwards compatible, so installing your app to it will be just the matter of copying war file (built by netbeans) to your tomcat 7 webapps.

提交回复
热议问题