在你开始前

了解对本教程的期望以及如何最大程度地利用本教程。

关于本教程

如果您正在学习本教程,则可能已经安装了现有的Apache Tomcat基本独立Web服务器。 如果没有,请首先阅读上一个教程“ 在UNIX中安装和配置开发Web服务器 ”。 然后,您可以返回本教程,以了解有关可用于配置服务器的高级功能和选项的更多信息,以及实现它们的详细步骤。

但是,如果您只是对可能从一种Web服务器环境普遍过渡到另一种Web服务器管理技术的某些技术感到好奇,则只想了解有关Tomcat产品本身的更多知识,或者想了解一些管理技巧,继续阅读。

目标

在本教程中,您将找到:

  • 介绍为什么需要为现有Web服务器配置其中一些高级设置,本教程针对的目标受众以及本教程提供的详细信息的摘要,包括开始本教程的先决条件。
  • 将基本Tomcat Web服务器的局限性与具有更高安全性,鲁棒性和可扩展性的局限性进行对比。
  • 在Tomcat中部署高级应用程序的概述。
  • 安全性考虑因素,包括针对Java™Security Manager和安全套接字层(SSL)等功能的Tomcat的逐步设置,安装和配置过程。
  • 来自Tomcat服务器的数据库和数据源连接。
  • Tomcat高级管理技巧。
  • 其他资源。

先决条件

本教程假定您已经安装了所选的基本UNIX®操作系统。 要运行本教程中的示例,您还必须安装并运行Tomcat版本6。

系统要求

您的服务器应至少有10GB的可用硬盘空间和至少512MB的RAM。 在开始之前,需要在UNIX服务器上安装以下附加工具:

  • Web浏览器:任何浏览器都可以。
  • Java 2,标准版运行时环境(JRE)发行版5.0或更高版本: Apache Tomcat版本6需要JRE。
  • Java安全套接字扩展(JSSE):该版本特定于您的操作系统,并且对于某些安全配置是必需的。 Java软件开发套件(JDK)版本5中包含JSSE。

你需要知道的

发现您需要了解的内容,以便为Tomcat环境做出正确的配置和自定义决策。

基本设置与高级设置

显然,安装Tomcat并启动并运行示例应用程序仅仅是开始。 您已经奠定了基础:现在,您必须释放这种简单,免费,有效的服务器软件的真正功能。 此外,您肯定希望保护服务器安全,并了解一些有关设置数据库以及在出现问题时进行故障排除的知识。

如果您完成了上一教程 ,则服务器已启动并正在运行。 但是即使在测试环境中,您也有局限性。 您必须设置测试服务器,使其与生产服务器相同。 在原始设置中,您花了最少的时间来启动和运行-安装和设置服务器软件环境,并实施Tomcat Web应用程序管理器控制台来部署Tomcat示例应用程序。 在本教程中,您将获得广泛的部署和安全信息以及管理技巧。

Tomcat在生产中

在本教程中,您可以自由尝试先进的中间件管理技术,以确保最高水平的正常运行时间和稳定性,而众所周知,在企业界这是重中之重! 在生产环境中,同一服务器上可能有多个应用程序可以通过不同的URL访问(虚拟主机),服务器场中可能有多个服务器,还有许多其他部署需求,当然至少要设置基本身份验证和SSL保护您的应用程序免受外界侵害。 但是,请不要担心:本教程的其余部分专用于使您能够设置服务器以提高效率,安全性和将来的可扩展性。

五个核心问题

首先,为要测试的应用程序计划需求。 无论此应用程序是高级“ Hello World”应用程序还是一些新开发的杰作,您都必须在开发级别了解您的需求,以及这些需求如何转化为必须在服务器级别设置的需求。 或者,也许您是一个管理员,不关心代码,只需要设置服务器即可。 也可以 无论您扮演什么角色,都需要回答以下问题:

  • 如何设置数据库访问,资源引用等以匹配应用程序的外部或内部依赖关系?
  • 在实施标准身份验证和其他安全措施时,如何保护Tomcat服务器?
  • 您如何成功部署应用程序?
  • 还有哪些其他管理和故障排除技巧可以确保持续成功?
  • 设置服务器以运行生产应用程序还有哪些其他技巧和资源?

这些问题将驱动本教程的其余部分。 您将获得有关如何实施回答上述问题所必需的实用解决方案的逐步说明,并将您的服务器和技能提高到一个新的水平。

应用部署

没有应用程序的应用程序服务器有什么好处?

先进的应用程序部署

在上一教程中 ,您学习了如何使用Tomcat Web应用程序管理器控制台安装简单的示例应用程序。 但是,尽管如此有趣,但这并不是您每天可能遇到的事情的非常真实的表示。 在这里,您将看到Tomcat如何与您的应用程序部署描述符一起工作,并严重依赖于上下文。 此外,您还将关注自动部署方法,这些方法使Tomcat可以完成大部分工作,而不必担心启动控制台和执行手动过程来部署应用程序。

在引入了Servlet 2.2版规范(参见相关主题 ),一个Web应用程序包括的servlet,超文本标记语言(HTML)页面,类以及其他可以捆绑和来自多个供应商的多个容器中运行的资源。 当然,您正在基于Java的服务器技术上部署Java应用程序:Tomcat不适用于与Microsoft®.NET相关的代码和部署。

WAR文件

您必须知道代码的打包方式,以便知道如何部署它。 当我说打包时,无论将目录结构的内容压缩成一个文件,都应该考虑压缩,存档。 在这种情况下,您将使用带有.war扩展名的Web存档(WAR)文件。

图1显示了如何打包Java应用程序的基本格式。

图1. Web模块的组件

目录

Web模块具有不变的特定结构。 程序集根目录/文档根目录(称为AppBase )包含JavaServer Pages™(JSP)代码页,客户端类和归档文件以及静态映像。 该目录包含一个名为/ WEB-INF /的子目录,该子目录又包含以下文件和目录:

  • web.xml:这是Web应用程序部署描述符,是部署画面的重要组成部分。 这也是特定于应用程序的安全性和基于角色的定义所在的位置。
  • lib:这是库存档文件夹。 它包含由服务器端类调用的库的Java Archive(JAR)文件。
  • classes:此目录包含服务器端类-servlet,JavaBean组件等。
  • 标签:此目录包含Web模块的标签文件,这些文件是标签库的实现。

语境

了解Tomcat中的上下文是继续实际安装应用程序的关键先决条件。 创建Web应用程序目录结构后,必须为Tomcat添加一个上下文,以便知道该应用程序已存在。

上下文定义了servlet容器用于与Web应用程序通信的方法集。 Java 2平台企业版(J2EE)标准在/WEB-INF/web.xml文件中提供了一组标准元素,以引用必须在特定于应用程序服务器的配置中定义的资源。 对于Tomcat版本6,这些InitialContext特定Web应用程序条目是在<Context>元素中配置的,可以在$ CATALINA_HOME / conf / server.xml或特定的Web应用程序上下文可扩展标记语言(XML)文件(META- INF / context.xml)。 最好不要像过去那样在server.xml文件中定义这些上下文。 相反,最好通过创建和编辑context.xml文件将它们分开。

上下文描述符只是一个XML文件,其中包含与上下文相关的Tomcat相关配置。 InitialContext被配置为最初部署的Web应用程序,并且可供Web应用程序组件使用(用于只读访问)。

