Apache Tomcat 6.0 объявлен стабильным


Apache Tomcat

Содержание

Apache Tomcat

Apache Tomcat — это контейнер, который позволяет вам использовать интернет приложения такие, как Java сервлеты и JSP (серверные страницы Java).

Пакеты Tomcat 6.0 в Ubuntu поддерживают два варианта запуска Tomcat. Вы можете установить его как классический одиночный экземпляр на всю систему, который будет запускаться при загрузке системы от имени непривилегированного пользователя tomcat6. Но вы можете развернуть частные экземпляры, которые будут запускаться с правами вашего собственного пользователя, и вам придется запускать и останавливать их самостоятельно. Второй вариант особенно полезен в контексте сервера разработки, где нескольким пользователям требуется тестировать их собственные частные экземпляры Tomcat.

Масштабная установка на всю систему

Для установки сервера Tomcat вам достаточно ввести следующую команду в терминале:

Это установит сервер Tomcat только с ROOT приложением, которое выдает минимальную страницу «It works» по умолчанию.

Настройка

Файл настроек Tomcat может быть найден в /etc/tomcat6. Здесь будут описаны только несколько общих элементов настройки; для более подробной информации обратитесь к документации по Tomcat 6.0.

Изменение портов по умолчанию

Изменение используемой JVM

По умолчанию Tomcat предпочитает использовать OpenJDK-6, затем пробует JVM от Sun (Oracle), а затем иные JVM. Если у вас установлено несколько JVM, вы можете определить какая из них будет использоваться, установив JAVA_HOME в /etc/default/tomcat6:

Определение пользователей и ролей

Пользователи, пароли и роли (группы) могут быть определены централизованно в секции Servlet. Для Tomcat 6.0 это настраивается в файле /etc/tomcat6/tomcat-users.xml:

Использование стандартных приложений Tomcat

Tomcat поставляется с приложениями, которые вы можете установить для документирования, администрирования или демонстрационных целей.

Документация Tomcat

Пакет tomcat6-docs содержит документацию Tomcat 6.0, упакованную в качестве интернет приложения, которое доступно по умолчанию по адресу http://yourserver:8080/docs. Вы можете его установить следующей командой в терминале:

Приложения администрирования Tomcat

Пакет tomcat6-admin содержит два приложения, которые могут быть использованы для администрирования сервера Tomcat через web интерфейс. Для их установки введите следующую команду в терминале:

Первое из них это приложение manager, которое по умолчанию доступно по адресу http://yourserver:8080/manager/html. Оно в первую очередь используется для получения статуса сервера и перезапуска web приложений.

Второе приложение — это host-manager, которое по умолчанию доступно вам по адресу http://yourserver:8080/host-manager/html. Оно может быть использовано для создания виртуальных хостов динамически.

По соображениям безопасности пользователь tomcat6 по умолчанию не может писать в каталог /etc/tomcat6. Некоторые возможности в этих приложениях администрирования (разработка приложений, создание виртуальных хостов) требуют права записи на этот каталог. Если вы хотите пользоваться этими возможностями, выполните следующее для предоставления группе tomcat6 необходимых прав:

Приложения примеров Tomcat

Пакет tomcat6-examples содержит два приложения, которые могут быть использованы для тестирования или демонстрации возможностей сервлетов и JSP, которые по умолчанию вы можете найти по адресу http://yourserver:8080/examples. Вы можете установить их следующей командой в терминале:

Использование пользовательских экземпляров

Tomcat в большей степени используется при разработке и тестировании, когда использование одиночной оболочки на сервере не удовлетворяет требованиям множества пользователей на одной системе. Пакеты Tomcat 6.0 в Ubuntu поставляются с инструментарием, помогающим создать ваши собственные настроенные на пользователя оболочки, позволяя каждому пользователю в системе запускать (без прав суперпользователя) отдельные частные экземпляры, при том, что они будут использовать библиотеки, установленные в системе.

Установка поддержки частных оболочек

Вы можете установить все необходимое для запуска частных оболочек вводом следующей команды в терминале:

Создание частного экземпляра

Вы можете создать каталог частной оболочки вводом следующей команды в терминале:

Это создаст новый каталог my-instance со всеми необходимыми подкаталогами и сценариями. Вы можете, например, установить свои общие библиотеки в подкаталог lib/ и развернуть свои приложения в подкаталоге webapps/. По умолчанию никакие приложения не разворачиваются.

Настройка вашего частного экземпляра

Вы обнаружите обычные файлы настроек Tomcat для вашего частного экземпляра в подкаталоге conf/. Вы конечно же можете отредактировать файл conf/server.xml для изменения портов по умолчанию, используемых вашим частным экземпляром Tomcat для предотвращения конфликтов с другими экземплярами, которые также могут быть запущены.

Запуск/остановка вашего частного экземпляра


Вы можете стартовать свой частный экземпляр, набрав следующую команду в терминале (подразумевается, что ваш экземпляр расположен в каталоге my-instance):

Вы можете остановить свой экземпляр, используя следующую команду в терминале (подразумевается, что ваш экземпляр все еще находится в каталоге my-instance):

Ссылки

Смотрите сайт Apache Tomcat для дополнительной информации.

Tomcat: The Definitive Guide — хороший ресурс для построения web приложений на Tomcat.

Для дополнительной литературы смотрите список на странице Tomcat Books.

Также загляните на страницу Ubuntu Wiki Apache Tomcat.

Apache Tomcat 6.0

Links

User Guide

Reference

Apache Tomcat Development

