Jump to content United States-English
HP.com Home Products and Services Support and Drivers Solutions How to Buy
» Contact HP
More options
HP.com home
HP Open Source Middleware Stacks Blueprint:: Web Server on HP ProLiant Servers with SUSE Linux Enterprise Server Version 10

Installing, Configuring, and Managing Web Server Middleware Stack Components

» 

Technical documentation

Complete book in PDF
» Feedback
Content starts here

 » Table of Contents

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

  • Tomcat

Configuring the Basic Apache HTTP Server

Use the following procedure to configure a basic Apache HTTP Server.

  1. Start Apache by entering the following:

    # /etc/init.d/apache2 start

  2. Verify that Apache starts successfully by ensuring that messages similar to the following appear in the log file /var/log/apache2/error_log:

    [Sat Feb 03 12:41:21 2007] [notice] Apache/2.2.0 (Linux/SUSE) configured -- resuming normal operations
  3. Create a file named /srv/www/htdocs/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 Sun JDK on an HP Proliant System

For an HP Proliant system, the following procedure to install and configure a Sun Java Development Kit (JDK):

  1. Download the Sun JDK package from the Java website and install as follows (see Table 1 for the correct version and website link):

    Change to the Sun JDK install package directory, as appropriate for your system, and install the package by entering the following command:

    # chmod 755 jdk-1_5_0_10-linux-amd64-rpm.bin

    # ./jdk-1_5_0_10-linux-amd64-rpm.bin

  2. Create a symbolic link for Sun JDK by entering the following:

    # ln -s /usr/java/jdk1.5.0_10 /usr/local/jdk

  3. The JAVA_HOME environment variable must be properly set before stack components, such as Tomcat, can begin executing.

    To export the JAVA_HOME environment variable, modify the system file that is appropriate for your shell, /etc/profile.d/alljava.sh or /etc/profile.d/alljava.csh:

    For the alljava.sh file, add the following lines:

    if [ -x /usr/local/jdk/bin/java ] ; then
      export PATH=$PATH:/usr/local/jdk/bin
      export JAVA_BINDIR=/usr/local/jdk/bin
      export JAVA_ROOT=/usr/local/jdk
      export JAVA_HOME=/usr/local/jdk
      export JRE_HOME=/usr/local/jdk
      unset JDK_HOME
      unset SDK_HOME
      export JDK_HOME=/usr/local/jdk
      export SDK_HOME=/usr/local/jdk
    else
      if [ -x /usr/lib/java/jre/bin/java ] ; then
        # it is IBMJava2-JRE or SunJava2-JRE
        export PATH=$PATH:/usr/lib/java/jre/bin
        export JAVA_BINDIR=/usr/lib/java/jre/bin
        export JAVA_ROOT=/usr/lib/java
        export JAVA_HOME=/usr/lib/java/jre
        export JRE_HOME=/usr/lib/java/jre
        unset JDK_HOME
        unset SDK_HOME
      fi
    fi

    For the alljava.csh file, add the following lines:

    if ( -x /usr/local/jdk/bin/java ) then
      setenv PATH ${PATH}:/usr/local/jdk/bin
      setenv JAVA_BINDIR /usr/local/jdk/bin
      setenv JAVA_ROOT /usr/local/jdk
      setenv JAVA_HOME /usr/local/jdk
      setenv JRE_HOME /usr/local/jdk
      unsetenv JDK_HOME
      unsetenv SDK_HOME
      setenv JDK_HOME /usr/local/jdk
      setenv SDK_HOME /usr/local/jdk
    else
      if (-x /usr/lib/java/jre/bin/java)then
        #it is IBMJava2-JRE or SunJava2-JRE
        setenv PATH ${PATH}:/usr/lib/java/jre/bin
        setenv JAVA_BINDIR /usr/lib/java/jre/bin
        setenv JAVA_ROOT /usr/lib/java
        setenv JAVA_HOME /usr/lib/java/jre
        setenv JRE_HOME /usr/lib/java/jre
        unsetenv JDK_HOME
        unsetenv SDK_HOME
      endif
    endif
  4. Log out of the system, and then log back in to start using the revised profile.

  5. Verify the Sun JDK installation was successful by entering the following:

    # java –version

    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)
    