上下文描述符的位置通常为:

  • $ CATALINA_HOME / conf / 引擎名称 / 主机名 /context.xml(例如,$ CATALINA_HOME / conf / Catalina / localhost / myApp.xml)
  • $ CATALINA_HOME / webapps / myApp / META-INF / context.xml
快速提示

如果未为上下文提供上下文描述符,则Tomcat使用默认值配置上下文。 您可以通过编辑$ CATALINA_HOME / conf / context.xml文件来明确定义要在webapps目录下使用的所有应用程序的元素。

清单1提供了特定于应用程序的上下文的基本示例。

清单1.特定于应用程序的上下文的示例
<Context docBase="myApp" debug="1" reloadable="true">
<Logger className=""
prefix="localhost_myApp" suffix=".log"
timestamp="false"/><Resource name="jdbc/myApp" auth="Container"
type="javax.sql.DataSource"/><ResourceParams name="jdbc/myApp"><parameter><name>driverClassName</name><value>sun.jdbc.odbc.JDriver</value></parameter><paramete><name>url<name><value>jdbc:odbc:myApp</value></parameter></ResourceParams>
</Contex>

此清单中的docBase和所有数据库驱动程序信息对于您的应用程序而言是唯一的。 请记住,除非您在server.xml文件中编辑上下文,否则不建议在上下文下使用path=""变量(不建议这样做)。

此代码使用Java命名和目录接口(JNDI)并引用您的数据源驱动程序和类名称,这两个详细信息将在Databases部分中进行描述。 请参阅相关主题 ,了解有关内资源定义更多的选择<Context>标签。

自动部署

在自动部署方法的整个说明中,将引用主机服务器(默认情况下为localhost )和appBase属性(默认的appBase目录为$ CATALINA_HOME / webapps)。

启动时部署

在启动时进行部署仅表示通过复制$ CATALINA_HOME / appbase目录下的内容(采用WAR文件格式或已扩展格式)来手动部署静态内容,然后停止或启动Tomcat服务器。 要利用“启动时部署”功能,您只需编辑主机即可将deployOnStartup属性设置为True,如清单2所示。

清单2. deployOnStartup.xml
<Engine name="Catalina" defaultHost="localhost" debug="0"><!-- This host is the default host. --><Host name="localhost" debug="0" appBase="webapps"unpackWARs="true" autoDeploy="true" deployOnStartup="true"><Context path="" docBase="ROOT" debug="0"/></Context></Host>

如果满足以下条件之一,则启动启动部署:

  • $ CATALINA_HOME / conf / engine_name / host_name目录中的XML文件中有新的或更新的上下文描述符。
  • appBase目录下有一个新的扩展应用程序。 在这种情况下,Tomcat将在appBase目录中检查关联的WAR文件,该文件的名称与扩展的Web应用程序的名称相同。 然后,删除扩展的目录,并从WAR重新部署Web应用程序(假设在主机上下文中为unpackWars=true )。
  • appBase目录中存在任何新的WAR文件。

除了能够在启动时进行部署之外,Tomcat还可以请求将新的XML配置文件,WAR文件或子目录放入appBase目录(对于XML配置文件,则为$ CATALINA_HOME / conf / engine_name / host_name )。在Tomcat运行时会自动进行部署。 您可以通过在上下文文件中设置autoDeploy="true"来配置此行为。

运行时部署

要在Tomcat中启用此有用的功能,请将autoDeploy标记设置为True,如清单3所示。

清单3. autoDeploy xml
<Engine name="Catalina" defaultHost="localhost" debug="0"><!-- This host is the default host. --><Host name="localhost" debug="0" appBase="webapps"unpackWARs="true" autoDeploy="true" deployOnStartup="true"><Context path="" docBase="ROOT" debug="0"/></Context></Host>

自动部署程序还将跟踪Web应用程序的以下更改:

  • 更新WEB-INF / web.xml文件会触发Web应用程序的重新加载。
  • 将更新的WAR文件放在先前扩展的appBase目录中,将触发“取消部署”(删除扩展的Web应用程序),然后进行部署。
  • 更新XML配置文件会触发“取消部署”(不删除任何扩展目录),然后部署关联的Web应用程序。

使用自动部署时,由XML上下文文件定义的docBase应该在appBase目录之外。 如果不是这种情况,则在部署Web应用程序时可能会遇到困难,或者该应用程序可能会部署两次。

关于在Tomcat中部署应用程序的最终想法

如果要明确定义上下文,则可能应该关闭自动应用程序部署。 否则,您的上下文将每次部署两次,这可能会导致应用程序出现问题。

另外,有时最好使用Tomcat在复制和扩展WAR之前删除所有旧目录。 否则,它将覆盖某些内容,同时保留旧代码,而不是按预期重新安装所有代码。 上面的server.xml文件中的设置应该可以缓解此问题,但是最好不要冒险。 如果您的应用程序运行异常,请考虑查看重新部署它的方式。 每当您安装新的东西时,这还需要重新启动Tomcat,但这很麻烦。

Tomcat Web应用程序管理器