Apache Tomcat 6.0

Apache Portable Runtime (APR) based Native library for Tomcat

Tomcat can use the Apache Portable Runtime to provide superior scalability, performance, and better integration with native server technologies. The Apache Portable Runtime is a highly portable library that is at the heart of Apache HTTP Server 2.x. APR has many uses, including access to advanced IO functionality (such as sendfile, epoll and OpenSSL), OS level functionality (random number generation, system status, etc), and native process handling (shared memory, NT pipes and Unix sockets).

These features allows making Tomcat a general purpose webserver, will enable much better integration with other native web technologies, and overall make Java much more viable as a full fledged webserver platform rather than simply a backend focused technology.

APR support requires three main native components to be installed:

  • APR library
  • JNI wrappers for APR used by Tomcat (libtcnative)
  • OpenSSL libraries

Windows binaries are provided for tcnative-1, which is a statically compiled .dll which includes OpenSSL and APR. It can be downloaded from here as 32bit or AMD x86-64 binaries. In security conscious production environments, it is recommended to use separate shared dlls for OpenSSL, APR, and libtcnative-1, and update them as needed according to security bulletins. Windows OpenSSL binaries are linked from the Official OpenSSL website (see related/binaries).

Most Linux distributions will ship packages for APR and OpenSSL. The JNI wrapper (libtcnative) will then have to be compiled. It depends on APR, OpenSSL, and the Java headers.

Requirements:

  • APR 1.2+ development headers (libapr1-dev package)
  • OpenSSL 0.9.7+ development headers (libssl-dev package)
  • JNI headers from Java compatible JDK 1.4+
  • GNU development environment (gcc, make)

The wrapper library sources are located in the Tomcat binary bundle, in the bin/tomcat-native.tar.gz archive. Once the build environment is installed and the source archive is extracted, the wrapper library can be compiled using (from the folder containing the configure script):

Once the libraries are properly installed and available to Java (if loading fails, the library path will be displayed), the Tomcat connectors will automatically use APR. Configuration of the connectors is similar to the regular connectors, but have a few extra attributes which are used to configure APR components. Note that the defaults should be well tuned for most use cases, and additional tweaking shouldn’t be required.

When APR is enabled, the following features are also enabled in Tomcat:

  • Secure session ID generation by default on all platforms (platforms other than Linux required random number generation using a configured entropy)
  • OS level statistics on memory usage and CPU usage by the Tomcat process are displayed by the status servlet

Name of the SSLEngine to use. off: Do not use SSL, on: Use SSL but no specific ENGINE. The default value is on. This initializes the native SSL engine, then enable the use of this engine in the connector using the SSLEnabled attribute. Example:

See the Official OpenSSL website for more details on SSL hardware engines and manufacturers.

When APR is enabled, the HTTP connector will use sendfile for handling large static files (all such files will be sent asynchronously using high performance kernel level calls), and will use a socket poller for keepalive, increasing scalability of the server.

The following attributes are supported in the HTTP APR connector in addition to the ones supported in the regular HTTP connector:

The number of milliseconds this Connector will wait for another HTTP request before closing the connection. The default value is to use the value that has been set for the connectionTimeout attribute. This value also controls the timeout interval which is used for Comet connections.

Duration of a poll call. Lowering this value will slightly decrease latency of connections being kept alive in some cases, but will use more CPU as more poll calls are being made. The default value is 2000 (5ms).

Amount of sockets that the poller responsible for polling kept alive connections can hold at a given time. Extra connections will be closed right away. The default value is 8192, corresponding to 8192 keepalive connections.


Number of threads used to poll kept alive connections. On Windows the default is chosen so that the sockets managed by each thread is less than 1024. For Linux the default is 1. Changing the default on Windows is likely to have a negative performance impact.

Use kernel level sendfile for certain static files. The default value is true.

Amount of sockets that the poller responsible for sending static files asynchronously can hold at a given time. Extra connections will be closed right away without any data being sent (resulting in a zero length file on the client side). Note that in most cases, sendfile is a call that will return right away (being taken care of «synchronously» by the kernel), and the sendfile poller will not be used, so the amount of static files which can be sent concurrently is much larger than the specified amount. The default value is 1024.

Number of threads used service sendfile sockets. On Windows the default is chosen so that the sockets managed by each thread is less than 1024. For Linux the default is 1. Changing the default on Windows is likely to have a negative performance impact.

When APR is enabled, the HTTPS connector will use a socket poller for keepalive, increasing scalability of the server. It also uses OpenSSL, which may be more optimized than JSSE depending on the processor being used, and can be complemented with many commercial accelerator components. Unlike the HTTP connector, the HTTPS connector cannot use sendfile to optimize static file processing.

The HTTPS APR connector has the same basic attributes than the HTTP APR connector, but adds OpenSSL specific ones. For the full details on using OpenSSL, please refer to OpenSSL documentations and the many books available for it (see the Official OpenSSL website). The SSL specific attributes for the connector are:

Attribute Description
keepAliveTimeout
pollerSize
pollerThreadCount
useSendfile
sendfileSize
sendFileThreadCount

Enable SSL on the socket, default value is false. Set this value to true to enable SSL handshake/encryption/decryption in the APR connector.

Protocol which may be used for communicating with clients. The default is «all», with other acceptable values being «SSLv2», «SSLv3», «TLSv1», and «SSLv2+SSLv3».

Ciphers which may be used for communicating with clients. The default is «ALL», with other acceptable values being a list of ciphers, with «:» used as the delimiter (see OpenSSL documentation for the list of ciphers supported).

