ПУТЬ К КЛАССУ, Java Путь Buld (затмение) и СЕТЬ-INF\LIB: что использовать, когда, и почему?

Пока название папки не должно быть значимым, как насчет того, чтобы использовать GUID для них?

36
задан sangfroid 30 November 2009 в 18:35
поделиться

6 ответов

The CLASSPATH you set in your environment affects only standalone Java applications, i.e. ones you run from a command prompt or an icon. As you've noticed, Eclipse ignores this. It sets up its own per-project classpaths.

javac and java, if called from the command prompt, should/may honor this path, but it's no longer considered great practice to do this. It's turned out that every app needs its own set of stuff, so a global CLASSPATH isn't really doing any of them any good. Modern practice is to simply specify the classpath with the -cp option on the command line for javac or java.

A standalone Web Application server will also set up its own classpath. From the command line or GUI, WebAppServers are usually started by a script (.BAT or .sh) that sets up a classpath using -cp. Tomcat has a directory called common or common/lib where it expects to see libraries that should be available the the server and all programs running under it. But you will generally not need/want to mess with this, as it's customaries for applications to provide their own library collectons in WEB-INF/lib.

So for a Web app, you'd put your varous jars into the lib directory, under WEB-INF, assuming Eclipse pre-builds such a directory structure for you.

All the libs you need also need to be made known to Eclipse. In the Project Explorer, I select the whole slew of them at once, right-click and select Build Path | add to build path. That's easier than messing with Eclipse's project build path manually.

31
ответ дан 27 November 2019 в 06:01
поделиться

Java has a long history and experience has shown that some ideas were good and some were bad.

The CLASSPATH environment variable was the initial way to tell the Java machine where to locate classes from your program, and works reasonably well for command line programs. It was rapidly found that this should not be a global thing (as that tend to mess things up in the long run) but a per-program thing. This could be done by creating a wrapper script/BAT-file which sets the variable and runs the Java machine.

All was well, then people wanted to write web server stuff in Java. The Servlet API was created where a web application is a stand-alone unit - this resulted in that the CLASSPATH for each web application is the unpacked files under WEB-INF/classes plus the jar-files under WEB-INF/lib. And only that. This means the global CLASSPATH variable is ignored. This has been found to be a VERY good thing, so the concept has migrated elsewhere.

For instance a "executable jar" (which Eclipse calls a "runnable jar") which is invoked with "java -jar foobar.jar" contains the complete classpath INSIDE the Jar in a special manifest file. Java Web Start which is used to start java programs from a web server explicily lists the full classpath in the configuration file on the server.

But, to get you started. If you want to write a Java web application:

  1. Get the Eclipse Java EE version.
  2. Create a new Dynamic Web Project e.g. named foobar.
  3. Drag and drop (or copy/paste) the jar files you need in foobar/WebContent/WEB-INF/lib
  4. Create a new file named foobar/WebContent/index.jsp. In the blank file type

    Hello World <%= new java.util.Date() %>

  5. Right click in editor for index.jsp, choose Run -> Run on Server, and choose the Basic -> J2EE preview at localhost server, and Finish.

A browser window will now open, either in a browser or inside Eclipse which will render your JSP-page. You can change the JSP-page, save it with Ctrl-S and reload the browser window to see the changes.

11
ответ дан 27 November 2019 в 06:01
поделиться

Кроме того, я знаю, что WEB-INF \ LIB - это место, где вы можете размещать файлы JAR, которые будет использовать ваше веб-приложение. Однако я поместил JAR в WEB-INF \ LIB только для того, чтобы их игнорировать. В каких случаях следует помещать JAR-файлы в папку WEB-INF \ LIB? Как мне заставить Eclipse или веб-сервер заметить их?

Настоящая реальная проблема, которая у вас возникла, скорее всего, вы не заметили. t получил Eclipse для Java EE разработчиков и / или что вы только что создали общий Java-проект вместо динамического веб-проекта и построили самостоятельно создайте необходимую структуру папок.