Tomcat Web应用程序管理器是Tomcat的一部分,您已在上一教程中安装了它,它具有有趣的功能。 它允许您通过安装在上下文路径/ manager中的应用程序(例如, http:// localhost:8080 / manager )部署和管理Web应用程序。 它允许您在本地或远程使用基于超文本传输​​协议(HTTP)的URL命令,应用程序图形用户界面(GUI)或什至由Apache Ant命令通过以下方式部署,启动和停止,列出操作系统设置,等等。蚂蚁构建脚本。

要使用自动部署的功能,必须在tomcat-users.xml文件(Tomcat Web Application Manager应用程序的默认XML文件)中设置Tomcat Web Application Manager用户。 如果尚未设置应用程序,请立即进行。 然后,使用角色管理器添加用户和密码,然后重新启动Tomcat。

注意:如果要浏览GUI功能,请转至Tomcat Web应用程序管理器URL,或单击左上方导航栏中的“ Tomcat管理器”链接。

所有基于统一资源标识符(URI)的管理器命令都在单个请求URI中指定,如下所示:

http://{host}:{port}/manager/{command}?{parameters}

有用的URL命令

Tomcat Web应用程序管理器提供了几个URL命令,可用于部署和重新部署应用程序:

  • 使用URI部署使用URI部署应用程序,请在Web浏览器的地址栏中键入以下URL:

    http://localhost:8080/manager/deploy?path=/sample&war=file:$CATALINA_HOME/webapps/docs/appdev/sample/sample.war

    如果成功,您应该看到类似以下消息:

    OK - Deployed application at context path /sample

    为了确保您可能要访问http:// localhost:8080 / sample /。

  • 重新加载当前应用程序:要重新加载当前应用程序,请在Web浏览器的地址栏中键入以下URL:
    http://localhost:8080/manager/reload?path=/sample

    该URL向现有应用程序发出信号以使其自行关闭并重新加载。 当Web应用程序上下文不可重载并且您在/ WEB-INF / classes目录中有更新的类或属性文件时,或者在/ WEB-INF / lib目录中添加或更新了JAR文件时,此URL命令很有用。 但是,对web.xml文件所做的任何更改都需要重新启动应用程序。

    如果命令成功执行,您应该会看到类似以下内容:

    OK - Reloaded application at context path /sample
  • 列出操作系统和Java虚拟机(JVM)属性:要列出操作系统和JVM属性,请在Web浏览器的地址栏中键入以下URL:
    http://localhost:8080/manager/serverinfo

    如果命令成功执行,您应该会看到类似以下内容:

    OK - Server info
    Tomcat Version: Apache Tomcat/6.0.16
    OS Name: SunOS
    OS Version: 5.10
    OS Architecture: x86
    JVM Version: 1.5.0_12-b04
    JVM Vendor: Sun Microsystems Inc.
  • 启动,停止或取消部署应用程序:您只需在URL路径中键入以下值即可启动,停止或“取消部署”应用程序:
    http://localhost:8080/manager/start?path=/sample
    http://localhost:8080/manager/stop?path=/sample
    http://localhost:8080/manager/undeploy?path=/sample
  • 列出当前部署的应用程序:要列出当前部署的应用程序,请在Web浏览器的地址栏中键入以下URL:
    http://localhost:8080/manager/list

    如果命令成功执行,您应该会看到类似以下内容:

    OK - Listed applications for virtual host localhost
    /examples:running:0:examples
    /host-manager:running:0:host-manager
    /sample:running:0:sample
    /docs:running:0:docs
    /manager:running:0:manager
    /:running:0:ROOT

在扩展的Tomcat工具箱中还可以使用其他几个部署工具。 许多开发人员和管理员专门使用Ant,并且由于其可定制的构建脚本和易于执行的命令,因此通常比Tomcat Web Application Manager URL管理更喜欢它。

其他部署工具

本节讨论了Ant和Tomcat Client Deployer(TCD)。 两者都值得进一步探索,因此请参阅参考资料了解更多信息。

蚂蚁

在使用Ant之前,请执行以下步骤:

  1. 下载并安装Ant版本1.4或更高版本的二进制发行版。

    安装位置在$ ANT_HOME目录下,该目录位于您选择安装的位置(例如,在/ opt或/ export / home下)。 最好使该路径与您安装Tomcat服务器的位置相似。

  2. 从Tomcat 6安装中将文件server / lib / catalina-ant.jar复制到$ ANT_HOME / lib中。
  3. 将$ ANT_HOME / bin目录添加到PATH环境变量中,这样就不必每次都键入完整路径。 为此,请键入:
    PATH=$ANT_HOME/bin; export PATH

Ant与用于构建和编译Java应用程序的make实用程序相似。 但是,Ant更强大,更受欢迎。 它可以编译Java源代码文件,复制类文件和打包WAR文件。

为了使Ant能够从命令行访问部署应用程序,它必须具有具有管理员角色访问权限的用户名和密码。 您可以在Tomcat Web应用程序管理器中使用相同的用户名和密码(请参阅本教程前面的Tomcat Web应用程序管理器 ),并在build.xml文件中以清单4所示的XML格式进行配置。 build.xml文件将是您为Ant定制的主文件。

清单4.示例build.xml文件
<project name="My Application" default="compile" basedir="."><!-- Configure the directory into which the Web application is built. --><property name="build"    value="${basedir}/build"/><!-- Configure the context path for this application. --><property name="path"     value="/myapp"/><!-- Configure properties to access the Manager application. --><property name="url"     value="http://localhost:8080/manager"/><property name="username" value="myusername"/><property name="password" value="mypassword"/><!-- Configure the custom Ant tasks for the Manager application -><taskdef name="deploy"    classname="org.apache.catalina.ant.DeployTask"/><taskdef name="list"      classname="org.apache.catalina.ant.ListTask"/><taskdef name="reload"    classname="org.apache.catalina.ant.ReloadTask"/><taskdef name="resources" classname="org.apache.catalina.ant.ResourcesTask"/><taskdef name="roles"     classname="org.apache.catalina.ant.RolesTask"/><taskdef name="start"     classname="org.apache.catalina.ant.StartTask"/><taskdef name="stop"      classname="org.apache.catalina.ant.StopTask"/><taskdef name="undeploy"  classname="org.apache.catalina.ant.UndeployTask"/><!-- Executable Targets --><target name="compile" description="Compile web application"><!-- ... construct web application in ${build} subdirectory, andgenerated a ${path}.war ... --></target><target name="deploy" description="Install web application"depends="compile"><deploy url="${url}" username="${username}" password="${password}"path="${path}" war="file:${build}${path}.war"/></target><target name="reload" description="Reload web application"depends="compile"><reload  url="${url}" username="${username}" password="${password}"path="${path}"/></target><target name="undeploy" description="Remove web application"><undeploy url="${url}" username="${username}" password="${password}"path="${path}"/></target></project>

此清单中的taskdef命令是您在执行Ant时使用的命令。 要运行Ant命令,只需键入ant startant deployant undeploy等。 显然,您需要使用与为Tomcat Web应用程序管理器插入的值相似的值来对所有$变量进行硬编码,但是这样做为常见的部署和管理任务提供了很好的捷径。

注意:您可以在主ANT_HOME路径中创建build.xml文件。 如果尝试在没有build.xml文件的情况下或在Ant无法看到的位置的build.xml文件中执行Ant命令,则会出现以下错误:

Buildfile: build.xml does not exist!Build failed

当使用build.xml文件运行Ant时,它将编译/ src目录中存在的Java文件,并将已编译的类文件放置在build / src目录中。

Tomcat客户端部署程序

TCD是用于验证,编译,压缩为WAR并将Web应用程序部署到Tomcat服务器的第三方工具。 运行此工具的先决条件是按照上面Ant部分中的说明下载并正确安装Ant 。 有关此工具的更多信息,请参见参考资料 。

数据库连接

您知道数据库是任何动态Web应用程序的重要组成部分,它将存储,共享或访问通过会话,表单等接收的任何类型的数据。 使用基本和高级数据仓库,每个客户的Web特质,购物和浏览模式都越来越关注Web自定义。 Web与基于社交,社区或基于Wiki的站点上的用户之间的简单公共交互,是在甚至很小的基本站点中都需要一个或多个数据库的另一个原因。

面向服务的体系结构(SOA)越来越多地基于业务流程建模(BPM)以及特定的客户端和数据统计信息来驱动信息技术(IT)系统。 唯一的方法就是拥有存储和检索数据的方法。 本节说明如何将Tomcat连接到数据库。

资料库

数据库的最低要求是服务器上安装的数据库软件本身(例如Oracle,IBM®DB2®或MySQL)。 在将应用程序连接到Tomcat中的该数据库之前,还必须有一个用户和至少一个测试表。

您还需要安装Java数据库连接(JDBC)驱动程序。 该驱动程序是管理数据库调用和连接池所必需的,以最大程度地提高效率和灵活性,以独立于代码的方式管理数据库连接。

安装驱动程序

与数据库一样,驱动程序也取决于软件。 对于Oracle以及可能的DB2,还需要安装客户机。 无论使用哪种驱动程序,都必须将JAR文件复制到CATALINA_HOME / lib。 我发现这样做的一个有用提示是将驱动程序下载文件的扩展名从.zip重命名为.jar。 除了重命名,您无需执行任何其他操作,因为.zip和.jar文件是相同的。

JDBC

JDBC应用程序接口(API)是Java编程语言与各种数据库之间独立于数据库的连接的行业标准。

JDBC API使得可以做三件事:

  • 与数据库建立连接或访问任何表格数据源。
  • 发送结构化查询语言(SQL)语句。
  • 处理结果。

DBCP

数据库连接池(DBCP)仍然是标准的Tomcat连接池代理。 commons-dbcp软件包依赖commons-pool软件包中的代码来提供其使用的基础对象池机制。 这些库位于$ CATALINA_HOME / lib / tomcat-dbcp.jar中的单个JAR中。 应用程序可以直接使用commons-dbcp组件,也可以通过其容器框架的现有接口使用。

注意:在Tomcat的较早版本中,必须将数据库驱动程序的JDBC JAR放在$ CATALINA_HOME / common / lib目录中。 否则,Tomcat将无法加载JDBC驱动程序。 如果Tomcat看到您的驱动程序有问题,请将文件复制到CATALINA_HOME / common / lib。

创建数据库并安装驱动程序后,请执行以下步骤:

  1. 在Tomcat的server.xml文件中创建或映射初始上下文。

    这样做在server.xml文件中定义了资源,以确保基本的Tomcat安装以及Web应用程序都可以看到您的驱动程序。 这与在Tomcat中手动创建数据源以查找,连接和管理这些连接相同。

  2. 在应用程序的web.xml文件中创建资源引用,或使其在server.xml文件中共享。
  3. 要利用代码中新定义的JNDI名称,请使用javax.naming.Context.lookup()方法来查找数据源并获得数据库连接。

完成这三个简单步骤后,即可测试您的应用程序。

创建初始上下文

初始上下文只是使用JNDI引用server.xml文件中<Context>标记中定义的资源定义,以引用已定义的资源。 您需要进一步了解JNDI,因为它是J2EE的基础元素,并且是Java平台的扩展。

JNDI是一种目录和命名服务,用于使用公共API访问不同的(可能是多个)命名和目录服务。 对于GUI和创建资源引用的手动过程,您都需要表1中概述的信息。

日本国家发展研究院

JNDI提供了用于定位用户,机器,网络,对象和服务的标准接口。 命名服务使您可以存储各种类型的对象,并将名称关联或绑定到这些对象。 它还提供了一种基于名称搜索或查找对象的功能。

通常,执行以下步骤来查找对象:

  1. 获取初始上下文。
  2. 使用JNDI名称查找对象。
表1.创建数据源资源定义的前提条件
名称 描述
JNDI名称 数据源的JNDI查找名称
资料来源网址 数据源的特定JDBC参考URL
JDBC驱动程序类 查找并在此输入您的JDBC驱动程序类(请参阅相关主题以获取更多信息。)
用户名 数据库模式用户名
密码 您为数据库用户名设置的密码

创建资源定义/数据源

如果要拉起Tomcat Web Administration Manager控制台并在GUI中创建数据源,则手动创建资源引用实际上就是您要做的事情。 为此(如果您更喜欢拉起控制台),请执行以下步骤:

  1. 打开Tomcat主页http:// localhost:8080(如果已经保护了Tomcat服务器,则打开https:// localhost:8443)。
  2. 单击页面左上方的“ Tomcat管理”链接。
  3. 输入您的管理员用户名和密码,然后单击登录
  4. 单击左窗格中Resources文件夹下的Data Source
  5. 单击“ 创建新数据源”
  6. 根据表1键入所有适当的信息。
  7. 单击“ 保存” ,然后单击“ 提交更改”
  8. 查看server.xml文件以获取刚刚提供的信息。

注意:您可能仍然需要将全局数据源名称映射到Web应用程序中使用的本地名称。 为此,请将以下资源链接添加到server.xml文件中的<Context> XML标记中:

<ResourceLink global="jdbc/TestDS" name="ds/TestDS"type="javax.sql.DataSource"/>

使用Tomcat Web应用程序管理器GUI创建数据源时,它会在全局名称空间中创建供所有应用程序使用的数据源。 对于仅由您的应用程序使用的特定数据源,请在<Context>标记下添加资源。

最好在server.xml文件中手动创建资源定义和资源引用,因为它是同一件事,但是速度更快,并且允许您直接操纵服务器配置,从而无需依赖控制台即可获得更多知识和经验。

server.xml文件在<Context>标记下包含基本资源配置。 只需在vi编辑器中删除该行前面的特殊字符(例如<!--和相应的-->标记)即可清除注释。然后,您可以进一步编辑文件以匹配在中找到的值下一节。

创建资源定义

清单5提供了需要在server.xml文件中更新的定义的基本示例。

清单5.在server.xml文件中创建资源定义
<Context path="/{your Web application's context path}" docBase="{the Web application path where yourWAR is installed}"debug="5" reloadable="true" crossContext="true"><Resource name="jdbc/{db name}" auth="Container" type="{database type}"maxActive="100" maxIdle="30" maxWait="10000"username="{your db user}" password="{your db pwd}" driverClassName=
"{your driver class}"url="{your jdbc URL}"/></Context>ie.
<Context path="/DBTest" docBase="DBTest"debug="5" reloadable="true" crossContext="true"><Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"maxActive="100" maxIdle="30" maxWait="10000"username="dbuser" password="test1234" \driverClassName="com.mysql.jdbc.Driver"url="jdbc:mysql://localhost/javatest?autoReconnect=true"/>
</Context>

您可以在<DefaultContext>标记内定义资源以供所有Web应用程序使用,或者可以在特定应用程序的<Context>元素内定义资源。

创建资源参考

键入vi APP_HOME/WEB-INF/web.xml从命令行创建一个新的web.xml文件。 然后,键入i以使用名为TestDB的测试数据源插入清单6中的代码。

清单6.为此测试应用程序创建一个WEB-INF / web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"version="2.4"><description>Test SQL for test App</description><resource-ref><description>DB Connection</description><res-ref-name>jdbc/TestDB</res-ref-name><res-type>javax.sql.DataSource</res-type><res-auth>Container</res-auth></resource-ref>
</web-app>

然后,输入:wq! 保存文件和相当vi。 或者,您可以简单地更新现有的web.xml文件,而不是从头开始创建web.xml文件。 差异很小,如清单7所示 。 这两种方法是相似的,并且如上所述只是引用您的数据库资源。

在命令行中,在vi中打开现有的web.xml文件。 然后,键入i以将清单7中的代码插入<web-app>标记之间。

清单7.在现有的web.xml文件中定义资源引用
<description>DB Connection</description><resource-ref><description>DB Connection</description><res-ref-name>jdbc/TestDB</res-ref-name><res-type>javax.sql.DataSource</res-type><res-auth>Container</res-auth></resource-ref>
</web-app>

输入:wq! 保存文件和相当vi。

清单6中的代码与清单7中的代码之间的唯一区别是<web-app>标记,其中引用了模式URL。

使用JNDI引用修改代码

最佳实践是要注意的重要一点,如果将硬编码的数据库访问引用分隔为不会影响其余代码的对象,则部署和管理安装版本会更容易。 这适用于业务逻辑与表示层,等等。

本教程不涉及创建自定义资源工厂,使用数据访问对象或使用非DBCP连接。 然而,在提供更多信息的链接相关的话题 。

安全

如果您要提供实时Web应用程序,则保护Tomcat服务器至关重要。 即使仅将Tomcat服务器作为测试服务器运行,以下概念对于理解和实现也很重要。

服务器安全性

从两个不同的角度考虑安全性:服务器安全性和应用程序安全性。 服务器安全性包括Java安全管理器,在安全端口下启动Tomcat以及为服务器设置SSL证书。 应用程序安全性主要涉及基于安全角色的用户身份验证和授权,具体取决于用户尝试访问的受保护资产。

如果要将服务器用作独立服务器,则强烈建议在Tomcat服务器上设置SSL。 如果您有前端HTTP服务器,则该服务器可能会处理所有需要SSL的HTTP over HTTP(HTTPS)连接上的SSL,并将这些请求路由到适当的Tomcat服务器。 在其他情况下,即使Tomcat服务器位于同一网络中的同一防火墙之后,也可能需要打开SSL才能在它们之间启动受信任的连接。

使用keytool设置SSL

SSL连接本质上是两个互相信任的服务器。 他们彼此信任的方式是拥有自签名的或由第三方验证的安全密钥。

自签名证书适合加密,但不能接受真正的在线受信任身份验证。 尝试仅使用自签名证书访问网站时,您将在浏览器中看到许多警告消息。

下面讨论存储,请求和导入签名的服务器证书的过程。 此信息是执行最基本的Tomcat安全性操作(例如在安全端口下启动服务器)的先决条件。

幸运的是,Java提供了一个相对简单的命令行工具,称为keytool ,可以轻松创建自签名证书。 自签名证书只是用户生成的证书,尚未在任何知名的证书颁发机构(CA)进行正式注册,因此根本无法保证它们是真实的。 但是,使用keytool ,您可以生成一个证书请求,该证书请求可以发送给第三方以进行可信验证,然后发送回“已签名”,以便您可以再次使用keytool导入该已签名的服务器证书。 然后,当客户端或其他服务器访问您的服务器或应用程序时,他们将知道您的服务器是谁。

创建一个密钥库

在获取安全证书之前,必须有放置证书的位置。 这个地方称为您的密钥库。 您还可以使用清单8或清单9中所示的命令同时创建您的自签名证书,具体取决于您的Java版本。

清单8.为Java 1.6或更高版本创建密钥库和自签名证书
keytool -genkeypair -alias tomcat -keyalg RSA -keystore /
$CATALINA_HOME/ssl/keystore
清单9.为低于1.6的Java版本创建密钥库和自签名证书
<!-- For Java versions earlier than 1.6, you must run two separate commands. -->
keytool -genkey -alias tomcat -keyalg RSA -keystore /
$CATALINA_HOME/ssl/keystore<!-- and -->
keytool -selfcert -alias tomcat -keystore /
$CATALINA_HOME/ssl/keystore

You can specify key size, validity, e-mail address, and so on from the command line when creating the key, or you can type each value as you are prompted. Specify a password value of changeit , which is the default password recommended by most documentation. Feel free to set this to something different, if you'd like.

Note: $CATALINA_HOME/ssl is a directory that I created and recommend creating to hold your keystore and server certificates. However, you can include any directory path here as long as you stay consistent when referencing it in the future.

Save typing time

To avoid typing the full $JAVA_HOME/bin/keytool path before each command, add $JAVA_HOME/bin to your PATH variable, if you haven't done so already. Also, in case you were wondering, if you don't specify a -keystore value, keytool still creates the keystore under your user home directory under the name .keystore.

Edit your keystore

You can edit your keystore at a later time, if needed. When you're prompted to type your key password for <tomcat> or whatever your alias name is, press Enter to leave this the same as your keystore password. You will use your alias to reference your keystore from here on out.

Listing 10 shows the code for editing your keystore

Listing 10. Edit your keystore
keytool -genkey -alias tomcat -keyalg RSA  -keystore /
$CATALINA_HOME/ssl/keystore

Change the company, location, default password information, and so on as appropriate.

Obtain a certificate from a trusted authority

To obtain a certificate from the CA of your choice, you must first create a Certificate Signing Request (CSR). This is synonymous with Server Cert Request, if you're familiar with that term from working on other software platforms. Listing 11 shows the code for creating a CSR.

Listing 11. Create your CSR
$keytool -certreq -keyalg RSA -alias tomcat -file certreq.csr /-keystore $CATALINA_HOME/ssl/keystore

Now you have a file called certreq.csr that you can submit to the CA. In return, you get a certificate. For a list of third-party digital CAs, see Related topics .

To complete the certificate process, perform the following steps:

  1. Go to your third-party vendor's Web site, and obtain the Root certificate or certificate chain.

    Note that some secure servers require an intermediary and Root certificate. You must obtain both from the third-party vendor, both of which will be in the chain. You can also import these certificates individually.

  2. Import the chain by typing:
    keytool -import -alias root -keystore $CATALINA_HOME/ssl/keystore -trustcacerts -file

    where file is the name of the certificate chain.

  3. Import your signed server certificate by typing:
    keytool -import -alias tomcat -keystore $CATALINA_HOME/ssl/keystore -file

    where file is the name of your signed certificate file.

Quick tip

When saving your signed server certificate and certificate chain, you do not have to download and save it. You can actually cut and paste the contents of the SSL RSA key encryption into the file with the appropriate name on the server. You can open chain.csr, select the key contents, and then paste the contents into vi. Save the file by typing :wq!

You now have the SSL keys necessary to run Tomcat as a trusted server. However, you must now configure Tomcat to use SSL. Tomcat does this through connectors, which the next section defines as you start the server under a secure port.

Start Tomcat under a secure port

By default, the server.xml file contains SSL connector information that you need to "uncomment" to finish configuring Tomcat security. First, make sure the SSLEngine attribute is set to On in the server.xml file—for example:

<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />

Listing 12 shows the defaults for the Connector element in Tomcat version 6's server.xml file.

Listing 12. Connector element defaults:
<Connector port="8443" minSpareThreads="5" maxSpareThreads="75"enableLookups="true" disableUploadTimeout="true" acceptCount="100"  maxThreads="200"scheme="https" secure="true" SSLEnabled="true"keystoreFile="$CATALINA_HOME/ssl/keystore" keystorePass="changeit"clientAuth="false" sslProtocol="TLS"/>
...

Uncomment the <Connector> tag, then set the keystoreFile and keystorePass attributes to match what you configured the keystore for. The default port attribute value used in this example is 8443. This is the TCP/IP port number on which Tomcat will listen for secure connections. You can change this value to any port number you wish. Best practice, however, is to stick to somewhat typical SSL ports, such as 443.

Note that if you change the port number here, you should also change the value specified for the redirectPort attribute on the non-SSL connector. This allows Tomcat to automatically redirect users who attempt to access a secure page or resource specifying that SSL is required.

To access your new protected and secure Tomcat server default page, type the address https://localhost:8443 in your Web browser's address bar. You should see a page similar to Figure 2 .

Figure 2. The Security console Welcome page

A final nugget of truth to keep in your head for later is, if and when you run secure virtual hosts, you need to add an SSL Factory element to the SSL connector for each server's keystore.

Security manager

The built-in Java Security Manager for Tomcat is simply an alternative to protect your Tomcat server from mischievous or accidental code packages that can cause damage to your server. The JRE lets you purposely restrict certain pieces of code from administering the JVM, having certain permissions on your server file systems, and so on. In many cases, a server hosted in an environment easily accessible from the Web should add this additional layer of security so that hackers cannot manipulate the server or view any files on it. Note, however, that this addition can also be too restrictive if your code needs to write files to your server file system for some reason, so use it wisely and test full application functionality before implementing it in a production environment.

The security policies that Security Manager implements are configured in the $CATALINA_HOME/conf/catalina.policy file, with the appropriate permissions pertaining to different pieces of the Web application. Please review the file to determine what and where you will need to edit to change anything that deviates from the default values.

To start the server with Security Manager policies enabled, type the following command:

$CATALINA_HOME/bin/catalina.sh start -security

Authentication and security roles

Securing the server with SSL keys to make it trusted is great, but now you need to make your application (or at least parts of it) prompt users to securely authenticate to gain access to protected resources. Tomcat provides four common authentication mechanisms and also allows for customized secure authentication. For time purposes, I show you how to set up Basic authentication, and then how to expand this to Form-based, Custom, and Digest authentication.

If you configure Basic authentication, users are prompted with a login dialog box when they attempt to access a protected resource. If you use Form-based authentication, users are redirected to an HTML page that allows them to log in when they attempt to access a protected resource. You use Custom authentication when you require additional information from the user before allowing him or her to log in. And you use Digest authentication when you need an added level of security through hashed passwords.

基本认证

First, define the apps- appname. xml file to specify the application that's going to use Basic authentication as well as the users file that it will reference specifically for security roles for this application. Listing 13 shows the contents of this XML file.

Listing 13. Contents of a conf/apps- appname. xml file
<?xml version="1.0" encoding="ISO-8859-1"?>
<webapps><Context path="/sample" docBase="webapps/sample" reloadable="true"> <SimpleRealm filename="conf/users/appname-users.xml" /></Context>
</webapps>

Next, you must create the application-specific security role in the appname -users.xml file. Type any user name and password you would like, and make sure you give them the appropriate authentication role. For more information on the available roles, refer to the Tomcat documentation (see Related topics ).

Listing 14 shows an example appname -users.xml file.

Listing 14. Sample conf/users/ appname -users.xml
<tomcat-users><user name="username" password="passwd" roles="rolename" />
</tomcat-users>

Finally, type the details shown in Listing 15 in the main WEB-INF/web.xml file. These details specify your different protected resources and which HTTP methods they are protected against. If you have resources other than JSP or HTML files that you need to protect, you can add them here. Additionally, you will see Basic authentication defined along with which role is given by default to any user on the system.

Listing 15. Sample webapps/appname/WEB-INF/web.xml file
<security-constraint><web-resource-collection><web-resource-name>user-resource</web-resource-name><description>pages which require login</description><url-pattern>*.jsp</url-pattern><url-pattern>*.html</url-pattern><http-method>GET</http-method><http-method>POST</http-method></web-resource-collection><auth-constraint><description>Must authenticate before querying the system</description><role-name>rolename</role-name></auth-constraint><user-data-constraint><transport-guarantee>NONE</transport-guarantee></user-data-constraint></security-constraint><login-config><auth-method>BASIC</auth-method><realm-name>default</realm-name></login-config><security-role><description>Any user of the system</description><role-name>rolename</role-name></security-role>

Note that you will have to ensure that the <role-name> section points to the roles in which you created the users.

基于表单的身份验证

Form-based authentication is probably the most common way to authenticate users to access-protected Web pages. It has been around for quite a while and allows you to create custom login and error pages to match the look and feel of your site while building upon the security features of Basic authentication.

Form-based authentication when switching back and forth between HTTPS and HTTP is better than Basic authentication, as your user name and password are not sent with each request. Remember that it is still highly recommended that you use a secure transport mechanism such as HTTPS when using Form-based or any of the four authentication mechanisms mentioned here.

To build on the Basic authentication that you've already set up, perform the following steps:

  1. Create a custom error and login.jsp file (not covered in this tutorial).
  2. Replace the login-config section of the Basic authentication code with the code in Listing 16 .
    Listing 16. Modify the Basic authentication code
    <login-config><auth-method>FORM</auth-method><realm-name>Web Demo</realm-name><form-login-config><form-login-page>/admin/login.jsp</form-login-page><form-error-page>/admin/error.jsp</form-error-page></form-login-config>
    </login-config>

    The security constraint information stays the same.

    Note: When creating the HTML form, the following syntax is required:

    <form method="POST" action="j_security_check"><input type="text" name="j_username"><input type="text" name="j_password"><input type="submit" value="Log in">
    </form>
  3. Restart Tomcat for the changes to take effect.

Custom authentication

Both Form-based and Custom authentication concepts are beyond the scope of this tutorial and require additional development. Custom authentication would have you protect a resource—for example, a JSP file—then refer to that resource in the Web-INF directory, as shown in Listing 17 .

Listing 17. Referring to a resource in the WEB-INF/web.xml file
<web-app> <security-constraint>  <!-- web resources that are protected --> <web-resource-collection> <web-resource-name>A Protected Page</web-resource-name> <url-pattern>/protected-page.jsp</url-pattern> </web-resource-collection> <auth-constraint> <role-name>resin-user</role-name> </auth-constraint> </security-constraint><login-config> <auth-method>BASIC</auth-method> <realm-name>Basic Authentication Example</realm-name> <!-- The authenticator tag is Resin-specific --> <authenticator id='beans.SimpleAuthenticator'/> </login-config></web-app>

Digest authentication

Digest authentication is essentially the same as Basic authentication, except that Digest authentication transmits a password's hash value, not the password itself. Listing 18 shows the update you would make to the web.xml file originally edited for Basic authentication.

Listing 18. The web.xml file edited for Digest authentication
<auth-method>DIGEST</auth-method>  <realm-name>Digest Authentication Example</realm-name> </login-config>
</web-app>

The only difference between Basic and Digest authentication is the specification of the authentication method, as shown in Listing 18. So, why would you prefer Basic over Digest? I haven't found a great answer for that. Digest is simply the more secure alternative.

Expandability

Expandability is an extremely important concept for anyone wanting to really get into production-type architecture and high availability. It allows you to run many more Web sites or applications in your Web server environment with greater availability than ever before. Of course, such advantages always come at a price. A true architectural solution for what your business needs are should be decided by your management and an IT architect. However, I'm always a fan of techies with extra hardware and too much time on their hands, so if you'd like to explore the concepts below on your own servers, I certainly encourage that!

Virtual hosts

Virtual hosting is simply the concept of allowing one server instance configured on one or more physical server nodes to host two or more applications at the same time. This is an extremely common practice on the Web, mainly because most individuals and small companies cannot afford their own dedicated servers to host their Web applications. With shared space and processes along with ever-improving virtual server software, this is relatively easy for a Web administrator to set up.

Virtual hosting has its obvious limitations, like one application or Web site being codependent on resources with another. What if one application brings a whole server down, which (surprisingly) happens quite often? All other applications are affected. The only true way to remove (or come close to it) such dependencies is to try to eliminate single points of failure in your server environment. That's where clustering comes in.

To use virtual hosts in Tomcat, you just need to set up the Domain Name System (DNS) or hosts data for the host. (For testing, making an IP alias for localhost is sufficient.)

Then, you must add the lines in Listing 19 to the server.xml configuration file.

Listing 19. Set up DNS for the host
<Engine name="Catalina" defaultHost="localhost" debug="0"><!-- This host is the default host. --><Host name="localhost" debug="0" appBase="webapps"unpackWARs="true" autoDeploy="true"><Context path="" docBase="ROOT" debug="0"/></Context></Host><!-- This host is the first virtual host: www.example.com. --><Host name="www.example.com" appBase="/home/example/webapp"><Context path="" docBase="."/></Host></Engine>

Tomcat's server.xml file, as distributed, contains only one virtual host, but it's easy to add support for additional virtual hosts. The simplified version of the server.xml file in Listing 19 shows the overall additional structure needed to add one virtual host. Each Host element must have one or more Context elements within it; one of these must be the default context for this host, which is specified by having its relative path set to the empty string (for example, path="" ).

Note: If you've configured Tomcat to support multiple virtual hosts (Web sites), you need to configure a manager for each.

A default Tomcat installation includes the manager. To add an instance of the manager Web application context to a new host, install the manager.xml context configuration file in the $CATALINA_HOME/conf/ enginename / hostname folder, as shown in Listing 20 .

Listing 20. Example manager context path
<Context path="/manager" debug="0" privileged="true"docBase="/opt/tomcat/localhost/webapps/manager">
</Context>

聚类

Clustering is the second important concept of expandability that you should understand in a Web server environment. In contrast to virtual hosting, which allows you to serve multiple applications from a single server instance, clustering allows you to run multiple server instances from different physical servers while providing robust session and load management. In any true production environment, this is a must. Its purposes are three-fold:

  • It removes single points of failure in the environment from a software or hardware level. Two servers installed on one physical node provide what's called vertical scaling to failover at a software level. However, this does not suffice if there were a hardware failure. Horizontal scaling provides physical and logical failover, as is the case with true clustering.
  • Clustering has the potential to improve performance. Certainly, if your application has its own stand-alone server mansion to exhaust all the resources by its lonesome, then this doesn't hold true. However, most applications share one server with many other applications. When you add more servers and more resources—memory, CPU, and so on—you get increased performance.
  • Clustering is transparent to users. Even if a server goes down in the middle of a user's transaction, session persistence handled through a persistent session database will hold the session data and immediately transfer it to the other server.

Considering how extensive a topic clustering is, this tutorial doesn't get into its implementation. If you truly are hosting many applications or plan to from your Tomcat servers, see Related topics for more information.

Additional administration tips

This section outlines a few tasks that you may need to perform as you navigate your server, stop and start processes, troubleshoot, and so on. You can employ these tips could before, after, or during the steps for securing your server or setting up your database.

Granting access to the Tomcat Web Server Administration tool

The Tomcat Web Server Administration tool allows you to see server information, edit connections, modify resources, and more. It also gives you a nice interface in which to manage, create, and change user names and passwords for your main Tomcat admin user as well as add new roles and new users.

This tool is defined in $CATALINA_HOME/webapps/admin.xml. The initial login administrative user must be defined in the same tomcat-users.xml file in which your Tomcat Web Server Administration tool role and user is set up. First, add these two lines between the two <tomcat-users> tags:

cd $CATALINA_HOME/conf
vi tomcat-users.xml

Then, add the code in Listing 21 to the tomcat-users.xml file to grant access to Tomcat Web Application Manager by adding users and roles.

Listing 21. Grant access to the Tomcat Web Server Administration tool
<tomcat-users>
<role rolename="admin"/>
<user username="admin" password="s3cur3" roles="admin"/></user>
</tomcat-users>

You must restart Tomcat to access the Tomcat Web Server Administration tool using the http://localhost:8080/admin URL. To restart the server, use the code in Listing 22 .

Listing 22. Restart your Tomcat Server
cd $CATALINA_HOME/bin
./shutdown.sh
./startup.sh ;tail -f ../logs/catalina.out

You should see something similar to this when you tail your catalina.out log file:

May 15, 2008 4:08:12 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/74  config=null
May 15, 2008 4:08:12 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 6271 ms

Type the URL http://localhost:8080/admin in your Web browser's address bar. If your changes were successful, you'll see the page shown in Figure 3. .

Figure 3. Tomcat Web Server Administration tool login page

Run the server under a non-root user ID

If you have a true multi-user system with many people logging in and out of your Web server, consider running your Tomcat installation under a Tomcat user that has specific access to your directories and processes. Also, if you have multiple software installations on that server, such as a database installation or a down-version or alternative Web or application server, you need a way to differentiate them. The best way to administer them using a specific ID for each installation. It's definitely good practice in a production environment and something you will typically find when you have segregated administration and deployment teams administering the same server. The administrators are typically given greater control and grant only certain accesses to deployment teams.

First, you must create your user ID and group. If you worked through the previous Tomcat tutorial, you will already have done this. Simply run the following commands:

  • To create a group for Tomcat to run under, use the following code:

    /usr/sbin/groupadd -g {specific gid. Leave this blank, and the operating system willassign you a gid}
    {group name}
    ie.
    /usr/sbin/groupadd -g 10004 tomcatgroup
  • To create a unique user for Tomcat to run under, use the following code:
    /usr/sbin/useradd -d {user home directory} -g {user
    primary group} -u
    {specific UID. You can leave this blank, and the operating system will
    assign you a UID.)
    -s {default shell path for this user} -c "{Description of
    the user}" {username}
    ie.
    /usr/sbin/useradd -d /export/home/tomcat -g tomcatgroup -u
    10010 -s /bin/ksh -c
    "Main Tomcat Administrative User" tomcat