Name of the file that contains the server certificate. The format is PEM-encoded.

Name of the file that contains the server private key. The format is PEM-encoded. The default value is the value of «SSLCertificateFile» and in this case both certificate and private key have to be in this file (NOT RECOMMENDED).

Pass phrase for the encrypted private key. If «SSLPassword» is not provided, the callback function should prompt for the pass phrase.

Ask client for certificate. The default is «none», meaning the client will not have the opportunity to submit a certificate. Other acceptable values include «optional», «require» and «optionalNoCA».

Maximum verification depth for client certificates. The default is «10».

An example SSL Connector declaration can be:

When APR is enabled, the AJP connector will use a socket poller for keepalive, increasing scalability of the server. As AJP is designed around a pool of persistent (or almost persistent) connections, this will reduce significantly the amount of processing threads needed by Tomcat. Unlike the HTTP connector, the AJP connector cannot use sendfile to optimize static file processing.

The following attributes are supported in the AJP APR connector in addition to the ones supported in the regular AJP connector:

Attribute Description
SSLEnabled
SSLProtocol
SSLCipherSuite
SSLCertificateFile
SSLCertificateKeyFile
SSLPassword
SSLVerifyClient
SSLVerifyDepth
SSLCACertificateFile
SSLCACertificatePath
SSLCertificateChainFile
SSLCARevocationFile
SSLCARevocationPath

Duration of a poll call. Lowering this value will slightly decrease latency of connections being kept alive in some cases, but will use more CPU as more poll calls are being made. The default value is 2000 (5ms).


Amount of sockets that the poller responsible for polling kept alive connections can hold at a given time. Extra connections will be closed right away. The default value is 8192, corresponding to 8192 keepalive connections.

Ошибка развертывания на Apache Tomcat / 6.0.24

Я пытаюсь развернуть WAR на указанном сервере приложений Tomcat. Однако следующее это ошибка, я получаю, когда я пытаюсь использовать менеджер / муравей кота скрипт для развертывания.

WAR содержит пружинные бобы, HTML-страницы, JS, изображения, CSS и т.д. Мы в настоящее время развертывания проекта по справляясь распакованный проект непосредственно в папку WebApps на сервере Tomcat, который работает отлично. Тем не менее, мы хотели бы развернуть с помощью муравьиного сценария, разработанного для развертывания войны файла на удаленный кот.

Развитие было сделано на платформе окон, но сервер Tomcat находится на Linux (Oracle Enterprise Linux)

Отрывок, что делает развертывание следующим образом:

Любая помощь будет apprrciated. Если требуется больше информации, пожалуйста, дайте мне знать.

У меня была та же проблема с Tomcat 5.5.34. Я строй WAR с Ant и целевой WAR содержал следующую задачу:

Приставка вызвала запись баночки с именем «/» в пакете войны и поскольку Tomcat 5.5.26, что запись вызывает исключение при запуске контейнера Tomcat.

Изменение значения атрибута префикса команды войны, чтобы удалены все мои проблемы.

Apache Tomcat 6.0 объявлен стабильным

Установка и настройка Apache Tomcat в Windows

TomCat — контейнер сервлетов. Он может быть использован для приложений, написанных с помощью технологий Servlets, JSP и JSF, правда он не поддерживает другие Java EE технологии, такие как EJBs или JPA.

  • Загрузка Дистрибутивов
  • Настройка WebServer’a Apache Tomcat

————————————————————-

1) заходим на сайт java.sun.com или сразу на сайт oracle.com

2) Выбираем JDK последней стабильной версии

3) Выбираем платформу Windows, кликаем загрузить

4) Заходим на сайт tomcat.apache.org
Кликаем на download и выбираем последнюю стабильную версию сервера

5) 32 bit Windows zip

Получены дистрибутивы: apache-tomcat-6.0.26-windows-x86.zip и jdk-6u18-windows-i586.exe

Настройка WebServer’a Apache Tomcat

1) Выполнили установку по умолчанию jdk-6u18-windows-i586.exe

2) Настраиваем переменные окружения.

3) Environment Variables

4) В нижней части окна нажать на кнопку New (окно system variables)

5)
Variable Name: JAVA_HOME
Variable Value: C:\Program Files\Java\jdk1.6.0_18

6) Разархивируем файл apache-tomcat-6.0.26-windows-x86.zip в каталог C:\Program Files

Переходим в C:\Program Files\apache-tomcat\bin\

Выполняем команду statrup

8) В строке адреса набираем http://localhost:8080/ (таким образом проверяем, работает ли наш WebServer)

9) Устанавливаем 80 порт вместо 8080

Для этого в файле C:\Program Files\apache-tomcat\conf\server.xml

Меняем Connector port с 8080 на 80 и сохраняем файл.

10) Создаем файл StartApacheTomcat.bat

Attribute Description
pollTime
pollerSize
cd C:\Program Files\apache-tomcat\bin
startup

11) Запускаем файл. Ожидаем, что сервер запустится.


Apache Tomcat 6.0

Version 6.0.41, May 19 2014

Links

User Guide

Reference

Apache Tomcat Development

Apache Tomcat 6.0

JNDI Datasource HOW-TO

JNDI Datasource configuration is covered extensively in the JNDI-Resources-HOWTO. However, feedback from tomcat-user has shown that specifics for individual configurations can be rather tricky.

Here then are some example configurations that have been posted to tomcat-user for popular databases and some general tips for db usage.