Installing and Configuring Tomcat

The following procedure provides the steps for installing and configuring Tomcat.

NOTE: Prior to installing Apache Tomcat, you must verify that JDK is installed and configured on your system.
  1. Download the Tomcat Web Server package from the Apache Software Foundation website and follow the instructions provided to install it. See Table 1 for the correct version and website link.

    NOTE: In the following steps, it is assumed that Tomcat is installed in /usr/local/apache-tomcat; if Tomcat is installed in a different directory, replace /usr/local/apache-tomcat with the correct path.
  2. Set the CATALINA_HOME environment variable to the Tomcat directory path by editing /etc/profile and adding the following lines to the end of the file:

    CATALINA_HOME=/usr/local/apache-tomcat
    export CATALINA_HOME
    
  3. Log out of the system, and then log back in to it to start using the revised profile.

  4. Start Tomcat by entering the following:

    # /usr/local/apache-tomcat/bin/startup.sh

    The following messages appear:

    Using CATALINA_BASE:   /usr/local/apache-tomcat
    Using CATALINA_HOME:   /usr/local/apache-tomcat
    Using CATALINA_TMPDIR: /usr/local/apache-tomcat/temp
    Using JRE_HOME:       /usr/local/jdk
    
  5. Verify that the Tomcat installation once the startup is complete by opening a browser and entering the following URL:

    http://<YOUR_TOMCAT_SERVER_IP>:8080

    The Tomcat web page is displayed as in Figure 5.

    Figure 5  Tomcat Successful Installation Verification

    Tomcat Successful Installation Verification
    NOTE: If the iptables firewall is enabled, you will not be able to connect to Tomcat from a remote computer.
  6. If necessary, stop Tomcat by entering the following command:

    # /usr/local/apache-tomcat/bin/shutdown.sh

    The following messages appear:

    Using CATALINA_BASE:   /usr/local/apache-tomcat
    Using CATALINA_HOME:   /usr/local/apache-tomcat
    Using CATALINA_TMPDIR: /usr/local/apache-tomcat/temp
    Using JRE_HOME:        /usr/local/jdk
    

Advanced Apache HTTP Server Features

The following section describes several widely used Apache HTTP Server features.

Using the Apache HTTP Server Benchmarking Tool

The 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:

# /usr/ab2

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:

  1. Create a file using the following path name: /srv/www/htdocs/abtest.html

  2. 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>
  3. Perform a concurrency request to the test system by logging into another system and entering the following command:

    # ab2 -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.

  4. 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/apache2/access_log

    The system displays messages similar to the following:

    10.101.2.28 - - [03/Feb/2007:12:49:53 -0500] "GET / HTTP/1.0" 200 44 "-" "ApacheBench/2.0.40-dev"
    10.101.2.28 - - [03/Feb/2007:12:49:53 -0500] "GET / HTTP/1.0" 200 44 "-" "ApacheBench/2.0.40-dev"
    10.101.2.28 - - [03/Feb/2007:12:49:53 -0500] "GET / HTTP/1.0" 200 44 "-" "ApacheBench/2.0.40-dev"
    10.101.2.28 - - [03/Feb/2007:12:49:53 -0500] "GET / HTTP/1.0" 200 44 "-" "ApacheBench/2.0.40-dev"
    10.101.2.28 - - [03/Feb/2007:12:49:53 -0500] "GET / HTTP/1.0" 200 44 "-" "ApacheBench/2.0.40-dev"
    10.101.2.28 - - [03/Feb/2007:12:49:53 -0500] "GET / HTTP/1.0" 200 44 "-" "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.

NOTE: If you encounter the following error:
socket: Too many open files (24)

You can correct the error by entering the following:

# ulimit -n <NUMBER>

This command increases the limit on the number of open files only for the current shell session. The increased limit is applicable to the newly launched commands on that shell after the change. Commands that you launched previously continue to use the previous limit.

Apache HTTP Server Status and Information