To change ownership of all $CATALINA_HOME directories to the Tomcat user and Tomcat group, type:

Chown -R tomcat:tomcat $CATALINA_HOME

Note: The -R option specifies a fully recursive change of ownership.

Next, start Tomcat using the jsvc daemon but with the -user option specified. You can do this by directly editing the $CATALINA_HOME/bin/jsvc/native/tomcat.sh script and changing the following parameter to your ID:

TOMCAT_USER=tomcat

Note: You'll find the above variable grouped with other variables such as $JAVA_HOME, $CATALINA_HOME just under the comment section of the script. Use vi or your editor of choice to change that.

You can also make this change by running the jsvc service manually while specifying the -user option:

Cd $DAEMON_HOME (where this is the location of your jsvc-src dir)
Bash#./jsvc -user tomcat -cp ./bin/bootstrap.jar \
-outfile ./logs/catalina.out -errfile ./logs/catalina.err \org.apache.catalina.startup.Bootstrap

This is assuming that JAVA_HOME and CATALINA_HOME are already specified. If not, you can add those directories to the above manual startup:

Bash#./jsvc -user tomcat -home /usr/jdk/instances/jdk1.5.0 \
-Dcatalina.home=/opt/apache-tomcat-6.0.16 \
-cp ./bin/bootstrap.jar -outfile ./logs/catalina.out \
-errfile ./logs/catalina.err \org.apache.catalina.startup.Bootstrap