You should be aware that since these notes are derived from configuration and/or feedback posted to tomcat-user YMMV :-). Please let us know if you have any other tested configurations that you feel may be of use to the wider audience, or if you feel we can improve this section in anyway.

Please note that JNDI resource configuration changed somewhat between Tomcat 5.0.x and Tomcat 5.5.x. You will most likely need to modify older JNDI resource configurations to match the syntax in the example below in order to make them work in Tomcat 6.x.x.

Also, please note that JNDI DataSource configuration in general, and this tutorial in particular, assumes that you have read and understood the Context and Host configuration references, including the section about Automatic Application Deployment in the latter reference.

java.sql.DriverManager supports the service provider mechanism. This feature is that all the available JDBC drivers that announce themselves by providing a META-INF/services/java.sql.Driver file are automatically discovered, loaded and registered, relieving you from the need to load the database driver explicitly before you create a JDBC connection. However, the implementation is fundamentally broken in all Java versions for a servlet container environment. The problem is that java.sql.DriverManager will scan for the drivers only once.

The JRE Memory Leak Prevention Listener that is included with Apache Tomcat solves this by triggering the drivers scan during Tomcat startup. This is enabled by default. It means that only libraries visible to the listener such as the ones in $CATALINA_BASE/lib will be scanned for database drivers. If you are considering disabling this feature, note that the scan would be triggered by the first web application that is using JDBC, leading to failures when this web application is reloaded and for other web applications that rely on this feature.

Thus, the web applications that have database drivers in their WEB-INF/lib directory cannot rely on the service provider mechanism and should register the drivers explicitly.

The list of drivers in java.sql.DriverManager is also a known source of memory leaks. Any Drivers registered by a web application must be deregistered when the web application stops. Tomcat will attempt to automatically discover and deregister any JDBC drivers loaded by the web application class loader when the web application stops. However, it is expected that applications do this for themselves via a ServletContextListener .

The default database connection pool implementation in Apache Tomcat relies on the libraries from the Apache Commons project. The following libraries are used:

These libraries are located in a single JAR at $CATALINA_HOME/lib/tomcat-dbcp.jar . However, only the classes needed for connection pooling have been included, and the packages have been renamed to avoid interfering with applications.

DBCP 1.3 provides support for JDBC 3.0.

See the DBCP documentation for a complete list of configuration parameters.

A database connection pool creates and manages a pool of connections to a database. Recycling and reusing already existing connections to a database is more efficient than opening a new connection.

There is one problem with connection pooling. A web application has to explicitly close ResultSet’s, Statement’s, and Connection’s. Failure of a web application to close these resources can result in them never being available again for reuse, a database connection pool «leak». This can eventually result in your web application database connections failing if there are no more available connections.

There is a solution to this problem. The Apache Commons DBCP can be configured to track and recover these abandoned database connections. Not only can it recover them, but also generate a stack trace for the code which opened these resources and never closed them.

To configure a DBCP DataSource so that abandoned database connections are removed and recycled add the following attribute to the Resource configuration for your DBCP DataSource:

When available database connections run low DBCP will recover and recycle any abandoned database connections it finds. The default is false .

Use the removeAbandonedTimeout attribute to set the number of seconds a database connection has been idle before it is considered abandoned.

The default timeout for removing abandoned connections is 300 seconds.

The logAbandoned attribute can be set to true if you want DBCP to log a stack trace of the code which abandoned the database connection resources.

The default is false .

0. Introduction

Versions of MySQL and JDBC drivers that have been reported to work:

  • MySQL 3.23.47, MySQL 3.23.47 using InnoDB,, MySQL 3.23.58, MySQL 4.0.1alpha
  • Connector/J 3.0.11-stable (the official JDBC Driver)
  • mm.mysql 2.0.14 (an old 3rd party JDBC Driver)

Before you proceed, don’t forget to copy the JDBC Driver’s jar into $CATALINA_HOME/lib .

1. MySQL configuration


Ensure that you follow these instructions as variations can cause problems.

Create a new test user, a new database and a single test table. Your MySQL user must have a password assigned. The driver will fail if you try to connect with an empty password.

Note: the above user should be removed once testing is complete!

Next insert some test data into the testdata table.

2. Context configuration

Configure the JNDI DataSource in Tomcat by adding a declaration for your resource to your Context.

3. web.xml configuration

Now create a WEB-INF/web.xml for this test application.

4. Test code

Now create a simple test.jsp page for use later.

That JSP page makes use of JSTL’s SQL and Core taglibs. You can get it from Apache Tomcat Taglibs — Standard Tag Library project — just make sure you get a 1.1.x release. Once you have JSTL, copy jstl.jar and standard.jar to your web app’s WEB-INF/lib directory.

Finally deploy your web app into $CATALINA_BASE/webapps either as a warfile called DBTest.war or into a sub-directory called DBTest

Once deployed, point a browser at http://localhost:8080/DBTest/test.jsp to view the fruits of your hard work.

0. Introduction

Oracle requires minimal changes from the MySQL configuration except for the usual gotchas 🙂

Drivers for older Oracle versions may be distributed as *.zip files rather than *.jar files. Tomcat will only use *.jar files installed in $CATALINA_HOME/lib . Therefore classes111.zip or classes12.zip will need to be renamed with a .jar extension. Since jarfiles are zipfiles, there is no need to unzip and jar these files — a simple rename will suffice.

For Oracle 9i onwards you should use oracle.jdbc.OracleDriver rather than oracle.jdbc.driver.OracleDriver as Oracle have stated that oracle.jdbc.driver.OracleDriver is deprecated and support for this driver class will be discontinued in the next major release.