You 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 Modules

Use the following steps to enable these two modules to collect and display information.

  1. Edit the /etc/apache2/mod_status.conf file and add the following lines:

    <IfModule mod_status.c>
        <Location /server-status>
            SetHandler server-status
            Order deny,allow
            Deny from all
            Allow from YOUR_WEB_BROWSER_IP
        </Location>
    </IfModule>
  2. Edit the /etc/apache2/mod_info.conf file and add the following lines:

    <IfModule mod_info.c>
        <Location /server-info>
                SetHandler server-info
                Order deny,allow
                Deny from all
                Allow from YOUR_WEB_BROWSER_IP
        </Location>
    </IfModule>
  3. Modify the /etc/sysconfig/apache2 file by appending the following to the APACHE_MODULES definition:

    info status

    The APACHE_MODULES definition should now look like the following:

    APACHE_MODULES="actions alias auth_basic authn_file authz_host authz_groupfile authz_default authz_user authn_dbm autoindex cgi dir env expires include log_config mime negotiation setenvif ssl suexec userdir php5 info status"

  4. Restart the Apache HTTP Server for the changes take effect.

  5. Verify that the /etc/apache2/sysconfig.d/loadmodule.conf file contains the following lines:

    LoadModule info_module        /usr/lib64/apache2-prefork/mod_info.so
    LoadModule status_module      /usr/lib64/apache2-prefork/mod_status.so
    

    If these two lines exist , then the two modules have loaded successfully.

Use the following procedure to verify the server status and display the server information web page:

  1. Verify the server status by opening a browser and entering the following URL:

    http://<YOUR_WEB_SERVER_IP>/server-status

    The Apache Server Status web page opens, as shown in Figure 6.

    Figure 6 Apache Server Status

    Apache Server Status
  2. 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 7.

    Figure 7 Apache Server Information

    Apache Server Information

Apache HTTP Server Log

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/apache2

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/apache2/error_log

The following message is added to the end of the file:

[Sat Feb 03 13:03:55 2007] [error] [client 10.100.0.86] File does not exist: 
/srv/www/htdocs/non-exist
Using Webalizer to Perform Apache HTTP Server Log Analysis

Webalizer 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:

  1. Modify the Webalizer configuration file, /etc/webalizer.conf, by adding the following lines:

    LogFile       /var/log/apache2/access_log
    OutputDir     /srv/www/htdocs/webalizer
  2. Restart the Apache server by entering the following:

    # /etc/init.d/apache2 restart

  3. Run the Webalizer program to generate a report:

    # webalizer

    A message similar to the following appears:

    Webalizer V2.01-10 (Linux 2.6.16.21-0.8-smp) English
    Using logfile /var/log/apache2/access_log (clf)
    DNS Lookup (10): 1 addresses in 1.00 seconds, 1/sec
    Using DNS cache file dns_cache.db
    Creating output in /srv/www/htdocs/webalizer
    Hostname for reports is 'bl35p-16'
    Reading history file... webalizer.hist
    Generating report for February 2007
    Generating summary report
    Saving history information...
    307 records in 1.00 seconds, 307/sec

Verify that the server status configuration is correct by opening a browser and entering the following website:

http://<YOUR_WEB_SERVER_IP>/webalizer

Figure 8 shows an example of a Webalizer usage report web page.

Figure 8 Webalizer Usage Report

Webalizer Usage Report

For detailed information, see the Webalizer website at:

http://www.mrunix.net/webalizer/

Using Virtual Host Support

A 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:

  1. 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.

  2. Add the following line:

    <YOUR_WEB_SERVER_IP>  www.website1.com  www.website2.com
  3. Verify that both websites resolve to the same IP address by entering the following commands:

    # ping www.website1.com 
    # ping www.website2.com 
  4. Create the following two directories:

    /srv/www/htdocs/website1
    /srv/www/htdocs/website2
  5. Create the following file:

    /srv/www/htdocs/website1/index.html
  6. 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>
    
  7. Create the following file:

    /srv/www/htdocs/website2/index.html
  8. 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>
    
  9. Configure virtual hosting by creating a file named /etc/apache2/vhosts.d/vhosts.conf and adding the following lines:

    NameVirtualHost *:80
    
    <VirtualHost *:80>
    DocumentRoot /srv/www/htdocs/website1
    ServerName www.website1.com
    </VirtualHost>
    
    <VirtualHost *:80>
    DocumentRoot /srv/www/htdocs/website2
    ServerName www.website2.com
    </VirtualHost>
  10. Restart your Apache HTTP server for the changes to take effect.

  11. 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 Redirection