Both methods technically start as root and change the user running this process to the user specified.

Determining whether Tomcat is running

Tomcat has no status. So, to determine whether Tomcat is running, you must type:

ps -ef |grep java |grep server

You should see output similar to Listing 23 if you started as the root user with the default startup.sh script.

Listing 23. Output from starting Tomcat as the root user
bash-3.00# ps -ef | grep java|grep server
noaccess   720     1   0 16:35:05 ?           5:06 /usr/java/bin/java -server
-Xmx128m -XX:+BackgroundCompilation -XX:PermSize=32m

If you started the server using the jsvc daemon manually or Tomcat started upon server startup through the tomcat.sh script under $CATALINA_HOME/bin/jsvc/native/tomcat.sh, you can check to see if the server is running by checking for the existence of the Tomcat .pid file:

Ls -l var/run/tomcat.pid

or by viewing or use Cat on the pid file:

Cat /var/run/tomcat.pid

Check for the .pid file, then use grep on the pid process to see if it's running:

Ps -ef | grep {pid}

Altering the JVM settings

This tip is in particular reference to JVM-allowable memory. The main reason why you would need to raise this value is if you have a large application, plan to use the Tomcat server in a production environment, or plan to run certain controlled load tests against your application with various JVM memory levels to see where memory heap exhaustion takes place. Usually, when running controlled tests, you will set the minimum and maximum heap at the same size until you reach your peak load and gain your desired data. Then, you can change the settings back to normal.