Если вы создадите динамический веб-проект в Eclipse для разработчиков Java EE , то Eclipse автоматически добавит любые библиотеки в WEB-INF / lib в путь сборки . Путь сборки грубо называется просто путем к классам, который используется как во время компиляции, так и во время выполнения. Другими словами: просто поместите туда сторонние JAR-файлы, больше ничего делать не нужно.

Обратите внимание, что Java чувствительна к регистру, поэтому ее следует называть WEB-INF / lib , а не WEB-INF / LIB . Но в любом случае, если вы создаете динамический веб-проект , то Eclipse просто автоматически сгенерирует для вас правильную структуру папок / файлов.

Как говорили другие, игнорируйте переменную среды % CLASSPATH% . Это только , используемый javac.exe / java.exe, и даже тогда только , когда вы не укажете какой-либо из -cp , -classpath или - jar аргументы. В реальном мире эта переменная окружения используется редко, это просто удобство для начинающих (и, к сожалению, самое запутанное, они никогда не должны были его изобретать).

игнорируйте переменную среды % CLASSPATH% . Это только , используемый javac.exe / java.exe, и даже тогда только , когда вы не укажете какой-либо из -cp , -classpath или - jar аргументы. В реальном мире эта переменная окружения используется редко, это просто удобство для начинающих (и, к сожалению, самое запутанное, они никогда не должны были его изобретать).

игнорируйте переменную среды % CLASSPATH% . Это только , используемый javac.exe / java.exe, и даже тогда только , когда вы не укажете какой-либо из -cp , -classpath или - jar аргументы. В реальном мире эта переменная окружения используется редко, это просто удобство для начинающих (и, к сожалению, самое запутанное, они никогда не должны были его изобретать).

4
ответ дан 27 November 2019 в 06:01
поделиться

Если вы имеете дело с веб-приложениями, / WEB-INF / lib - это переносимое место для размещения JAR-файлов. Именно здесь веб-серверы контейнеры сервлетов ожидают найти файлы jar приложения.

3
ответ дан 27 November 2019 в 06:01
поделиться

Eclipse требует, чтобы вы указали путь к вашим библиотекам, файлам jar (на вкладке «Свойства» -> «Путь сборки Java» -> вкладка «Библиотеки»). Его можно найти в файле проекта .classpath.

Обычно у вас есть библиотеки JRE на его пути (который также будет в вашем пути к классам), поэтому добавление библиотек в путь к классам и обновление пути сборки eclipse будет работать.

Каталог WEB-INF должен быть местом, где содержится необходимая информация для вашего веб-приложения.

2
ответ дан 27 November 2019 в 06:01
поделиться

I'm not an Eclipse expert, but I think that your problem can be answered like this:

1) CLASSPATH is an environment variable that is read in when you launch java programs and is used by classloader to figure out where the classes are placed.

I would modify the CLASSPATH variable only in the case when you are launching an java program from a script, as this allows you to conveniently launch a program and make sure that the classes are found. This would not be the case for you, as you are developing the web application.

2) WEB-INF/lib is the directory under which the web application container's classloader (like tomcat or glassfish) looks into if your web application needs to resolve a class. So you put there the classes that are used in your web application.

Some IDE's do include the libraries/.jar files that you are using in a project automatically to the package.

3) Eclipse library/classpath resolving during the development time. I would assume, but apologies for assuming, as one really shouldn't do this ;), that you can define a library (add external .jar files to projects) and autocomplete/all the other interesting features should start working with this, as you basically make those classes visible for the IDE with that activity. I also would assume that you can then mark those libraries to be automatically added to the web projects etc., by the IDE.

In general a good reading about how classes are found during execution is here (it's a sun's official documentation). Also a good place to read about this is the ClassLoader class documentation.

2
ответ дан 27 November 2019 в 06:01
поделиться
Другие вопросы по тегам:

Похожие вопросы: