 |
» |
|
|
 |
|  |  |
This section explains how to install, configure, and manage
the Web Server middleware stack components not included in the Linux
distribution along with other related components. All components are
distributed as RPM packages or binaries, therefore, you can install
and remove all the components separately. Table 1 lists the appropriate version and additional
information. You must install the following components separately: SUN JDK for HP Proliant systems or
BEA JRockit for HP Integrity systems
Configuring the Basic Apache HTTP Server |  |
Use the following procedure to configure a basic Apache HTTP
Server. It is necessary to set a valid server host name prior
to running an Apache HTTP Server to avoid an error. The Apache configuration
files are located in /etc/httpd/conf and the
main configuration file is httpd.conf. Edit /etc/httpd/conf/httpd.conf and designate
a valid hostname for the ServerName directive using the following syntax: ServerName <YOUR_HOSTNAME>:80 |
Restart Apache for the changes take effect by entering
the following command: # /etc/init.d/httpd restart Verify that Apache starts successfully by ensuring that
messages similar to the following appear in the /var/log/httpd/error_log log file: [Thu May 10 11:25:14 2007] [notice] Apache/2.2.3 (Red Hat) configured -- resuming normal operations |
Create a file named /var/www/html/apache.html and add the following lines: <HTML>
<HEAD>
</HEAD>
<BODY DIR="LTR">
<P ALIGN=CENTER STYLE="margin-bottom: 0cm">
<FONT FACE="Times New Roman, serif">
<FONT SIZE=6>Apache http server worked !</FONT>
</FONT></P>
</BODY>
</HTML>
|
Verify the Apache installation by opening a browser and entering
the following website: http://<YOUR_WEB_SERVER_IP>/apache.html The following message appears: Apache HTTP server worked ! Installing and Configuring the Sun JDK on an HP Proliant System |  |
For an HP Proliant system, use the following procedure for installing
and configuring a Sun Java Development Kit (JDK). Download the hardware appropriate Sun JDK from the Java
website and install as follows (see Table 1 for the correct version and website link): - For x86_64 systems:
Change to the Sun JDK install package directory, as
appropriate for your system, and install the package by entering the
following commands: # chmod 755 jdk-1_5_0_10-linux-amd64-rpm.bin # ./jdk-1_5_0_10-linux-amd64-rpm.bin - For x86 systems:
Change to the Sun JDK install package directory, as
appropriate for your system, and install the package by entering the
following commands: # chmod 755 jdk-1_5_0_10-linux-i586-rpm.bin # ./jdk-1_5_0_10-linux-i586-rpm.bin
Create symbolic links for the Sun JDK by entering the
following command: # ln -s /usr/java/jdk1.5.0_10 /usr/local/jdk The JAVA_HOME environment variable must
be properly set before stack components, such as Tomcat, can begin
executing. Both bash and cshell use a different syntax for setting environment variables.
To export the JAVA_HOME environment variable, modify the system file
that is appropriate for your shell, /etc/profile.d/java.sh or /etc/profile.d/java.csh: - For the java.sh file add
the following lines:
export JAVA_HOME=/usr/local/jdk
export PATH=$JAVA_HOME/bin:$PATH |
- For the java.csh file add
the following lines:
setenv JAVA_HOME /usr/local/jdk
setenv PATH $JAVA_HOME/bin:$PATH |
Log out of the system, then log back in to start using
the revised profile. Verify that the Sun JDK installation was successful by
entering the following command: # java –version - For x86_64 systems:
The following messages appear: java version "1.5.0_10"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_10-b03)
Java HotSpot(TM) 64-Bit Server VM (build 1.5.0_10-b03, mixed mode) |
- For x86 systems:
The following messages appear: java version "1.5.0_10"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_10-b03)
Java HotSpot(TM) Server VM (build 1.5.0_10-b03, mixed mode) |
Installing and Configuring BEA JRockit on an HP Integrity System |  |
For an HP Integrity system, use the following procedure for
installing and configuring BEA JRockit on your Web Server. Download the BEA JRockit package from the BEA website.
See Table 1 for the
correct version and website link. Change the permissions of the downloaded package file
and install it using the following commands: # chmod 755 jrockit-R27.2.0-jdk1.5.0_10-linux-ipf.bin # ./jrockit-R27.2.0-jdk1.5.0_10-linux-ipf.bin Create a symbolic link for the BEA JRockit by entering
the following commands: # ln -s /usr/local/jrockit-R27.2.0-jdk1.5.0_10 /usr/local/jdk The JAVA_HOME environment variable must
be set properly before stack components, such as Tomcat, can begin
executing. To export the JAVA_HOME environment
variable, edit /etc/profile and add the following
lines: JAVA_HOME=/usr/local/jdk
PATH=$JAVA_HOME/bin:$PATH
export JAVA_HOME PATH
|
Log out of the system, and then log back in to start using
the revised profile. Verify the BEA JRockit installation was successful by
entering the following command: # java –version The following message appears: java version "1.5.0_10"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_10-b03)
BEA JRockit(R) (build R27.2.0-131-78843-1.5.0_10-20070320-1457-linux-ia64, compiled mode) |
Advanced Apache HTTP Server Features |  |
The following section describes several widely used Apache HTTP
Server features. Using the Apache HTTP Server Benchmarking ToolThe benchmarking tool is supplied with the Apache HTTP Server
and is used to benchmark your Apache HTTP Server and monitor its performance.
For example, you can use the benchmarking tool to perform concurrency
requests to an Apache HTTP Server. Use the following command to start
using the benchmarking tool: Additionally, you can verify the stability of the Apache HTTP
Server by running a basic stress test on the test system. The following
steps show a stress test for an example system: Create a file using the following path name: /var/www/html/abtest.html Add the following lines to the file you created in Step
1: <HTML>
<HEAD>
</HEAD>
<BODY DIR="LTR">
<P ALIGN=CENTER STYLE="margin-bottom: 0cm">
<FONT FACE="Times New Roman, serif">
<FONT SIZE=6>The page is used for Apache benchmarking test !</FONT>
</FONT>
</P>
</BODY>
</HTML> |
Perform a concurrency request to the test system by logging
into another system and entering the following command: # ab -c 1000 -n 1000 http://<YOUR_WEB_SERVER_IP>/abtest.html |
Where: The value of the -n option sets the
number of requests. The value of the -c option sets the
number of concurrency requests.
Monitor the access status on the test system by displaying
the end of the access log file. To do this, enter the following command: # tail -f /var/log/httpd/access_log |
The system displays messages similar to the following: 10.101.1.84 - - [10/May/2007:12:00:46 +0800] "GET /abtest.html HTTP/1.0" 200 206 "-" "ApacheBench/2.0.40-dev"
10.101.1.84 - - [10/May/2007:12:00:46 +0800] "GET /abtest.html HTTP/1.0" 200 206 "-" "ApacheBench/2.0.40-dev"
10.101.1.84 - - [10/May/2007:12:00:46 +0800] "GET /abtest.html HTTP/1.0" 200 206 "-" "ApacheBench/2.0.40-dev"
10.101.1.84 - - [10/May/2007:12:00:46 +0800] "GET /abtest.html HTTP/1.0" 200 206 "-" "ApacheBench/2.0.40-dev"
10.101.1.84 - - [10/May/2007:12:00:46 +0800] "GET /abtest.html HTTP/1.0" 200 206 "-" "ApacheBench/2.0.40-dev"
|
You can force a heavier load on the Apache HTTP Server by increasing
the number of concurrency requests with the -c option,
and by prolonging the testing round by increasing the number of requests
with the -n option. Apache HTTP Server Status and InformationYou can obtain various pieces of information regarding your
Apache HTTP Server by configuring the mod_status and mod_info module requests within the httpd.conf configuration file. The mod_status module is configured using the server-status request and the mod_info module is configured
using the server-info request. For example, you
can find out the current hosts and requests being processed, whether
the server was started or restarted, and basic server configuration
information. These two functions help you monitor your Apache HTTP
Server. Configuring and Using the ModulesUse the following steps to enable these two modules to collect
and display information. Edit the /etc/httpd/conf/httpd.conf file and add the following lines: <Location /server-status>
SetHandler server-status
Order deny,allow
Deny from all
Allow from YOUR_WEB_BROWSER_IP
</Location>
<Location /server-info>
SetHandler server-info
Order deny,allow
Deny from all
Allow from YOUR_WEB_BROWSER_IP
</Location> |
Restart your Apache HTTP Server for the changes to take
effect.
Use the following procedure to verify the server status and
display the server information web page: Verify the server status by opening a browser and entering
the following URL: http://<YOUR_WEB_SERVER_IP>/server-status Display the server information web page by opening a browser
and entering the following website: http://<YOUR_WEB_SERVER_IP>/server-info The Apache Server Information web page opens, as shown in Figure 4.
The Apache HTTP Server provides a detailed and flexible information-logging
mechanism. The two most important log files are the error and access
logs. The default location for the Apache HTTP Server log files is
the following directory: /var/log/httpd Using the Error Log to Diagnose the Apache HTTP Server The Apache HTTP Server records diagnostic information and all
errors encountered while processing requests to the error log file, error_log. For example, if you visit a nonexistent URL, the following 404
error is generated: The requested URL /non-exist/ was not found on this server. |
All error information is recorded in the default error log file,
which you can obtain by entering the following command: # tail –f /var/log/httpd/error_log |
The following message is added to the end of the file: <Tue Dec 19 00:59:03 2006> <error> <client 10.100.0.22> File does not exist:
/var/www/html/non-exist |
Using Webalizer to Perform Apache HTTP Server Log AnalysisWebalizer is an analysis tool that you can use to generate detailed
usage reports using the information recorded in the Apache HTTP Server
logs. Webalizer provides easy-to-read reports in HTML format that
you can customize for your needs. Use the following procedure to set up Webalizer: Open the file named /etc/httpd/conf.d/webalizer.conf with a text editor. Modify the file lines as follows: Alias /usage /var/www/usage
<Location /usage>
Order deny,allow
Deny from all
Allow from YOUR_WEB_BROWSER_IP
</Location>
|
Verify that the server status configuration is correct by opening
a browser and entering the following website: http://<YOUR_WEB_SERVER_IP>/usage |
Figure 5 shows an example
of a Webalizer usage report web page. For detailed information, see the Webalizer website at: http://www.mrunix.net/webalizer/ Using Virtual Host SupportA virtual host runs more than one website on a single server.
For example, www.website1.com and www.website2.com can be hosted on
the same server. The most widely used virtual host is "name-based," which means
that multiple names are running on one IP address. Because the user
provides the hostname as part of the URL, the user is not aware that
various websites are using the same IP address. The following example steps illustrate the use of virtual hosting: To configure virtual hosting, you must resolve two host
names to the same IP address. One method is to edit the /etc/hosts file of the client system as follows: For Windows systems, edit the C:\WINDOWS\system32\drivers\etc\hosts file. For Linux systems, edit the /etc/hosts file.
Add the following line: <YOUR_WEB_SERVER_IP> www.website1.com www.website2.com |
Verify that both websites resolve to the same IP address
by entering the following commands: # ping www.website1.com
# ping www.website2.com |
Create the following two directories: /var/www/html/website1
/var/www/html/website2 |
Create the following file: /var/www/html/website1/index.html |
Populate the file that you created in Step 5 with the
following lines: <HTML>
<HEAD>
</HEAD>
<BODY DIR="LTR">
<P ALIGN=CENTER STYLE="margin-bottom: 0cm">
<FONT FACE="Times New Roman, serif">
<FONT SIZE=6>This is www.website1.com</FONT>
</FONT></P>
</BODY>
</HTML>
|
Create the following file: /var/www/html/website2/index.html |
Populate the file that you created in Step 7 with the
following lines: <HTML>
<HEAD>
</HEAD>
<BODY DIR="LTR">
<P ALIGN=CENTER STYLE="margin-bottom: 0cm">
<FONT FACE="Times New Roman, serif">
<FONT SIZE=6>This is www.website2.com</FONT>
</FONT></P>
</BODY>
</HTML>
|
Configure virtual hosting by editing
the file named /etc/httpd/conf/httpd.conf and
adding the following lines: NameVirtualHost *:80
<VirtualHost *:80>
DocumentRoot /var/www/html/website1
ServerName www.website1.com
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /var/www/html/website2
ServerName www.website2.com
</VirtualHost>
|
Restart your Apache HTTP server for the changes to take
effect. Verify that the virtual hosting configuration operates
properly by opening a browser and entering the following website: www.website1.com The following message appears: This is www.website1.com Open a second browser and enter the following website: www.website2.com The following message appears: This is www.website2.com
Using Apache HTTP Server URL RedirectionThe following procedure illustrates the use of the URL redirection
feature which allows you to configure the Apache HTTP server to send
requests for one URL to another URL. This requires the use of two
servers that are both running Apache HTTP server. On the first server, create the following directory: On the second server, create the following HTML file: Add the following lines to the file you created in Step
2: <HTML>
<HEAD>
</HEAD>
<BODY DIR="LTR">
<P ALIGN=CENTER STYLE="margin-bottom: 0cm">
<FONT FACE="Times New Roman, serif">
<FONT SIZE=6>The URL redirect is successful!</FONT>
</FONT></P>
</BODY>
</HTML>
|
Edit the following configuration file: /etc/httpd/conf/httpd.conf |
Add the following line to the preceding file: Redirect permanent /testdir http://<ANOTHER_WEB_SERVER_IP>/test.html |
Use the following command to restart your Apache HTTP
server, for the preceding changes to take effect: # /etc/init.d/httpd restart |
Verify that the URL redirect configuration is correct
by opening a browser and entering the following website: http://<YOUR_WEB_SERVER_IP>/testdir The following message appears: The URL redirect is successful! |
Using Apache HTTP Server Proxy FeaturesThe proxy features within the Apache HTTP server enable your
server to act as a Proxy server (a network gateway). The following procedure illustrates the use of URL redirection.
The procedure requires the use of three systems that are all running
identical Linux distributions. The first system functions as an Apache
HTTP server, the second functions as the Apache Proxy server, and
the third system is a web client. Start the Apache HTTP server on the first system. On the second system, which acts as the Apache Proxy server,
edit the following file: /etc/httpd/conf/httpd.conf |
Add the following lines to the preceding file: ProxyRequests On
ProxyVia On
<Proxy *>
Order deny,allow
Deny from all
Allow from all
</Proxy>
|
Using the benchmarking tool, test the Apache Proxy server
using the third system, which acts as the web client: # ab -c 10 -n 10 -X <YOUR_PROXY_SERVER_IP>:80 \
http://<YOUR_WEB_SERVER_IP>/test.html |
View the access log file on the Apache Proxy server. Messages
similar to the following are contained in the file: YOUR_WEB_BROSWER_IP - - [11/May/2007:15:51:13 +0800]
"GET http://YOUR_WEB_SERVER_IP/test.html HTTP/1.0"
200 206 "-" "ApacheBench/2.0.40-dev" |
View the access log file on the Apache HTTP server. Messages
similar to the following are contained in the file: YOUR_PROXY_SERVER_IP - - [11/May/2007:16:05:19 +0800]
"GET http://YOUR_WEB_SERVER_IP/test.html HTTP/1.0"
200 206 "-" "ApacheBench/2.0.40-dev" |
These messages verify that the Apache Proxy server configuration
is successful.
Error Responses and RedirectsThe following three types of error responses can be customized
and are addressed in this section: Customizing Plain Text ResponsesThe following is an example of how to customize a plain text
error response: Edit the following file: /etc/http/conf/httpd.conf |
In the preceding file, change (or add, if it does not exist
already) the following line: ErrorDocument 404 "The page you requested does not exist! Plain text example" |
Restart your Apache HTTP server for the changes take effect. Verify the custom text error message by opening a browser
and entering the following website: http://<YOUR_WEB_SERVER_IP>/non-exist The following message appears: The page you requested does not exist! Plain text example |
Customizing Local URL Redirect ResponsesThe following is an example for customizing a local URL redirect
error message: Edit the following file: /etc/http/conf/httpd.conf |
In the preceding file, change (or add, if it does not exist
already) the following line: ErrorDocument 404 "/missing.html" |
Create the following HTML file: /var/www/html/missing.html |
Add the following lines to the preceding file: <HTML>
<HEAD>
</HEAD>
<BODY DIR="LTR">
<P ALIGN=CENTER STYLE="margin-bottom: 0cm">
<FONT FACE="Times New Roman, serif">
<FONT SIZE=6>The page you request does not exist!
Local redirects example</FONT></FONT></P>
</BODY>
</HTML>
|
Verify the custom local URL redirect message by opening
a browser and entering the following website: http://<YOUR_WEB_SERVER_IP>/non-exist The following message appears: The page you request does not exist!
Local redirects example |
Customizing External URL Redirect ResponsesThe URL redirect feature allows you to trap a missing link error
(404 error) in a browser on a local server, display a message, and
then redirect it to a URL on an external server. The following steps
illustrate how to customize external URL redirect responses. The process
requires the use of two servers; one that acts as local server, another
that acts as an external server. Use the following procedure to customize
external URL redirect responses: Edit the following configuration file: /etc/http/conf/httpd.conf |
In the preceding file, change (or add, if it does not exist
already) the following line: ErrorDocument 404 http://<EXTERNAL_WEB_SERVER_IP>/missing.html |
Create the following HTML file: /var/www/html/missing.html |
Populate the preceding file with the following
lines: <HTML>
<HEAD>
</HEAD>
<BODY DIR="LTR">
<P ALIGN=CENTER STYLE="margin-bottom: 0cm">
<FONT FACE="Times New Roman, serif">
<FONT SIZE=6>The page you request does not exist!
External redirects example</FONT></FONT></P>
</BODY>
</HTML>
|
Verify the custom external URL redirect message by opening
a browser and entering the following website: http://<YOUR_WEB_SERVER_IP>/non-exist The following message appears: The page you request does not exist!
External redirects example |
Using Per-User Web DirectoriesUsing the UserDir function, each user is
allowed to have a personal website in their home directory on servers
that have multiple users. Visiting a URL with its name in the form http://example.com/~username displays the contents of the home directory of the user. The following is an example for configuring per-user web directories: Add a user named tester to your server
by entering the following commands: # useradd tester
# mkdir /home/tester/public_html
# chmod 755 /home/tester/public_html |
Create an HTML file named /home/tester/public_html/index.html that contains the following lines: <HTML>
<HEAD>
</HEAD>
<BODY DIR="LTR">
<P ALIGN=CENTER STYLE="margin-bottom: 0cm">
<FONT FACE="Times New Roman, serif">
<FONT SIZE=6>The is personal homepage of user tester .</FONT>
</FONT></P>
</BODY>
</HTML>
|
Edit the /etc/httpd/conf/httpd.conf file and comment out the following line, if it exists: Then, add the following lines: UserDir enabled tester
UserDir public_html
|
Restart your Apache HTTP server for the
changes to take effect. Verify that the per-user web directory configuration was
successful by opening a browser and entering the following website: http://<YOUR_WEB_SERVER_IP>/~tester The following message appears: The is personal homepage of user tester. |
Integrating the Web Server Stack Components |  |
This section describes the commonly used configurations for
the Web server stack components. Configuring the Apache and Tomcat Connector The following section explains how to use the mod_jk module from the Apache Jakarta Project (AJP) to connect the Apache
Web server and the Tomcat Web Container. The Apache HTTP server uses URL pattern rules, defined in the
Apache Web server configuration file, to determine which requests
to handle and which to forward. It handles content, such as static
HTML pages, images, and CGI scripts. The Tomcat connector (mod_jk) uses the AJP protocol to forward all requests
for JSPs, servlets, and web functionality to Tomcat as shown in Figure 6. The following example provides the steps to configure Apache
Web server routing requests under the DOCUMENT_ROOT/jsp-examples/ directory to the Tomcat server: Download the mod_jk module from the
Apache Software Foundation (see Table 1 for the correct version and website link),
and follow the instructions provided to build the mod_jk.so shared library. If necessary, copy the mod_jk.so file into the appropriate directory as follows: - For x86_64 servers:
/usr/lib64/httpd/modules - For x86 or HP Integrity servers:
/usr/lib/httpd/modules
Edit the Apache Web
server configuration file, /etc/httpd/conf/httpd.conf. Add the lines as appropriate for
your server model. - For x86_64 servers:
# Load mod_jk
LoadModule jk_module /usr/lib64/httpd/mod_jk.so
# Configure mod_jk
JkWorkersFile conf/workers.properties
JkLogFile logs/mod_jk.log
JkLogLevel info |
- For x86 or HP Integrity servers:
# Load mod_jk
LoadModule jk_module /usr/lib/httpd/mod_jk.so
# Configure mod_jk
JkWorkersFile conf/workers.properties
JkLogFile logs/mod_jk.log
JkLogLevel info |
Insert the following line below the DocumentRoot line: JkMount /jsp-examples/* worker1 |
Before you can verify the Tomcat and Apache integration,
you must set Tomcat to listen for AJP13 requests. The JK module uses
AJP to communicate with Tomcat so, you must verify that the AJP <Connector> element is enabled in the Tomcat
file server.xml and that this file is placed
inside the <Service> element.
Verify that the following lines are included and not
commented out in the $CATALINA_HOME/conf/server.xml file. <Connector port="8009"
enableLookups="false" redirectPort="8443" protocol="AJP/1.3" /> |
Create the following file: /etc/httpd/conf/workers.properties |
Add the following lines to the preceding file: # Define 1 real worker using ajp13
worker.list=worker1
# Set properties for worker1 (ajp13)
worker.worker1.type=ajp13
worker.worker1.host=<YOUR_TOMCAT_SERVER_IP>
worker.worker1.port=8009
worker.worker1.lbfactor=50
worker.worker1.cachesize=10
worker.worker1.cache_timeout=600
worker.worker1.socket_keepalive=1
worker.worker1.socket_timeout=300
|
If necessary, start Tomcat it by entering the following
command: # $CATALINA_HOME/bin/startup.sh |
Restart Apache by entering the following command: # /etc/init.d/httpd restart |
Verify that you can connect to Tomcat through the standard
HTTP port served by Apache by navigating to the website: http://<YOUR_HOSTNAME>/jsp-examples/ Figure 7 show an example
of the JSP Examples page.
If there are any errors, check the following log files: /var/log/httpd/error_log
/var/log/httpd/access_log
/var/log/httpd/mod_jk.log |
Integrating the Apache Web Server and PHPThe Apache Web server that is shipped with the supported Linux
distribution includes a built-in PHP module. Therefore, no extra configuration
is required for Apache. Use the following procedure to configure PHP: Verify that PHP is installed by entering the following
command: # rpm -q php Create the following test file: Add the following lines to the preceding file: <?
## test.php
phpinfo();
?> |
Verify that PHP works by opening a browser and navigating
to the following website : http://<YOUR_HOSTNAME>/test.php A web page containing the PHP version and license numbers is
displayed.
Integrating the Apache Web Server and PerlThe mod_perl module integrates a Perl interpreter
into the Apache Web server, allowing you to use Perl when creating
web applications. Use the mod_perl module provided
by the Linux distribution. To test the installation, perform the following steps: Verify that the mod_perl module is
installed by entering the following command: # rpm -q mod_perl Add the following lines to the /etc/httpd/conf.d/perl.conf file: #!/usr/bin/perl
print "Content-type: text/plain\n\n";
print "mod_perl rocks!\n"; |
Restart Apache by entering the following command: # /etc/init.d/httpd
restart Verify that Perl works by opening a browser
and navigating to the following website: http://<YOUR_HOSTNAME>/perl-status Figure 8 is displayed.
If there are any errors, check the following log files: /var/log/httpd/error
/var/log/httpd/access |
Integrating the Apache Web Server and PythonThe mod_python module embeds the Python
environment into the Apache Web server. Embedding this environment
avoids the run-time overhead of starting the Python environment externally. Use the mod_python package provided by
the Linux distribution. Verify that the mod_python module
is installed by entering the following command: Create the following test file: Add the following lines to the preceding file from mod_python import apache
def handler(req):
req.content_type = 'text/plain'
req.write("Hello World!")
return apache.OK
|
Edit the following file: /etc/httpd/conf.d/python.conf |
Add the following lines to the preceding file: <Directory /var/www/html>
AddHandler mod_python .py
PythonHandler test
PythonDebug On
</Directory> |
Restart Apache by entering the following command: # /etc/init.d/httpd restart |
Verify that Python works by opening a browser and navigating
to the following website: http://<YOUR_HOSTNAME>/test.py The web page displays the following text: Hello World!
If there are any errors, check the following log files: /var/log/httpd/error
/var/log/httpd/access |
Connecting Tomcat to a Database |  |
Connecting Tomcat to a database requires a JDBC driver for that
particular database . The driver is responsible for translating calls
from Java programs to the native protocol that is understood by the
database. Figure 9 depicts
the connection between Tomcat and a database using JDBC. Tomcat uses the data-source concept to create database connections.
A data source must be configured in an XML configuration file. The
data source provides details about the target database, such as the
database server IP address and login credentials. The JDBC driver
connects to the database and the username/password combination is
used to login to the database. For Tomcat 5.5, a data source is configured
either in $CATALINA_HOME/conf/context.xml or
in /META-INF/context.xml within the web applications.
By default, the data source support in Tomcat is based on the Database
Connection Pool (DBCP), which is used to create active connections
and manage the lifecycle of the individual connections automatically. Connecting Tomcat and MySQLMySQL is the leading open source database, and is used widely
for web application middleware environments. MySQL stores relational
data and enables fast, simple access and updates to stored data through
the standard JDBC APIs. These APIs are supplied by MySQL in the form
of the Connector/J software. This section describes the steps to connect
Tomcat to MySQL. Obtaining and Installing the JDBC DriversPerform the following steps on the Tomcat web server: Download the MySQL JDBC driver 5.0 from the MySQL website: http://dev.mysql.com/downloads/connector/j/5.0.html Unzip the downloaded packages by entering the following
command: # tar zxf mysql-connector-java-<version>.tar.gz Install the JDBC driver for Tomcat by entering the following
command: # cp mysql-connector-java-<version>-.jar
$CATALINA_HOME/common/lib
Creating a New Data SourceTo create a data source binding for a JDBC driver, perform the
following steps on the Tomcat web server: Create a data source descriptor file named $CATALINA_HOME/conf/context.xml and insert the following lines: <Context>
…
<Resource name="jdbc/mysqlDB" auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://<IP_OR_NAME_OF_MYSQL_SERVER>:3306/<DATABASE_NAME>"
username="<DB_USERNAME>"
password="<DB_PASSWORD>" maxActive="10" maxIdle="10" maxWait="-1" />
</Context>
|
For example: <Resource name="jdbc/mysqlDB" auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://191.168.1.100:3306/osmsdb" username="osmsusr"
password="osmspass" maxActive="10" maxIdle="10" maxWait="-1" /> |
Start the Tomcat web server by entering the following
command: # $CATALINA_HOME/bin/startup.sh
Configuring the MySQL ServerTo configure the MySQL database, perform the following steps
on the MySQL server: Verify that the MySQL server is running properly by entering
the following command: # ps -ef|grep mysqld If the MySQL server is running, a process named mysqld displays in the output; otherwise, enter
the following command: # /etc/init.d/mysql
start If the database used in the Tomcat data source does not
exist, create the database by entering the following command: # mysqladmin -u
root -p create osmsdb The name of the database created in the command is osmsdb. If the database user in the Tomcat data source does not
exist, create the user and grant the appropriate privileges by entering
the following commands from the mysql prompt: mysql> grant all on osmsdb.* to osmsuser@'%.%.%.%' identified by \ 'osmsuser'; mysql> flush privileges; The user named osmsuser with
the password osmspass is created
and is granted all operation privileges on the database osmsdb.
Testing MySQL Database ConnectivityTo test the connectivity between Tomcat and MySQL, perform the
following steps on the Tomcat web server: Create a JSP file named $CATALINA_HOME/webapps/ROOT/mysqltest.jsp and insert the following lines: <%@page contentType="text/html" import="java.io.*,java.sql.*,
javax.sql.*,javax.naming.*"%>
<html>
<head>
<title>Tomcat->MySQL Test </title>
<link rel="stylesheet" href="style_master.css" type="text/css">
<meta http-equiv="cache-control" content="no-cache">
</head>
<body>
<%
InitialContext ctx = new InitialContext();
DatabaseMetaData dm = null;
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mysqlDB");
Connection conn = null;
Statement stmt = null;
try {
conn = ds.getConnection();
dm =conn.getMetaData();
out.println("Connected to-> database version"
+dm.getDatabaseProductVersion());
}catch (Exception sqlex) {
out.println(sqlex.getMessage());
}finally{
conn.close();
}
%>
</body>
</html> |
If needed, start Tomcat by entering the following command: # $CATALINA_HOME/bin/startup.sh Verify Tomcat is connecting to MySQL by opening a browser
and navigating to the following website: http://<YOUR_HOSTNAME>:8080/mysqltest.jsp The test page opens as shown in Figure 10.
Connecting Tomcat and Oracle |  |
Oracle is the leading commercial relational database. It is
generally used to store and manage sensitive and mission-critical
data. As with MySQL, Oracle can also be used as the persistence layer
for web applications. A JDBC connector for Oracle is needed to integrate
an external Oracle Database server with the Tomcat Web server. This
section describes the steps for connecting the Tomcat Web server to
an Oracle database. Obtaining and Installing the Oracle JDBC DriverPerform the following steps from the Tomcat Web server: Creating an Oracle Data SourceTo create a data source binding for the Oracle JDBC driver data
source, perform the following on the Tomcat Web server: Create a file named $CATALINA_HOME/conf/context.xml and insert the following lines: <Context>
…
<Resource name="jdbc/oracleDB" type="javax.sql.DataSource"
password="<DB_PASSWORD>"
driverClassName="oracle.jdbc.driver.OracleDriver"
maxIdle="2" maxWait="5000" username="<DB_USERNAME>"
url="jdbc:oracle:thin:@ <IP_OR_NAME_OF_ORACLE_SERVER>:1521:<ORACLE_SID>" maxActive="4"/>
</Context>
|
For example: <Resource name="jdbc/oracleDB" type="javax.sql.DataSource"
password="osmspass"
driverClassName="oracle.jdbc.driver.OracleDriver"
maxIdle="2" maxWait="5000" username="osmsusr"
url="jdbc:oracle:thin:@192.168.1.100:1521:OSMSDB" maxActive="4"/> |
Configuring the Oracle ServerPerform the following steps on the Oracle Database server: Verify that the Oracle server and the listener are running
by entering the following command: # lsnrctl status Create a database user and grant the proper privileges,
which should be the same as the user in the $CATALINA_HOME/conf/context.xml file, by entering the following commands: # sqlplus / as sysdba SQL> create user
osmsusr identified by osmspass; SQL> grant connect,resource
to osmsusr;
Testing the Oracle Database ConnectivityTest the connectivity between the Tomcat server and the Oracle
database by performing the following steps on the Tomcat Web server: Create a JSP file named $CATALINA_HOME/webapps/ROOT/oracleTest.jsp and insert the following lines: <%@page contentType="text/html" import="java.io.*,java.sql.*,
javax.sql.*,javax.naming.*"%>
<html>
<head>
<title>Tomcat->Oracle Test </title>
<link rel="stylesheet" href="style_master.css" type="text/css">
<meta http-equiv="cache-control" content="no-cache"></head>
<body>
<%
InitialContext ctx = new InitialContext();
DatabaseMetaData dm = null;
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/oracleDB");
Connection conn = null;
Statement stmt = null;
try {
conn = ds.getConnection();
dm =conn.getMetaData();
out.println("Connected to-> database version"
+dm.getDatabaseProductVersion());
}catch (Exception sqlex) {
out.println(sqlex.getMessage());
}finally{
conn.close();
}
%>
</body>
</html> |
If the Tomcat Web server is not running, start it by entering
the following command: # $CATALINA_HOME/bin/startup.sh Verify that the Oracle test page is displayed (Figure 11 ) by opening a browser
and navigating to the following website: http://<YOUR_HOSTNAME>:8080/oracleTest.jsp
Connecting Tomcat to MySQL or Oracle Using Hibernate |  |
Hibernate is an open-source object and relational mapping framework.
It uses a lightweight object encapsulation for JDBC and allows JAVA
developers to access data from databases using JAVA objects. Hibernate
is designed to run in a managed environment, such as the environment
of the web server. With Hibernate, you only need to configure a small
part of the environment. Hibernate inherits database connections from
the application server. Therefore, it is easy to create an enterprise
application that uses Hibernate capabilities in the same way as other
capabilities available in the application server. You can obtain Hibernate
and Hibernate tools from the product websites. See Table 1 for the appropriate
links. This section provides an example demonstrating the use of Hibernate
for web applications using a MySQL or Oracle database. Configuring a Database Driver in TomcatVerify that MySQL or Oracle are configured as data sources for
Tomcat as described in “Connecting Tomcat to a Database” before proceeding. To verify that the mysql-connector-java-<VERSION>.jar or ojdbc14.jar are configured, go to the $CATALINA_HOME/common/lib directory and verify that the corresponding file exists. Adding Test Data to the DatabasesIn order to verify that the MySQL or Oracle database interact
properly with Tomcat, you must populate the database with test data. Add test data to the MySQL database using the following steps: Log in to the MySQL command line tool by entering the
following command: # mysql -u root -p <PASSWORD> Create a database named osmsdb and create a table named USERS by
entering the following commands: mysql> create database osmsdb; mysql> use osmsdb; mysql> create table
USERS( mysql> User_id int(10)
auto_increment not null primary key, mysql> First_name
varchar(30) not null, mysql> Last_name
varchar(30) not null mysql> ); Add a user named osmsusr that uses
the password osmspass and grant the appropriate
privileges to it by entering the following commands mysql> create user 'osmsusr'@'%.%.%.%'; mysql> grant all
on osmsdb.* to 'osmsusr'@'%.%.%.%' identified \ by 'osmspass';
Add test data to the Oracle database using the following steps: Creating a Simple Application in TomcatYou must create a simple application within Tomcat to facilitate
verification of this functionality. This simple application implements
the insert, update, select, and delete functions for the USERS table in the MySQL or Oracle database. Use the following steps to create a simple application in Tomcat: Create a directory named $CATALINA_HOME/webapps/SimpleDemo that contains the appropriate subdirectories by entering the following
commands: # mkdir $CATALINA_HOME/webapps/SimpleDemo # mkdir $CATALINA_HOME/webapps/SimpleDemo/META-INF # mkdir $CATALINA_HOME/webapps/SimpleDemo/WEB-INF # mkdir $CATALINA_HOME/webapps/SimpleDemo/WEB-INF/classes # mkdir $CATALINA_HOME/webapps/SimpleDemo/WEB-INF/lib Configure the MySQL or Oracle data source by creating
a file named $CATALINA_HOME/webapps/conf/Catalina/localhost/SimpleDemo.xml. Add the following lines, depending on whether your database is
MySQL or Oracle: For a MySQL database server: <Context>
<Resource
name="MySqlDS"
type="javax.sql.DataSource"
password="osmspass"
driverClassName="com.mysql.jdbc.Driver"
maxIdle="10"
maxWait="5000"
username="osmsusr"
url="jdbc:mysql://IP_OR_HOSTNAME_OF_DB_SERVER:3306/osmsdb"
maxActive="15"/>
</Context> |
For an Oracle database server: <Context>
<Resource
name="OracleDS"
type="javax.sql.DataSource"
password="osmspass"
driverClassName="oracle.jdbc.driver.OracleDriver"
maxIdle="10"
maxWait="5000"
username="osmsusr"
url="jdbc:oracle:thin:@IP_OR_HOSTNAME_OF_DB_SERVER:1521:osmsdb_ora"
maxActive="15"/>
</Context> |
Where: IP_OR_HOSTNAME_OF_DB_SERVER is the MySQL or Oracle database server name or IP address. Add the Hibernate3 JAR files to the application library
by copying the following files from the Hibernate3 installation directory
to $CATALINA_HOME/webapps/SimpleDemo/WEB-INF/lib: | hibernate3.jar | | dom4j-1.6.1.jar | | cglig-2.1.3.jar | | commons-logging-1.0.4.jar | | commons-collections-2.1.1.jar | | ehcache-1.1.jar | | asm.jar | | asm-attrs.jar | | antlr-2.7.6rc1.jar |
Hibernate uses a configuration file named hibernate.cfg.xml to obtain the database connection information and mapping file information. Create a Hibernate configuration file named $CATALINA_HOME/webapps/SimpleDemo/WEB-INF/classes/hibernate.cfg.xml. Add the following lines, depending on whether your database
is MySQL or Oracle: For a MySQL database server: <?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property name="connection.datasource">java:comp/env/MySqlDS</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="com/hp/osms/hibernate/Users.hbm.xml" />
</session-factory>
</hibernate-configuration> |
For an Oracle database server: <?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
Installing,Configuring,and Managing Web Application Server Middleware Stack
Components 33 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property name="connection.datasource">java:comp/env/OracleDS</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<mapping resource="com/hp/osms/hibernate/Users.hbm.xml" />
</session-factory>
</hibernate-configuration> |
 |  |  |  |  | NOTE: The values of OracleDS and MySqlDS are the data source names
that are configured in the Tomcat Web server. |  |  |  |  |
In Hibernate, a unit of work is named a session that is managed by SessionFactory. To retrieve data for a session, create a utility named HibernateSessionFactory.java located in $CATALINA_HOME/webapps/SimpleDemo/WEB-INF/classes/com/hp/osms/utility and add the following lines so the application can interact with
Hibernate:  |
package com.hp.osms.hibernate.utility;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
private HibernateSessionFactory() {
}
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession():null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("Can not create SessionFactory!!");
e.printStackTrace();
}
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null)
session.close();
}
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
} |
 |
Compile the HibernateSessionFactory.java file by entering the following commands: # cd $CATALINA_HOME/webapps/SimpleDemo/WEB-INF/classes/com/hp
\ /osms/hibernate/utility # javac -cp $CATALINA_HOME/webapps/SimpleDemo
\ /WEB-INF/lib/hibernate3.jar HibernateSessionFactory.java The file HibernateSessionFactory.class is
generated. Create a Hibernate mapping file named Users.hbm.xml, in the directory $CATALINA_HOME/webapps/SimpleDemo/WEB-INF/classes/com/hp/osms/hibernate according to the definition in the USERS table that contains the following lines: <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.hp.osms.hibernate.Users" table="USERS">
<id name="userId" type="java.lang.Long">
<column name="USER_ID" precision="10" scale="0" />
<generator class="native">
<param name="sequence"> HIBERNATE_SEQUENCE</param>
</generator>
</id>
<property name="firstName" type="java.lang.String">
<column name="FIRST_NAME" length="30" />
</property>
<property name="lastName" type="java.lang.String">
<column name="LAST_NAME" length="30" />
</property>
</class>
</hibernate-mapping> |
Hibernate uses a Plain Old Java Object (POJO) to pass
values between the application tier and the persistent tier. Change
your default directory to the following path: # cd $CATALINA_HOME/webapps/SimpleDemo/WEB-INF/classes \
/com/hp/osms/hibernate |
In this directory, create a Hibernate POJO file named $CATALINA_HOME/webapps/SimpleDemo/WEB-INF \ /classes/com/hp/osms/hibernate/Users.java according to the mapping file for your application. Add the following
lines: package com.hp.osms.hibernate;
public class Users implements java.io.Serializable {
private Long userId;
private String firstName;
private String lastName;
public Users() {
}
public Users(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Long getUserId() {
return this.userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
} |
Compile a Hibernate POJO file and move the class file
into $CATALINA_HOME/webapps/SimpleDemo/WEB-INF \ /classes/com/hp/osms/hibernate/Users.java by entering the following command: The preceding command creates a class file named: $CATALINA_HOME/webapps/SimpleDemo/WEB-INF \ /classes/com/hp/osms/hibernate/Users.class Test Hibernate functionality such as inserting, updating,
deleting, and retrieving data from the database, by creating a sample
JSP file named $CATALINA_HOME/webapps/SimpleDemo/hibernate.jsp. The following code fragment from hibernate.jsp shows how to use Hibernate to insert data into the database: org.hibernate.Session hbsession = HibernateSessionFactory.getSession();
try{
Transaction tx = hbsession.beginTransaction();
Users users= new Users();
users.setFirstNa |
|