1. Context configuration

In a similar manner to the mysql config above, you will need to define your Datasource in your Context. Here we define a Datasource called myoracle using the thin driver to connect as user scott, password tiger to the sid called mysid. (Note: with the thin driver this sid is not the same as the tnsname). The schema used will be the default schema for the user scott.

Use of the OCI driver should simply involve a changing thin to oci in the URL string.

2. web.xml configuration

You should ensure that you respect the element ordering defined by the DTD when you create you applications web.xml file.

3. Code example

You can use the same example application as above (asuming you create the required DB instance, tables etc.) replacing the Datasource code with something like

0. Introduction

PostgreSQL is configured in a similar manner to Oracle.

1. Required files

Copy the Postgres JDBC jar to $CATALINA_HOME/lib. As with Oracle, the jars need to be in this directory in order for DBCP’s Classloader to find them. This has to be done regardless of which configuration step you take next.

2. Resource configuration

You have two choices here: define a datasource that is shared across all Tomcat applications, or define a datasource specifically for one application.

2a. Shared resource configuration

Use this option if you wish to define a datasource that is shared across multiple Tomcat applications, or if you just prefer defining your datasource in this file.

This author has not had success here, although others have reported so. Clarification would be appreciated here.

2b. Application-specific resource configuration

Use this option if you wish to define a datasource specific to your application, not visible to other Tomcat applications. This method is less invasive to your Tomcat installation.


Create a resource definition for your Context. The Context element should look something like the following.

3. web.xml configuration

4. Accessing the datasource

When accessing the datasource programmatically, remember to prepend java:/comp/env to your JNDI lookup, as in the following snippet of code. Note also that «jdbc/postgres» can be replaced with any value you prefer, provided you change it in the above resource definition file as well.

These solutions either utilise a single connection to the database (not recommended for anything other than testing!) or some other pooling technology.

Whilst not strictly addressing the creation of a JNDI DataSource using the OCI client, these notes can be combined with the Oracle and DBCP solution above.

In order to use OCI driver, you should have an Oracle client installed. You should have installed Oracle8i(8.1.7) client from cd, and download the suitable JDBC/OCI driver(Oracle8i 8.1.7.1 JDBC/OCI Driver) from otn.oracle.com.

After renaming classes12.zip file to classes12.jar for Tomcat, copy it into $CATALINA_HOME/lib . You may also have to remove the javax.sql.* classes from this file depending upon the version of Tomcat and JDK you are using.

Ensure that you have the ocijdbc8.dll or .so in your $PATH or LD_LIBRARY_PATH (possibly in $ORAHOME\bin ) and also confirm that the native library can be loaded by a simple test program using System.loadLibrary(«ocijdbc8»);

You should next create a simple test servlet or jsp that has these critical lines:

where database is of the form host:port:SID Now if you try to access the URL of your test servlet/jsp and what you get is a ServletException with a root cause of java.lang.UnsatisfiedLinkError:get_env_handle .

First, the UnsatisfiedLinkError indicates that you have

  • a mismatch between your JDBC classes file and your Oracle client version. The giveaway here is the message stating that a needed library file cannot be found. For example, you may be using a classes12.zip file from Oracle Version 8.1.6 with a Version 8.1.5 Oracle client. The classeXXXs.zip file and Oracle client software versions must match.
  • A $PATH , LD_LIBRARY_PATH problem.
  • It has been reported that ignoring the driver you have downloded from otn and using the classes12.zip file from the directory $ORAHOME\jdbc\lib will also work.

Next you may experience the error ORA-06401 NETCMN: invalid driver designator