The 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.

  1. On the first server, create the following directory:

    /srv/www/htdocs/testdir
  2. On the second server, create the following HTML file:

    /srv/www/htdocs/test.html
  3. 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>
    
  4. Edit the following configuration file:

    /etc/apache2/default-server.conf

    Add the following line to the preceding file:

    Redirect permanent /testdir  http://<ANOTHER_WEB_SERVER_IP>/test.html
  5. Use the following command to restart your Apache HTTP server, for the preceding changes to take effect:

    # /etc/init.d/apache2 restart
  6. 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 Features

The 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.

  1. Start the Apache HTTP server on the first system.

  2. Modify the /etc/sysconfig/apache2 file by appending the following string to the APACHE_MODULES definition:

    proxy proxy_connect proxy_ftp proxy_http

    The APACHE_MODULES definition should now look like the following:

    APACHE_MODULES="actions alias auth_basic authn_file authz_host authz_groupfile authz_default authz_user authn_dbm autoindex cgi dir env expires include log_config mime negotiation setenvif ssl suexec userdir php5 info status proxy proxy_connect proxy_ftp proxy_http"
  3. On the second system, which acts as the Apache Proxy server, edit the following file:

    /etc/apache2/default-server.conf

    Add the following lines to the preceding file:

    ProxyRequests On
    ProxyVia On
    
    <Proxy *>
    		Order deny,allow
    		Deny from all
    		Allow from all
    </Proxy>
    
  4. Restart the Apache HTTP server, so the Apache Proxy server will take effect on the second system, by entering the following:

    # /etc/init.d/apache2 restart
  5. Using the benchmarking tool, test the Apache Proxy server using the third system, which acts as the web client:

    # ab2 -c 10 -n 10 -X <YOUR_PROXY_SERVER_IP>:80 \
    http://<YOUR_WEB_SERVER_IP>/test.html 
  6. View the access log file on the Apache Proxy server. Messages similar to the following are contained in the file:

    YOUR_WEB_BROSWER_IP - - [03/Feb/2007:13:30:48 -0500] "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 - - [24/May/2007:11:38:46 +0800] "GET /test.html HTTP/1.1" 200 206 "-" "ApacheBench/2.0.40-dev"

    These messages verify that the Apache Proxy server configuration is successful.

Error Responses and Redirects

The following three types of error responses can be customized and are addressed in this section:

  • Plain text

  • Local URL redirect

  • External URL redirect

Customizing Plain Text Responses

The following is an example of how to customize a plain text error response:

  1. Edit the following file:

    /etc/apache2/errors.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"
  2. Restart your Apache HTTP server for the changes take effect.

  3. 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 Responses

The following is an example for customizing a local URL redirect error message:

  1. Edit the following file:

    /etc/apache2/errors.conf

    In the preceding file, change (or add, if it does not exist already) the following line:

    ErrorDocument 404 "/missing.html"
  2. Create the following HTML file:

    /srv/www/htdocs/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>
    
  3. 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 Responses

The 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:

  1. Edit the following configuration file:

    /etc/apache2/errors.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
  2. Create the following HTML file:

    /srv/www/htdocs/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>
    
  3. 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 Directories

Using 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:

  1. Add a user named tester to your server by entering the following commands:

    # useradd -m tester
  2. 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>
    
  3. 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 9.

Figure 9 Connecting the Apache Web Server and Tomcat Web Container

Connecting the Apache Web Server and Tomcat Web Container