The Tomcat default is set to a maximum of 128MB. To see the value, the line server -Xmx128m appears when you use the status check command. If you're running multiple JVMs, remember not to set the accumulate total of the maximum JVM heap sizes greater than the available memory on your server.

In this case, you can edit the tomcat.sh script or run the jsvc daemon manually with the following options included in the startup line:

server -Xms128m -Xmx512m

Use the command shown in Listing 24 to configure your JVM settings.

Listing 24. Configure your JVM settings
#./jsvc -user tomcat -home /usr/jdk/instances/jdk1.5.0 \
-Dcatalina.home=/opt/apache-tomcat-6.0.16 \
-cp ./bin/bootstrap.jar -outfile ./logs/catalina.out \
-errfile ./logs/catalina.err \
-server -Xms128m -Xmx512m \org.apache.catalina.startup.Bootstrap

Typical advanced application server best practices state that it's best to set the minimum JVM heap size to one-quarter of the maximum. Try to avoid changing the memory settings arbitrarily, especially when trying to fix a problem that likely isn't related to the JVM memory in the first place. Increasing the maximum heap size has pros and cons: It's important to understand both.

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

摘要

Tutorial conclusion and summary

Your intense Tomcat training session is complete! You will likely not need to implement everything discussed in this tutorial at once, but you now have the knowledge to configure a robust Web or application server.