The Oracle documentation says : «Cause: The login (connect) string contains an invalid driver designator. Action: Correct the string and re-submit.» Change the database connect string (of the form host:port:SID ) with this one: (description=(address=(host=myhost)(protocol=tcp)(port=1521))(connect_data=(s >

Ed. Hmm, I don’t think this is really needed if you sort out your TNSNames — but I’m not an Oracle DBA 🙂

Here are some common problems encountered with a web application which uses a database and tips for how to solve them.

Tomcat runs within a JVM. The JVM periodically performs garbage collection (GC) to remove java objects which are no longer being used. When the JVM performs GC execution of code within Tomcat freezes. If the maximum time configured for establishment of a database connection is less than the amount of time garbage collection took you can get a database connection failure.

To collect data on how long garbage collection is taking add the -verbose:gc argument to your CATALINA_OPTS environment variable when starting Tomcat. When verbose gc is enabled your $CATALINA_BASE/logs/catalina.out log file will include data for every garbage collection including how long it took.

When your JVM is tuned correctly 99% of the time a GC will take less than one second. The remainder will only take a few seconds. Rarely, if ever should a GC take more than 10 seconds.

Make sure that the db connection timeout is set to 10-15 seconds. For the DBCP you set this using the parameter maxWait .

These can occur when one request gets a db connection from the connection pool and closes it twice. When using a connection pool, closing the connection just returns it to the pool for reuse by another request, it doesn’t close the connection. And Tomcat uses multiple threads to handle concurrent requests. Here is an example of the sequence of events which could cause this error in Tomcat:

Here is an example of properly written code to use a database connection obtained from a connection pool:

Please note that although the above instructions place the JNDI declarations in a Context element, it is possible and sometimes desirable to place these declarations in the GlobalNamingResources section of the server configuration file. A resource placed in the GlobalNamingResources section will be shared among the Contexts of the server.

In order to get Realms to work, the realm must refer to the datasource as defined in the or section, not a datasource as renamed using .

Apache Tomcat 7

Version 7.0.76, Oct 16 2020

Links

User Guide

Reference

Apache Tomcat Development

JNDI Datasource HOW-TO

JNDI Datasource configuration is covered extensively in the JNDI-Resources-HOWTO. However, feedback from tomcat-user has shown that specifics for individual configurations can be rather tricky.

Here then are some example configurations that have been posted to tomcat-user for popular databases and some general tips for db usage.

You should be aware that since these notes are derived from configuration and/or feedback posted to tomcat-user YMMV :-). Please let us know if you have any other tested configurations that you feel may be of use to the wider audience, or if you feel we can improve this section in anyway.

Please note that JNDI resource configuration changed somewhat between Tomcat 5.0.x and Tomcat 5.5.x. You will most likely need to modify older JNDI resource configurations to match the syntax in the example below in order to make them work in Tomcat 7.x.x.


Also, please note that JNDI DataSource configuration in general, and this tutorial in particular, assumes that you have read and understood the Context and Host configuration references, including the section about Automatic Application Deployment in the latter reference.

java.sql.DriverManager supports the service provider mechanism. This feature is that all the available JDBC drivers that announce themselves by providing a META-INF/services/java.sql.Driver file are automatically discovered, loaded and registered, relieving you from the need to load the database driver explicitly before you create a JDBC connection. However, the implementation is fundamentally broken in all Java versions for a servlet container environment. The problem is that java.sql.DriverManager will scan for the drivers only once.

The JRE Memory Leak Prevention Listener that is included with Apache Tomcat solves this by triggering the drivers scan during Tomcat startup. This is enabled by default. It means that only libraries visible to the listener such as the ones in $CATALINA_BASE/lib will be scanned for database drivers. If you are considering disabling this feature, note that the scan would be triggered by the first web application that is using JDBC, leading to failures when this web application is reloaded and for other web applications that rely on this feature.

Thus, the web applications that have database drivers in their WEB-INF/lib directory cannot rely on the service provider mechanism and should register the drivers explicitly.

The list of drivers in java.sql.DriverManager is also a known source of memory leaks. Any Drivers registered by a web application must be deregistered when the web application stops. Tomcat will attempt to automatically discover and deregister any JDBC drivers loaded by the web application class loader when the web application stops. However, it is expected that applications do this for themselves via a ServletContextListener .

The default database connection pool implementation in Apache Tomcat relies on the libraries from the Apache Commons project. The following libraries are used:

These libraries are located in a single JAR at $CATALINA_HOME/lib/tomcat-dbcp.jar . However, only the classes needed for connection pooling have been included, and the packages have been renamed to avoid interfering with applications.

DBCP 1.4 provides support for JDBC 4.0.

See the DBCP documentation for a complete list of configuration parameters.

A database connection pool creates and manages a pool of connections to a database. Recycling and reusing already existing connections to a database is more efficient than opening a new connection.

There is one problem with connection pooling. A web application has to explicitly close ResultSet’s, Statement’s, and Connection’s. Failure of a web application to close these resources can result in them never being available again for reuse, a database connection pool «leak». This can eventually result in your web application database connections failing if there are no more available connections.

There is a solution to this problem. The Apache Commons DBCP can be configured to track and recover these abandoned database connections. Not only can it recover them, but also generate a stack trace for the code which opened these resources and never closed them.

To configure a DBCP DataSource so that abandoned database connections are removed and recycled add the following attribute to the Resource configuration for your DBCP DataSource:

When available database connections run low DBCP will recover and recycle any abandoned database connections it finds. The default is false .

Use the removeAbandonedTimeout attribute to set the number of seconds a database connection has been idle before it is considered abandoned.

The default timeout for removing abandoned connections is 300 seconds.

The logAbandoned attribute can be set to true if you want DBCP to log a stack trace of the code which abandoned the database connection resources.

The default is false .

0. Introduction

Versions of MySQL and JDBC drivers that have been reported to work:

  • MySQL 3.23.47, MySQL 3.23.47 using InnoDB,, MySQL 3.23.58, MySQL 4.0.1alpha
  • Connector/J 3.0.11-stable (the official JDBC Driver)
  • mm.mysql 2.0.14 (an old 3rd party JDBC Driver)

Before you proceed, don’t forget to copy the JDBC Driver’s jar into $CATALINA_HOME/lib .

1. MySQL configuration

Ensure that you follow these instructions as variations can cause problems.

Create a new test user, a new database and a single test table. Your MySQL user must have a password assigned. The driver will fail if you try to connect with an empty password.

Note: the above user should be removed once testing is complete!

Next insert some test data into the testdata table.

2. Context configuration

Configure the JNDI DataSource in Tomcat by adding a declaration for your resource to your Context.

3. web.xml configuration

Now create a WEB-INF/web.xml for this test application.

4. Test code

Now create a simple test.jsp page for use later.

That JSP page makes use of JSTL’s SQL and Core taglibs. You can get it from Apache Tomcat Taglibs — Standard Tag Library project — just make sure you get a 1.1.x or later release. Once you have JSTL, copy jstl.jar and standard.jar to your web app’s WEB-INF/lib directory.

Finally deploy your web app into $CATALINA_BASE/webapps either as a warfile called DBTest.war or into a sub-directory called DBTest


Once deployed, point a browser at http://localhost:8080/DBTest/test.jsp to view the fruits of your hard work.

0. Introduction

Oracle requires minimal changes from the MySQL configuration except for the usual gotchas 🙂

Drivers for older Oracle versions may be distributed as *.zip files rather than *.jar files. Tomcat will only use *.jar files installed in $CATALINA_HOME/lib . Therefore classes111.zip or classes12.zip will need to be renamed with a .jar extension. Since jarfiles are zipfiles, there is no need to unzip and jar these files — a simple rename will suffice.

For Oracle 9i onwards you should use oracle.jdbc.OracleDriver rather than oracle.jdbc.driver.OracleDriver as Oracle have stated that oracle.jdbc.driver.OracleDriver is deprecated and support for this driver class will be discontinued in the next major release.

1. Context configuration

In a similar manner to the mysql config above, you will need to define your Datasource in your Context. Here we define a Datasource called myoracle using the thin driver to connect as user scott, password tiger to the sid called mysid. (Note: with the thin driver this sid is not the same as the tnsname). The schema used will be the default schema for the user scott.

Use of the OCI driver should simply involve a changing thin to oci in the URL string.

2. web.xml configuration

You should ensure that you respect the element ordering defined by the DTD when you create you applications web.xml file.

3. Code example

You can use the same example application as above (assuming you create the required DB instance, tables etc.) replacing the Datasource code with something like

0. Introduction

PostgreSQL is configured in a similar manner to Oracle.

1. Required files

Copy the Postgres JDBC jar to $CATALINA_HOME/lib. As with Oracle, the jars need to be in this directory in order for DBCP’s Classloader to find them. This has to be done regardless of which configuration step you take next.

2. Resource configuration

You have two choices here: define a datasource that is shared across all Tomcat applications, or define a datasource specifically for one application.

2a. Shared resource configuration

Use this option if you wish to define a datasource that is shared across multiple Tomcat applications, or if you just prefer defining your datasource in this file.

This author has not had success here, although others have reported so. Clarification would be appreciated here.

2b. Application-specific resource configuration

Use this option if you wish to define a datasource specific to your application, not visible to other Tomcat applications. This method is less invasive to your Tomcat installation.

Create a resource definition for your Context. The Context element should look something like the following.

3. web.xml configuration
4. Accessing the datasource

When accessing the datasource programmatically, remember to prepend java:/comp/env to your JNDI lookup, as in the following snippet of code. Note also that «jdbc/postgres» can be replaced with any value you prefer, provided you change it in the above resource definition file as well.

These solutions either utilise a single connection to the database (not recommended for anything other than testing!) or some other pooling technology.

Whilst not strictly addressing the creation of a JNDI DataSource using the OCI client, these notes can be combined with the Oracle and DBCP solution above.

In order to use OCI driver, you should have an Oracle client installed. You should have installed Oracle8i(8.1.7) client from cd, and download the suitable JDBC/OCI driver(Oracle8i 8.1.7.1 JDBC/OCI Driver) from otn.oracle.com.

After renaming classes12.zip file to classes12.jar for Tomcat, copy it into $CATALINA_HOME/lib . You may also have to remove the javax.sql.* classes from this file depending upon the version of Tomcat and JDK you are using.

Ensure that you have the ocijdbc8.dll or .so in your $PATH or LD_LIBRARY_PATH (possibly in $ORAHOME\bin ) and also confirm that the native library can be loaded by a simple test program using System.loadLibrary(«ocijdbc8»);

You should next create a simple test servlet or jsp that has these critical lines:

where database is of the form host:port:SID Now if you try to access the URL of your test servlet/jsp and what you get is a ServletException with a root cause of java.lang.UnsatisfiedLinkError:get_env_handle .

First, the UnsatisfiedLinkError indicates that you have

  • a mismatch between your JDBC classes file and your Oracle client version. The giveaway here is the message stating that a needed library file cannot be found. For example, you may be using a classes12.zip file from Oracle Version 8.1.6 with a Version 8.1.5 Oracle client. The classesXXX.zip file and Oracle client software versions must match.
  • A $PATH , LD_LIBRARY_PATH problem.
  • It has been reported that ignoring the driver you have downloaded from otn and using the classes12.zip file from the directory $ORAHOME\jdbc\lib will also work.


Next you may experience the error ORA-06401 NETCMN: invalid driver designator

The Oracle documentation says : «Cause: The login (connect) string contains an invalid driver designator. Action: Correct the string and re-submit.» Change the database connect string (of the form host:port:SID ) with this one: (description=(address=(host=myhost)(protocol=tcp)(port=1521))(connect_data=(s >

Ed. Hmm, I don’t think this is really needed if you sort out your TNSNames — but I’m not an Oracle DBA 🙂

Here are some common problems encountered with a web application which uses a database and tips for how to solve them.

Tomcat runs within a JVM. The JVM periodically performs garbage collection (GC) to remove java objects which are no longer being used. When the JVM performs GC execution of code within Tomcat freezes. If the maximum time configured for establishment of a database connection is less than the amount of time garbage collection took you can get a database connection failure.

To collect data on how long garbage collection is taking add the -verbose:gc argument to your CATALINA_OPTS environment variable when starting Tomcat. When verbose gc is enabled your $CATALINA_BASE/logs/catalina.out log file will include data for every garbage collection including how long it took.

When your JVM is tuned correctly 99% of the time a GC will take less than one second. The remainder will only take a few seconds. Rarely, if ever should a GC take more than 10 seconds.

Make sure that the db connection timeout is set to 10-15 seconds. For the DBCP you set this using the parameter maxWait .

These can occur when one request gets a db connection from the connection pool and closes it twice. When using a connection pool, closing the connection just returns it to the pool for reuse by another request, it doesn’t close the connection. And Tomcat uses multiple threads to handle concurrent requests. Here is an example of the sequence of events which could cause this error in Tomcat:

Here is an example of properly written code to use a database connection obtained from a connection pool:

Please note that although the above instructions place the JNDI declarations in a Context element, it is possible and sometimes desirable to place these declarations in the GlobalNamingResources section of the server configuration file. A resource placed in the GlobalNamingResources section will be shared among the Contexts of the server.

In order to get Realms to work, the realm must refer to the datasource as defined in the or section, not a datasource as renamed using .

Notice: This comments section collects your suggestions on improving documentation for Apache Tomcat.

If you have trouble and need help, read Find Help page and ask your question on the tomcat-users mailing list. Do not ask such questions here. This is not a Q&A section.

The Apache Comments System is explained here. Comments may be removed by our moderators if they are either implemented or considered invalid/off-topic.

Ошибка развертывания Apache Tomcat/6.0.24

Я пытаюсь развернуть WAR на упомянутом сервере приложений tomcat. Однако следующая ошибка, которую я получаю, когда пытаюсь использовать сценарий tomcat manager/ant для развертывания.

WAR содержит весенние бобы, HTML-страницы, js, изображения, css и т.д. В настоящее время мы развертываем проект, копируя распакованный проект непосредственно в папку webapps на сервере tomcat, который отлично работает. Однако мы хотели бы развернуть с использованием сценария ant, разработанного для развертывания военного файла на удаленном tomcat.

Разработка была выполнена на платформе Windows, но сервер tomcat находится на Linux (Oracle Enterprise Linux)

Сниппет, который выполняет развертывание следующим образом:

Любая помощь будет применена. Если потребуется больше информации, пожалуйста, дайте мне знать.

Ошибка развертывания на Apache Tomcat / 6.0.24

Я пытаюсь развернуть WAR на указанном сервере приложений Tomcat. Однако следующее это ошибка, я получаю, когда я пытаюсь использовать менеджер / муравей кота скрипт для развертывания.

WAR содержит пружинные бобы, HTML-страницы, JS, изображения, CSS и т.д. Мы в настоящее время развертывания проекта по справляясь распакованный проект непосредственно в папку WebApps на сервере Tomcat, который работает отлично. Тем не менее, мы хотели бы развернуть с помощью муравьиного сценария, разработанного для развертывания войны файла на удаленный кот.

Развитие было сделано на платформе окон, но сервер Tomcat находится на Linux (Oracle Enterprise Linux)

Отрывок, что делает развертывание следующим образом:

Любая помощь будет apprrciated. Если требуется больше информации, пожалуйста, дайте мне знать.

У меня была та же проблема с Tomcat 5.5.34. Я строй WAR с Ant и целевой WAR содержал следующую задачу:

Приставка вызвала запись баночки с именем «/» в пакете войны и поскольку Tomcat 5.5.26, что запись вызывает исключение при запуске контейнера Tomcat.

Изменение значения атрибута префикса команды войны, чтобы удалены все мои проблемы.

Установка Apache Tomcat на Windows, краткая инструкция

Небольшая выдержка из Википедии: Tomcat позволяет запускать веб-приложения, содержит ряд программ для самоконфигурирования.
Tomcat используется в качестве самостоятельного веб-сервера, в качестве сервера контента в сочетании с веб-сервером Apache HTTP Server, а также в качестве контейнера сервлетов в серверах приложений JBoss и GlassFish.

1. Необходимое программное обеспечение
1.1. Java, Apache Tomcat 7.0 работает с Java Standard Edition Runtime
Environment (JRE) версии 6.0 и старше.
Скачать JRE или JDK (если вы планируете использовать средства разработки, а не только java-машину) можно по ссылке: http://www.oracle.com/technetwork/java/javase/downloads/index.html
1.2. Tomcat, сам сервер можно скачать по ссылке: http://tomcat.apache.org/download-70.cgi.
Например, для 32-х битной windows это будет архив http://www.sai.msu.su/apache/tomcat/tomcat-7/v7.0.14/bin/apache-tomcat-7.0.14-windows-x86.zip

2. Установка Tomcat
2.1. JDK, ставим именно его для универсальности соглашаясь со всем подряд кроме локации, для удобства меняем на папку С:\jdk1.6.0.
2.1.2. Определяем переменную среды JAVA_HOME (JAVA_JRE в случае установки JRE) в Панель управления::Свойства системы::Дополнительно::Переменные среды::Системные переменные со значением папки размещения JDK из предыдущего пункта.
2.2. Tomcat, распаковываем архив с сервером в удобную папку, например, в С:\tomcat.

Служба Apache Tomcat 6.0 Tomcat6 неожиданно остановилась в Windows Server 2012

У нас есть приложение .Net, которое использует службы tomcat solr3.5 и развернуто на Windows Server 2012. Это 64-разрядная машина с 32 ГБ оперативной памяти, а Tomcat veriosn имеет 6 и устанавливается по адресу: «C: \ Program Files (x86) \ Apache Software Foundation \ Tomcat 6.0 «. Во время пиковой нагрузки solr-служба останавливается / не отвечает, и это происходит очень часто. Мы не нашли никаких ошибок в журнале событий Windows, но в журналах tomcat мы получили следующее исключение:

Мастер Йода рекомендует:  Зачем программисту блокчейн
Добавить комментарий