The following example provides the steps to configure Apache Web server routing requests under the DOCUMENT_ROOT/jsp-examples/ directory to the Tomcat server:

  1. 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:

    /usr/lib64/apache2/modules

  2. Edit the Apache Web server configuration file, /etc/apache2/default-server.conf, adding the following lines:

    #Load mod_jk
    LoadModule jk_module /usr/lib64/apache2/mod_jk.so
    #Configure mod_jk
    JkShmFile /var/log/apache2/memory.shm
    JkWorkersFile /etc/apache2/workers.properties
    JkLogFile /var/log/apache2/mod_jk.log
    JkLogLevel info
    
  3. Insert the following line below the DocumentRoot line:

    JkMount /jsp-examples/* worker1
  4. 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" />
  5. Create the following file:

    /etc/apache2/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
    
  6. If necessary, start Tomcat it by entering the following command:

    # $CATALINA_HOME/bin/startup.sh 
  7. Restart Apache by entering the following command:

    # /etc/init.d/apache2 restart
  8. 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 10 show an example of the JSP Examples page.

    Figure 10 JSP Examples Page to Test mod_jk

    JSP Examples Page to Test mod_jk

If there are any errors, check the following log files:

/var/log/apache2/error_log
/var/log/apache2/access_log
/var/log/apache2/mod_jk.log

Integrating the Apache Web Server and PHP

The 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:

  1. Verify that PHP is installed by entering the following command:

    # rpm -q php5 apache2-mod_php5

  2. Create the following test file:

    /srv/www/htdocs/test.php

    Add the following lines to the preceding file:

    <? 
    ## test.php 
    phpinfo(); 
    ?>
  3. 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 Perl

The apache2–mod_perl module integrates a Perl interpreter into the Apache Web server, allowing you to use Perl when creating web applications. Use the apache2–mod_perl module provided by the Linux distribution.

To test the installation, perform the following steps:

  1. Verify that the apache2–mod_perl module is installed by entering the following command:

    # rpm -q php5 apache2-mod_php5

  2. Create a sample file test file named /srv/www/cgi-bin/test.pl and add the following lines:

    #!/usr/bin/perl 
    print "Content-type: text/plain\n\n"; 
    print "Hello World!\n";
  3. Assign execute permissions to the file by entering the following command:

    # chmod +x /srv/www/cgi-bin/test.pl

  4. Edit the /etc/sysconfig/apache2 file by adding perl to the line with APACHE_MODULES.

    After completing this edit, the line should look like the following:

    APACHE_MODULES=”... ... perl”
  5. Restart Apache by entering the following command:

    # /etc/init.d/apache2 restart

If there are any errors, check the following log files:

/var/log/apache2/error_log
/var/log/apache2/access_log

Integrating the Apache Web Server and Python

The apache2–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 apache2–mod_python package provided by the Linux distribution.

  1. Verify that the apache2–mod_python module is installed by entering the following command:

    # rpm -q python apache2-mod_python
  2. Edit the /etc/sysconfig/apache2 file by adding python to the line with APACHE_MODULES.

    After completing this edit, the line should look like the following:

    APACHE_MODULES="... ... python"
  3. Create the following test file:

    /srv/www/htdocs/test.py

    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
  4. Edit the following file:

    /etc/apache2/conf.d/mod_python.conf

    Add the following lines to the preceding file:

    <Directory 
         AddHandler mod_python .py
    			PythonHandler test
    			PythonDebug On
    </Directory>
  5. Restart Apache by entering the following command:

    # /etc/init.d/apache2 restart
  6. Verify that Python works by opening a browser and navigating to:

    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/apache2/error_log
/var/log/apache2/access_log

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 11 depicts the connection between Tomcat and a database using JDBC.

Figure 11 Tomcat Connections Using JDBC

Tomcat Connections 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 MySQL

MySQL 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 Drivers

Perform the following steps on the Tomcat web server:

  1. Download the MySQL JDBC driver 5.0 from the MySQL website:

    http://dev.mysql.com/downloads/connector/j/5.0.html

  2. Unzip the downloaded packages by entering the following command:

    # tar zxf mysql-connector-java-<version>.tar.gz

  3. 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 Source

To create a data source binding for a JDBC driver, perform the following steps on the Tomcat web server:

  1. 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" />
  2. Start the Tomcat web server by entering the following command:

    # $CATALINA_HOME/bin/startup.sh

Configuring the MySQL Server

To configure the MySQL database, perform the following steps on the MySQL server:

  1. 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

  2. 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.

  3. 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 Connectivity

To test the connectivity between Tomcat and MySQL, perform the following steps on the Tomcat web server:

  1. 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>
  2. If needed, start Tomcat by entering the following command:

    # $CATALINA_HOME/bin/startup.sh

  3. 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 12.

    Figure 12 Tomcat Connecting MySQL Test Page

    Tomcat Connecting MySQL Test Page

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 Driver

Perform the following steps from the Tomcat Web server:

  1. Download the JDBC driver for Oracle 10g Release 2 from the Oracle website at:

    http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html

    NOTE: For the Oracle JDBC driver with JDK 1.4 and 1.5, use the ojdbc14.jar file.
  2. Copy the JDBC driver to the Tomcat environment by entering the following command:

    # cp ojdbc14.jar $CATALINA_HOME/common/lib

Creating an Oracle Data Source

To 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 Server

Perform the following steps on the Oracle Database server:

  1. Verify that the Oracle server and the listener are running by entering the following command:

    # lsnrctl status

  2. 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 Connectivity

Test the connectivity between the Tomcat server and the Oracle database by performing the following steps on the Tomcat Web server:

  1. 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>
  2. If the Tomcat Web server is not running, start it by entering the following command:

    # $CATALINA_HOME/bin/startup.sh

  3. Verify that the Oracle test page is displayed (Figure 13 ) by opening a browser and navigating to the following website:

    http://<YOUR_HOSTNAME>:8080/oracleTest.jsp

    Figure 13 Oracle Database Test

    Oracle Database Test

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.

Installing Hibernate, Tomcat, and JDK

Download the Hibernate package, including tools, from the Hibernate website and install it using the instructions provided. See Table 1 for the correct version and website link.

Verify that you have installed and configured both Sun JDK and Tomcat before proceeding. For additional information, see “Installing and Configuring Tomcat”.

Configuring a Database Driver in Tomcat

Verify 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 Databases

In 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:

  1. Log in to the MySQL command line tool by entering the following command:

    # mysql -u root -p <PASSWORD>

  2. 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> );

  3. 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:

  1. Log in to Oracle using the user name osmsusr and password osmspass by entering the following command:

    # sqlplus osmsusr/osmspass@osmsdb_ora

  2. In the Oracle database identified by the Oracle SID, osmsdb_ora, create a table named USERS, and then sequence with the osmsusr user by entering the following commands:

    SQL> Create sequence hibernate_sequence start with 10 increment by 1 min value 10 maxvalue 999999999999;

    SQL> Create table USERS ( user_id number(10) not null, first_name varchar(30) not null, last_name varchar2(30) not null);

    SQL> Alter table USERS add ( constraint user_primary_key primary key(user_id) using index);

    NOTE: The Oracle sequence, HIBERNATE_SEQUENCE, is used to generate a primary key for the table named USERS.

Creating a Simple Application in Tomcat

You 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:

  1. 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

  2. Configure the MySQL or Oracle data source by creating a file named $CATALINA_HOME/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.

  3. 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
  4. 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.
  5. 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/hibernate/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;
    	}
    }
  6. 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.

  7. 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>
  8. 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;
        }
       }
  9. 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:

    # javac Users.java

    The preceding command creates a class file named: $CATALINA_HOME/webapps/SimpleDemo/WEB-INF \ /classes/com/hp/osms/hibernate/Users.class

  10. 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.setFirstName("Smith");
    	      users.setLastName("Barney");
       	           
    	      hbsession.save(users);
    	      hbsession.flush();
    		tx.commit();
    
    	}catch(HibernateException he){
    				he.printStackTrace();
    }finally
    { 
    if(hbsession!=null) 
    HibernateSessionFactory.closeSession(); 
    }