You should be able to deploy your new applications seamlessly from here on out and have a stable and secure Web server that you can use in a test or production environment. 祝好运!


翻译自: https://www.ibm.com/developerworks/aix/tutorials/au-expandtomcat/index.html

web服务器tomcat_扩展Tomcat Web服务器的功能相关推荐

  1. Web开发如何实现Tomcat等服务器热部署不用重启

    Web开发如何实现Tomcat等服务器热部署不用重启 听语音 | 浏览:354 | 更新:2016-05-28 11:18 在进行java web开发的时候,对类改动一些代码后,通常就需要对服务器比如 ...

  2. 最锋利的Visual Studio Web开发工具扩展:Web Essentials详解(转)

    Web Essentials是目前为止见过的最好用的VS扩展工具了,具体功能请待我一一道来. 首先,从Extension Manager里安装:最新版本是19号发布的2.5版 然后重启你的VS开发环境 ...

  3. 最锋利的Visual Studio Web开发工具扩展:Web Essentials详解

    Web Essentials是目前为止见过的最好用的VS扩展工具了,具体功能请待我一一道来. 首先,从Extension Manager里安装:最新版本是19号发布的2.5版 然后重启你的VS开发环境 ...

  4. java web服务与配置,Java Web远端服务器的配置与部署

    写在前面 首先说使用云服务器和我们使用自己的PC电脑其实是差不多的,只是我们在服务器上运行的一些软件都是提供网络服务的.在本文中,我们首先了解一些远端服务器的控制工具,然后了解一下服务器的整体配置,最 ...

  5. 如何搭建java web环境_搭建java WEB开发环境和应用

    搭建java WEB开发环境和应用 更新时间:2009年06月07日 02:28:56   作者: 使用Tomcat服务器,使用DBCP数据源搭建Web开发环境 一 使用Tomcat服务器,使用DBC ...

  6. Linux Java Web 服务器搭建之tomcat安装

    Linux Java Web 服务器搭建之tomcat安装 一 Tomcat 简介 Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是 ...

  7. 将Web项目部署到华为云服务器的Linux的Tomcat中

    将Web项目部署到阿里云服务器的Linux的Tomcat中 01_用SSH Secure Shell Client或Xshell 6这个Windows客户端工具,将在Windows中已经开发完毕的Ja ...

  8. 服务器组件架构,tomcat组件图解 一个web服务器的架构演化史

    1. tomcat是谁? 2. tomcat可以做什么? tomcat是一个web容器,可以将web应用部署到tomcat,由它提供web服务,一个web容器中可以部署多个web应用,这些web应用可 ...

  9. web服务器 linux+apache+tomcat+mysql+jsp+php 整合安装

    2019独角兽企业重金招聘Python工程师标准>>> web服务器 linux+apache+tomcat+mysql+jsp+php 整合安装 自己的安装过程,以前发表在新浪博客 ...

最新文章

  1. 鸿蒙可以和安卓抗衡吗,鸿蒙手机系统正式登场!继承EMUI的衣钵,能抗衡安卓系统吗?...
  2. 第三章:3.5 傅里叶变换
  3. github高级搜索技巧_【建议收藏】百度 quot;隐藏quot; 的高级搜索技巧
  4. Boost:获取随机数的实例
  5. ms project 入门_Microsoft Project 2010入门
  6. c++ 与 java_Java与C++比较
  7. react 示例_2020年的React Cheatsheet(+真实示例)
  8. python遗传算法计算实例_遗传算法python简单例子(详解)
  9. 移动端与PC端页面布局区别
  10. Android精讲--界面编程2(布局管理器)
  11. fatal error C1083: 无法打开包括文件:“stdint.h”: No such file or directory
  12. PL/SQL学习笔记之存储过程
  13. MySQL中的isnull、ifnull和nullif函数用法
  14. js之数组去重的方法
  15. Java 正则表达式匹配规则
  16. matlab符号函数作图,matlab制图—符号函数(显函数、隐函数和参数方程)画图
  17. Java观察者模式(Observer)
  18. 腾讯云:开发者实验室
  19. 深度学习与自然语言处理(1)_斯坦福cs224d Lecture 1
  20. 邮件客户端 gmail hotmail

热门文章

  1. BAT面试官告诉你如何回答你的职业规划
  2. 百度·智能小程序学院院长沈抖:谈为趋势发展的百度智能小程序
  3. oracle数据库背景颜色,ORACLE FORM 开发:更新背景颜色
  4. cmakelist 常见用法
  5. 关于单片机串口接收不固定字节长度的解决方案
  6. 瑞云服务云携手慧而特,引领餐饮设备服务创新升级
  7. 小程序 VS 公众号、APP的区别在哪?
  8. 学海记录项目测试报告
  9. 英特尔® 虚拟化技术
  10. 【路径规划】基于matlab Hybrid A_Star算法机器人路径规划【含Matlab源码 1390期】