YoLinux Tutorial: Java Servlets, JSP, Jakarta-Tomcat, a Database (PostgreSQL or MySQL), Apache and Linux

This covers dynamic content using JAVA servlets, JAVA Server Pages (JSP and JASPER page compiler), Jakarta-Tomcat, Apache and a Database (PostgreSQL or MySQL) on Red Hat Linux 7.2. A configuration presented here will allow one to make a web request to the Apache web server which will recognize it as request for a servlet to be handled by Tomcat. Tomcat, the Java Servlet and JSP engine, will execute the Java Servlet which will use JDBC to access a database (PostgreSQL or MySQL). The servlet will dynamically generate a web page based on the results of the database query and will provide these results to Apache which will deliver the web content back to the requesting browser.

Instead of using C/C++ or PERL for a CGI back-end web server process, one may use JAVA servlets processed by the Jakarta project's "Tomcat". Apache will be configured to use the module mod_jk to communicate with Jakarta-Tomcat and it's JVM (JAVA virtual machine). Servlet programs are written as JAVA classes which inherit from "HttpServlet" to provide much of their principal function.

JAVA Server Pages (JSP) will utilize Tomcat's JASPER page compiler to generate dynamic web pages based on custom tags in one's HTML pages which are processed and served. These pages use the tag "<% %>" to denote JSP directives to be dynamically processed.

It has been my experience on this project that the configurations for the versions of software discussed here are very specific to the release. In this case we will be using Tomcat 4.0. Older releases of Tomcat (version 3) are configured differently. These versions of Tomcat and Apache can also be installed on newer releases of the operating system.

An example of a Java Servlet using JDBC to access a database (PostgreSQL or MySQL) is also covered.

Contents:
Note: Make sure your computer has massive amounts of memory!!!!

Related YoLinux Tutorials:

°Java on Linux

°Java WAR files

°IBM Websphere

°YoLinux Tutorials Index





Free Information Technology Magazines and Document Downloads
TradePub link image


   

    Bookmark and Share


Advertisements




JAVA Installation/Configuration:

In order to write and compile a JAVA programs, applets or servlets one must download the JAVA Development Kit (JDK) which provides a compiler, class libraries and tools to compile and run JAVA code. In this tutorial we will use the Sun JDK but I'm sure any will do. See YoLinux JAVA for a list of available JDK's for Linux.

Download the Sun JDK:

Note: The Java Runtime Environment (JRE) will be adequate to configure the server environment but the Software Development Kit (SDK) is required if one wants to write and compile JAVA programs. The "Forte SDK" is a full blown interactive GUI driven development environment. The SDK is available in RPM and tar format.

  • Download j2sdk-1_4_0-linux-i386-rpm.bin
  • chmod +x j2sdk-1_4_0-linux-i386-rpm.bin
  • ./j2sdk-1_4_0-linux-i386-rpm.bin
  • rpm -ivh j2sdk-1_4_0-fcs-linux-i386.rpm

SDK installed in /usr/java/latest/.

Configuration:

Set the environment variable PATH. Add statement to $HOME/.bash_profile or $HOME/.bashrc or shell script which controls the environment.
PATH=/usr/java/j2sdk1.4.0/bin:$PATH
export PATH
export JAVA_HOME=/usr/java/j2sdk1.4.0
export CLASSPATH=/usr/java/j2sdk1.4.0/lib/tools.jar:/usr/java/j2sdk1.4.0/jre/lib/rt.jar
The shell script may be re-executed with the command: . .bashrc

[Potential Pitfall]: Java SDK 1.4.0_03 now requires the current working directory to be listed to find files. Add reference to current directory ":./" to CLASSPATH.

   export CLASSPATH=/usr/java/j2sdk1.4.0_03/lib/tools.jar:/usr/java/j2sdk1.4.0_03/jre/lib/rt.jar:./

Test:

Use the following test program: Test.java
public class Test
{
public static void main(String[] args)
{
System.out.println("Hello world");
}
}
Compile: javac Test.java
(or /usr/java/j2sdk1.4.0/bin/javac Test.java)
Note that the file name and the class name are the same. This became a requirement in JDK 1.4. The result of the compile is the file: Test.class

Run:

[prompt]$ java Test
Hello world
(or /usr/java/j2sdk1.4.0/bin/java Test)

Links:


Jakarta Project - Tomcat:

Tomcat is the JAVA "container" or processor for Java Servlets and Java Server Pages (JSP). Note also that JAVA must be installed in order for Tomcat to operate. (See previous section above) This tutorial will focus on the use of Tomcat with Apache but it should be noted that the default Tomcat installation enables Tomcat to be a stand-alone http web server and servlet container.

Apache Tomcat JAVA Servlet and JSP container home page

Download: Tomcat 4.0 (Release: Catalina. Servlet 2.3 and JSP 1.2 specifications.)

  • regexp-1.2-1.noarch.rpm
  • servletapi4-4.0.3-1.noarch.rpm - servlet.jar files
  • xerces-j-1.4.4-1.noarch.rpm - Xerces is an XML parser available from the Apache Software Foundation.
  • tomcat4-webapps-4.0.3-1.noarch.rpm
  • tomcat4-4.0.3-1.noarch.rpm
Install: rpm -ivh regexp-1.2-1.noarch.rpm servletapi4-4.0.3-1.noarch.rpm tomcat4-webapps-4.0.3-1.noarch.rpm tomcat4-4.0.3-1.noarch.rpm xerces-j-1.4.4-2.noarch.rpm

Symlinks generated from /usr/share/java/... to /var/tomcat4/

Documentation:

Config file: /etc/tomcat4/conf/tomcat4.conf

Change the following reference to JAVA_HOME to:
JAVA_HOME=/usr/java/j2sdk1.4.0
Notes:
  • JAVA environment variable seem to be set here rather than in a start script.
  • Environment variable options:
    • CATALINA_HOME: Tomcat installation directory
    • CATALINA_OPTS example: export CATALINA_OPTS="-Djava.ext.dirs=/dummy_dir"
      Command line switches to pass to the Java Runtime Environment
    • CLASSPATH: Optional - Runs without this but I used it when adding custom JAR files (CLASSPATH=$CLASSPATH:/var/tomcat4/lib:/usr/share/pgsql:/usr/java/jre/lib:/usr/java/j2sdk1.4.0/lib:)
  • Tomcat will execute as user tomcat4

Config files:

  • /var/tomcat4/conf/server.xml - Servlet container configuration: Defines services offered, TCP port numbers for services, SSL, JDBC configuration for MySQL (user/passwd), PostgreSQL, Oracle, ODBC, etc. Later we will configure Apache to use one of these services.
  • /var/tomcat4/conf/web.xml - Tomcat's built-in http server global config file: Defines servlets to be processed by Tomcat. Some are predefined to perform pre-configured tasks like SSI, JSP, etc.
  • /var/tomcat4/conf/catalina.policy - Security policy permissions for Tomcat
  • /var/tomcat4/webapps/examples/WEB-INF/web.xml - Application specific config file.
Later we will use Tomcat with Apache's http server.

Start: service tomcat4 start (or: /etc/init.d/tomcat4 start)

Or execute init script directly: /etc/rc.d/init.d/tomcat4 start
To add to init boot process: /sbin/chkconfig --add tomcat4
Tomcat (and listener socket waiting for requests) will start before Apache so that Apache will have a socket to which it can connect and communicate. Tomcat will also stop after Apache. Have patience as there is a lot of stuff going on. Use the command top to look at all the JAVA processes being initiated. When the top processes are no longer Java, then Tomcat is probably ready.

[Potential Pitfall]: Note that the command service tomcat4 stop was not always successful in stopping all Java processes. Use the command ps -auwx | grep tomcat to measure success.

Test:

Note:
  • Port 8180 is defined in /var/tomcat4/conf/server.xml.
    If changed you must restart Tomcat: service tomcat4 restart (or: /etc/init.d/tomcat4 restart)
    If using stand-alone and not with Apache, change this to port 80.
    <Connector className="org.apache.catalina.connector.http.HttpConnector"
                   port="8180" minProcessors="5" maxProcessors="75"
                   enableLookups="true" redirectPort="8543"
                   acceptCount="10" debug="0" connectionTimeout="60000"/>
                      
  • Tomcat includes an http server which this test is using. We will be integrating it into the Apache environment so that Apache will be the default server and Tomcat will be processing JSP's and Servlets.
  • Tomcat Log files: /var/tomcat4/logs/
  • Application directories:
    • Servlets and utility classes: /var/tomcat4/webapps/examples/WEB-INF/classes/
    • JAR files and JDBC drivers: /var/tomcat4/webapps/examples/WEB-INF/lib/
Tomcat Manager:
Tomcat comes with a web management interface. (It's weak, so don't expect much.)
The access is controlled by the file /var/tomcat4/conf/tomcat-users.xml Add a manager definition in tomcat-users.xml:
<tomcat-users>
<user name="tomcat" password="tomcat" roles="tomcat" />
<user name="role1"  password="tomcat" roles="role1"  />
<user name="both"   password="tomcat" roles="tomcat,role1" />
<user name="admin1" password="supersecret" roles="standard,manager,tomcat,role1" />   - Added this line with "manager role"
<user name="admin2" password="supersecret2" roles="admin,manager,provider" />
</tomcat-users>
    
Then restart: service tomcat4 restart

Use URL to list web applications: http://localhost:8180/manager/list

Note:

Notes:

  • The rpm tomcat4-webapps-4.0.3-1.noarch.rpm will install many examples (JAVA source .java and compiled .class) in /var/tomcat4/webapps/.
  • If all you are running are static web pages, JSP and servlets then all you may need is Tomcat as it is an http server. If you need the functionality of Apache to execute CGI, php and support for many of the Apache features then read ahead to learn how to use Apache to invoke Tomcat to support JSP and Java Servlets.


JAVA Servlet Example:

File: MyHelloWorld.java

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyHelloWorld extends HttpServlet {

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello World!</h1>");
out.println("</body>");
out.println("</html>");
}
}
Create Source File: /var/tomcat4/webapps/examples/WEB-INF/classes/MyHelloWorld.java

Set CLASSPATH environment variable:

export CLASSPATH=$CLASSPATH:/var/tomcat4/common/lib/servlet.jar

OR export CLASSPATH=/usr/java/j2sdk1.4.0/lib/tools.jar:/usr/java/j2sdk1.4.0/jre/lib/rt.jar:/var/tomcat4/common/lib/servlet.jar
Note: /var/tomcat4/common/lib/servlet.jar is soft linked to /usr/share/java/servlet-2.3.jar.

Compile:

[prompt]$ cd /var/tomcat4/webapps/examples/WEB-INF/classes/
[prompt]$ javac MyHelloWorld.java

(OR /usr/java/j2sdk1.4.0/bin/javac MyHelloWorld.java )
This creates file: /var/tomcat4/webapps/examples/WEB-INF/classes/MyHelloWorld.class

Note:

  • Java class com.mycompany.mypackage.MyServlet would be stored in /WEB-INF/classes/com/mycompany/mypackage/MyServlet.class
  • Libraries (JAR files, JDBC drivers, etc) held in /WEB-INF/lib/ if one follows standard configuration. (I took the easy path instead.)

Tomcat Test: http://localhost:8180/examples/servlet/MyHelloWorld
Don't expect a lot. It just generates a web page dynamically which states "Hello World".

Note:

  • The mapping of path /var/tomcat4/webapps/examples/WEB-INF/classes/ to the URL /examples/servlet/ is defined in /var/tomcat4/conf/web.xml. Look for the XML tag "<servlet-mapping>".
  • Many examples with source code are included with Tomcat. See: http://localhost:8180/examples/servlets/index.html


Apache - Tomcat Configuration:

Apache is a fast and configurable web server. This section covers using Apache as the primary web server but using Tomcat to process JSP and Servlets. This configuration uses the AJP (Apache JServ Protocol) connector element (mod_jk) to perform this task. The Apache module mod_jk will send servlet requests to Tomcat using TCP/IP sockets for communications. Module mod_jk works with Tomcat versions 3.x and 4.x.

There are numerous Apache connection modules:

Connector Name Apache Module Name Connection Protocol Tomcat Version
AJP mod_jk AJP1.2,AJP1.3 3, 4
Coyote JK2 mod_jk AJP/JK1.3,AJP/JK1.4 4.1
WARP mod_webapp WARP 4
JSERV mod_jserv ?? old


AJP mod_jk Installation:

  • First check to see if Apache is compiled to support DSO: /usr/sbin/httpd -l
    If one of the lines contains the result mod_so.c then support is available.

  • Download mod_jk RPM: http://jakarta.apache.org/builds/jakarta-tomcat-4.0/release/v4.0.3/rpms/mod_jk-1.3-1.0-1.4.0.2.i386.rpm
    This module is dependent on the version of Apache one is using. For this tutorial I am using Apache 1.3.

  • Download EAPI version of mod_jk: http://jakarta.apache.org/builds/jakarta-tomcat/release/v3.3/bin/linux/i386/mod_jk-3.3-ap13-eapi.so
    The default Red Hat compiled Apache uses an API called EAPI which is incompatible with the version of mod_jk.so included in the RPM. Download and rename as /usr/lib/apache/mod_jk.so. This will overwrite the version installed by the RPM. The RPM is still required for the configuration files.

  • Or build mod_jk from source: http://jakarta.apache.org/builds/jakarta-tomcat-4.0/release/v4.0.3/src/jakarta-tomcat-connectors-4.0.2-01-src.tar.gz
    • Unpack: tar -xzf jakarta-tomcat-connectors-4.0.2-01-src.tar.gz
    • cd jakarta-tomcat-connectors-4.0.2-01-src/jk/native/apache-1.3/
    • Edit script: build-unix.sh
      Change lines:
      • JAVA_HOME=/usr/java/j2sdk1.4.0
      • APACHE_HOME=/etc/httpd
      • APXS=/usr/sbin/apxs
      • cp mod_jk.so /usr/lib/apache
    • Compile: . build-unix.sh

Configuration File Modifications:

The configuration file changes discussed below relate to those released with the RPM mod_jk-1.3-1.0-1.4.0.2.i386.rpm.
  • Define TCP/IP ports will be used for communications between Apache and Tomcat.
    • See Tomcat-Apache config file: /etc/httpd/conf/workers.properties
      (A separate host may also be specified.) (If you are defining multiple JVM's/servlet processors, used in virtual hosting, each must be assigned a different port.)
    • Tomcat services are defined in /var/tomcat4/conf/server.xml (See "Connector" definition) and in the Apache include file mod_jk.conf. Resource parameters may also be set to control the maximum number of threads which can be spawned.
  • Apache configuration to define:
    • module to load for communication with Tomcat. (Add to httpd.conf)
    • path (URL of servlets) and/or file types (JSP file types) which are destined for Tomcat processing. All requests in the given path (servlet location) or request of a given file type (i.e. *.jsp) will then be processed by Tomcat. (See JkMount directive in Apache include file mod_jk.conf) Everything else is served by Apache.

Modify: /etc/httpd/conf/workers.properties

workers.tomcat_home=/var/tomcat4             - Changed. Default was /var/tomcat3
workers.java_home=/usr/java/j2sdk1.4.0       - Changed to reflect location of JDK
ps=/
worker.list=ajp12, ajp13

# Define a worker named ajp12 and of type ajp12
# Note that the name and the type do not have to match.
#
worker.ajp12.port=8007
worker.ajp12.host=localhost
worker.ajp12.type=ajp12
worker.ajp12.lbfactor=1

# Define a worker named Ajp13 # worker.ajp13.port=8009 worker.ajp13.host=localhost worker.ajp13.type=ajp13 worker.ajp13.lbfactor=1 worker.loadbalancer.type=lb worker.loadbalancer.balanced_workers=ajp12, ajp13 # Defining a worker named inprocess and of type jni worker.inprocess.type=jni # Additional class path components. worker.inprocess.class_path=$(workers.tomcat_home)$(ps)server$(ps)lib$(ps)tomcat-ajp.jar - Changed this line to match location of library. worker.inprocess.cmd_line=start worker.inprocess.class_path=$(workers.java_home)$(ps)lib$(ps)tools.jar - This line based on something I read. (Also modified to match installation) # Unix - Sun VM worker.inprocess.jvm_lib=$(workers.java_home)$(ps)jre$(ps)lib$(ps)i386$(ps)server$(ps)libjvm.so - Changed this line to match location of library. # Setting the place for the stdout and stderr of tomcat worker.inprocess.stdout=$(workers.tomcat_home)$(ps)logs$(ps)inprocess.stdout worker.inprocess.stderr=$(workers.tomcat_home)$(ps)logs$(ps)inprocess.stderr
The effect of this configuration is to define socket listeners and communication protocols between Apache and Tomcat.

Add to: /var/tomcat4/conf/server.xml

Within the XML tags:
<Service name="Tomcat-Standalone">
...
</Service>
Define listener:
    <Connector className="org.apache.ajp.tomcat4.Ajp13Connector"
port="8007" minProcessors="5" maxProcessors="75"
acceptCount="10" debug="0"/>

<Connector className="org.apache.ajp.tomcat4.Ajp13Connector"
port="8009" minProcessors="5" maxProcessors="75"
acceptCount="10" debug="0"/>
Add definitions for connectors on ports 8007 and 8009 for workers.
For some reason the listener definition has no effect within the "Service" tag identified as "Tomcat-Apache". (I don't know why)

Add to: /etc/httpd/conf/httpd.conf

LoadModule jk_module /usr/lib/apache/mod_jk.so
OR
LoadModule jk_module         modules/mod_jk.so
...
...
AddModule mod_jk.c
...
...
Include /etc/httpd/conf/mod_jk.conf
                
Notes:
  • I added the "LoadModule" statement after the list of all the other "LoadModule" statements.
  • The statement "AddModule mod_jk.c" is placed after the line "ClearModuleList" and after all the "AddModule" declarations. Why? I don't know why position is important, but when listed as the first "AddModule" entry after "ClearModuleList", it would not work.
  • The statement modules/mod_jk.so is a relative reference from /etc/httpd/. The directory /etc/httpd/modules/ is soft linked to /usr/lib/apache/

File: /etc/httpd/conf/mod_jk.conf (Change references of "tomcat" to "tomcat4" throughout the file, otherwise the default file is ok.)

<IfModule mod_jk.c>

JkWorkersFile /etc/httpd/conf/workers.properties
JkLogFile /var/log/httpd/mod_jk.log
JkLogLevel info

# Root context mounts for Tomcat
# Format: JkMount URL_PREFIX WORKER_NAME JkMount /*.jsp ajp13 JkMount /servlet/* ajp13 # The following line makes apache aware of the location of the /examples contextAlias /examples "/var/tomcat4/webapps/examples"
<Directory "/var/tomcat4/webapps/examples">
Options Indexes FollowSymLinks
</Directory>

# The following line mounts all JSP files and the /servlet/ uri to tomcat
JkMount /examples/servlet/* ajp13
JkMount /examples/*.jsp ajp13

# The following line prohibits users from directly access WEB-INF
<Location "/examples/WEB-INF/">
AllowOverride None
deny from all
</Location>

...

</IfModule>

Virtual host example: (Just an FYI. I never used virtual hosting but wanted to let everyone know it is available.)

Configure a new JVM definition to handle requests separately.
# First Virtual Host.           - Virtual Host example not in default file

<VirtualHost 10.0.0.1:80>
DocumentRoot /web/host1
ServerName host1.yolinux.com
<IfModule mod_jk.c>
JkMount /*.jsp ajp13
JkMount /servlet/* ajp13
<Location "/examples/WEB-INF/">
    AllowOverride None
    deny from all
</Location>
</IfModule>
</VirtualHost>
          
Ajpv13 is the protocol used when Apache communicates with Tomcat. This file establishes the sockets and enables this communication process.

If using a virtual host configuration then file /etc/httpd/conf/workers.properties must have the following entries added:

...
<!-- Request Interceptor for jumpers -->
<RequestInterceptor
className="com.yolinux.servlet.jumpersInterceptor" />
...
<Host name="host1.yolinux.com" >
<Context path=""
docBase="/web/host1/html" />
</Host>

Run:

  • Start Tomcat first: service tomcat4 start
  • Start Apache: service httpd start
    After Apache has started, one may perform a syntax check of the Apache configuration files with the following command:
    [root prompt]# /usr/sbin/apachectl configtest
    If sucessful it should return the statement: Syntax OK
    [Potential Pitfall]: If you get the following error:
    [error] Cannot remove module mod_jk.c: not found in module list
    It is most likely that the placement of the aditional lines in /etc/httpd/conf/httpd.conf is incorrect. The additional lines must be placed accoring to above directions.
  • Test with the URL: Note that we are no longer referencing port 8180 but are referencing a directory which Apache defers to Tomcat for processing but Apache handles the request from the browser.

Log Files:

  • Apache:
    • /var/log/httpd/access_log
    • /var/log/httpd/error_log
  • Tomcat: /var/tomcat4/logs/...
  • Apache-Tomcat module mod_jk: /var/log/httpd/mod_jk.log

Links:


The Database:

We will cover connectivity to two databases:

  1. PostgreSQL
  2. MySQL
Note: If connecting to Oracle, use the JDBC driver: oracle.jdbc.driver.OracleDriver


1) PostgreSQL:

Install and configure a database. See: YoLinux Tutorial: PostgreSQL and Linux

JDBC and PostgreSQL JAR files: The "CLASSPATH" variable can set the Java runtime environment so that it will find the appropriate Java libraries (JAR files). Environment variables for Tomcat can be set in /etc/tomcat4/conf/tomcat4.conf. One may also set the CLASSPATH variable to include PostgreSQL JDBC JAR files. I did not set the CLASSPATH environment variable in the configuration file but instead employed the default path by performing the following steps:

List of PostgreSQL JDBC drivers:

[prompt]# rpm -ql postgresql-jdbc-7.1.3-2
/usr/share/pgsql/jdbc7.0-1.1.jar
/usr/share/pgsql/jdbc7.1-1.2.jar

Place JDBC JAR libraries in path where they can be found:

cp /usr/share/pgsql/jdbc7.1-1.2.jar /var/tomcat4/lib

JAVA Servlet run under Tomcat, accessing PostgreSQL using JDBC:

Java Servlet source file:
// File: ShowBedrock.java

/* A servlet to display the contents of the PostgreSQL Bedrock database */

import java.io.*;
import java.sql.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ShowBedrock extends HttpServlet 
{
    public String getServletInfo()
    {
       return "Servlet connects to PostgreSQL database and displays result of a SELECT";
    }

    private Connection dbcon;  // Connection for scope of ShowBedrock

    // "init" sets up a database connection
    public void init(ServletConfig config) throws ServletException
    {
        String loginUser = "postgres";
        String loginPasswd = "supersecret";
        String loginUrl = "jdbc:postgresql://localhost/bedrock";

        // Load the PostgreSQL driver
        try 
        {
              Class.forName("org.postgresql.Driver");
              dbcon = DriverManager.getConnection(loginUrl, loginUser, loginPasswd);
        }
        catch (ClassNotFoundException ex)
        {
               System.err.println("ClassNotFoundException: " + ex.getMessage());
               throw new ServletException("Class not found Error");
        }
        catch (SQLException ex)
        {
               System.err.println("SQLException: " + ex.getMessage());
        }
    }

    // Use http GET

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");    // Response mime type

        // Output stream to STDOUT
        PrintWriter out = response.getWriter();

        out.println("<HTML><Head><Title>Bedrock</Title></Head>");
        out.println("<Body><H1>Bedrock</H1>");
	    
        try
        {
                // Declare our statement
                Statement statement = dbcon.createStatement();

                String query = "SELECT name, dept, ";
                query +=       "       jobtitle ";
                query +=       "FROM   employee ";

                // Perform the query
                ResultSet rs = statement.executeQuery(query);

                out.println("<table border>");

                // Iterate through each row of rs
                while (rs.next())
                {
                   String m_name = rs.getString("name");
                   String m_dept = rs.getString("dept");
                   String m_jobtitle = rs.getString("jobtitle");
                   out.println("<tr>" + 
                               "<td>" + m_name + "</td>" +
                               "<td>" + m_dept + "</td>" +
                               "<td>" + m_jobtitle + "</td>" +
                               "</tr>");
                }

                out.println("</table></body></html>");
                statement.close();
        }
        catch(Exception ex)
        {
                out.println("<HTML>" +
                            "<Head><Title>" +
                            "Bedrock: Error" +
                            "</Title></Head>\n<Body>" +
                            "<P>SQL error in doGet: " +
                            ex.getMessage() + "</P></Body></HTML>");
                return;
        }
        out.close();
    }
}
                

Notes:

  • String loginUrl = "jdbc:postgresql://localhost/bedrock";
    The format for this is jdbc:postgresql:host-name-of-server:port/database-name
    Examples:
    • jdbc:postgresql:bedrock - bedrock is the PostgreSQL database name. See PostgreSQL tutorial.
    • jdbc:postgresql://localhost/bedrock
    • jdbc:postgresql://localhost:5432/bedrock - Default PostgreSQL standard port number is 5432
  • public void doGet(...
    Using http GET request. For http POST operations use doPost
  • String m_name = rs.getString("name");
    One may also use database field names or field numbers. i.e.
    String m_name = rs.getString(1);
    String m_dept = rs.getString(2);

Set CLASSPATH environment variable:

export CLASSPATH=$CLASSPATH:/var/tomcat4/lib/jdbc7.1-1.2.jar

OR export CLASSPATH=/usr/java/j2sdk1.4.0/lib/tools.jar:/usr/java/j2sdk1.4.0/jre/lib/rt.jar:/var/tomcat4/common/lib/servlet.jar:/var/tomcat4/lib/jdbc7.1-1.2.jar

Compile:

[prompt]# cd /var/tomcat4/webapps/examples/WEB-INF/classes
[prompt]# javac ShowBedrock.java

(OR /usr/java/j2sdk1.4.0/bin/javac ShowBedrock.java )
PostgreSQL Configuration: /var/lib/pgsql/data/postgresql.conf
Set: tcpip_socket = true
This allows JDBC to connect to PostgreSQL.

Test:

Results:

Bedrock

Fred Flinstone Quarry Worker Rock Digger
Wilma Flinstone Finance Analyst
Barney Rubble Sales Neighbor
Betty Rubble IT Neighbor


JDBC/PostgreSQL Links:


2) MySQL:

Install and configure a database: YoLinux Tutorial: MySQL and Linux

Download JDBC MM.MySQL JAR file:

  • MM.MySQL Downloads
  • sourceforge.net: mm.mysql-2.0.13-you-must-unjar-me.jar - Actual JAR file I used

Un-JAR and place MM.MySQL JDBC JAR libraries in path where they can be found:

[prompt]# /usr/java/j2sdk1.4.0/bin/jar xf mm.mysql-2.0.13-you-must-unjar-me.jar
OR if your paths are set properly:
[prompt]# jar xf mm.mysql-2.0.13-you-must-unjar-me.jar

[prompt]# cd mm.mysql-2.0.13/
[prompt]# cp mm.mysql-2.0.13-bin.jar /var/tomcat4/lib
"GRANT ALL PRIVILEGES ON bedrock to 'user@hostname' identified by 'password';
FLUSH PRIVILEGES

where hostname is localhost.localdomain (not localhost on default Red Hat installation)

JAVA Servlet run under Tomcat, accessing MySQL using JDBC:

Java Servlet source file: (Note that it does the same thing as the PostgrSQL example above but it is written with a different style.)
// File: ShowBedrock.java

/* A servlet to display the contents of the MySQL Bedrock database */

import java.io.*;
import java.net.*;
import java.sql.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ShowBedrock extends HttpServlet
{
public String getServletInfo()
{
return "Servlet connects to MySQL database and displays result of a SELECT";
}

// Use http GET

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
String loginUser = "Dude1";
String loginPasswd = "SuperSecret";
String loginUrl = "jdbc:mysql://localhost:3306/bedrock";

response.setContentType("text/html"); // Response mime type

// Output stream to STDOUT
PrintWriter out = response.getWriter();

out.println("<HTML><HEAD><TITLE>Bedrock</TITLE></HEAD>");
out.println("<BODY><H1>Bedrock</H1>");

// Load the mm.MySQL driver
try
{
Class.forName("org.gjt.mm.mysql.Driver");
Connection dbcon = DriverManager.getConnection(loginUrl, loginUser, loginPasswd);
// Declare our statement
Statement statement = dbcon.createStatement();

String query = "SELECT name, dept, ";
query += " jobtitle ";
query += "FROM employee ";

// Perform the query
ResultSet rs = statement.executeQuery(query);

out.println("<TABLE border>");

// Iterate through each row of rs
while (rs.next())
{
String m_name = rs.getString("name");
String m_dept = rs.getString("dept");
String m_jobtitle = rs.getString("jobtitle");
out.println("<tr>" +
"<td>" + m_name + "</td>" +
"<td>" + m_dept + "</td>" +
"<td>" + m_jobtitle + "</td>" +
"</tr>");
}

out.println("</TABLE>");

rs.close();
statement.close();
dbcon.close();
}
catch (SQLException ex) {
while (ex != null) {
System.out.println ("SQL Exception: " + ex.getMessage ());
ex = ex.getNextException ();
} // end while
} // end catch SQLException

catch(java.lang.Exception ex)
{
out.println("<HTML>" +
"<HEAD><TITLE>" +
"Bedrock: Error" +
"</TITLE></HEAD>\n<BODY>" +
"<P>SQL error in doGet: " +
ex.getMessage() + "</P></BODY></HTML>");
return;
}
out.close();
}
}
Compile:
[prompt]# export CLASSPATH=/var/tomcat4/common/lib/mm.mysql-2.0.13-bin.jar:$CLASSPATH
[prompt]# cd /var/tomcat4/webapps/examples/WEB-INF/classes
[prompt]# javac ShowBedrock.java

(ORexport CLASSPATH=/usr/java/j2sdk1.4.0/lib/tools.jar:/usr/java/j2sdk1.4.0/jre/lib/rt.jar:/var/tomcat4/common/lib/servlet.jar:/var/tomcat4/lib/mm.mysql-2.0.13-bin.jar )
(OR /usr/java/j2sdk1.4.0/bin/javac ShowBedrock.java )

Test:

Notes:

  • [Potential Pitfall]: The MySQL "user" table will define users and their host. I made the mistake of using "localhost" when the host name returned by the Unix command "hostname" was different. When the servlet tried to connect to the database it was refused.
    [prompt]$ hostname
    superserver [prompt]$ mysql -h localhost -u root -p
    ...
    mysql> use mysql
    mysql> select user,host from user;
    +-------+------------+
    | user | host |
    +-------+------------+
    | root | |
    | Dude1 | localhost |
    +-------+------------+
    mysql> update user set Host='superserver' where User='Dude1';
    Query OK, 1 row affected (0.00 sec)
    Rows matched: 1 Changed: 1 Warnings: 0


Links:


JAVA JDBC:

JAVA JDBC programs require the package: java.sql. Contained within this package are:

  • Classes:
    • Date
    • DriverManager
    • DriverPropertyInfo
    • Time
    • Timestamp
    • Types
  • Interfaces:
    • CallableStatement
    • Connection
    • DatabaseMetaData
    • Driver
    • PreparedStatement
    • ResultSet
    • ResultMetaData
    • Statement

JDBC Links:


JAVA Server Pages (JSP):

Basic JSP elements:

  • <jsp: ... %> : Define/execute Java statements.
    Example:
       
       Year: is  <jsp:getProperty name="clock" property="year"/>
       <BR>
       Month: is  <jsp:getProperty name="clock" property="month"/>
        
  • <% ... %> : Execute Java statements. Nothing displayed.
    Example: <% numguess.reset(); %>
  • <%= ... %> : Execute Java expression and place results here.
    Example: Calendar:<%= table.getDate() %>
  • <%@ ... %> : Declare Java variable or method.
    Example:
       <%@ page language="java" import="cal.*" %>
    <jsp:useBean id="table" scope="session" class="cal.TableBean" />
JSP's are rarely self contained. JSP's most often require use of classes and methods defined in Java programs.

The samples delivered with Tomcat show numerous JSP examples and the source code:


Links:


Books:

"Core Java 2, Volume 1: Fundamentals "
by Cay S. Horstmann, Gary Cornell
ISBN # 0130894680, Prentice Hall PTR

The industry standard. Need I say more?

Amazon.com
"Distributed Java 2 Platform Database Development "
by Stewart Birnam
ISBN # 0130268615, Prentice Hall PTR

The industry standard. Need I say more?

Amazon.com
"Core Servlets and JavaServer Pages (JSP) "
by Marty Hall
ISBN # 0130893404, Prentice Hall

Amazon.com
"More Servlets and JavaServer Pages (JSP) "
by Marty Hall
ISBN # 0130676144, Prentice Hall

Amazon.com
Tomcat: The Definitive Guide
by Jason Brittain, Ian F. Darwin
ISBN # 0596003188 O'Reilly & Associates; 1st Edition edition

Amazon.com
"Professional Apache Tomcat"
by Chanoch Wiggers, Ben Galbraith, Vivek Chopra, Sing Li, Debashish Bhattacharjee, Amit Bakore, Romin Irani, Sandip Bhattacharya, Chad Fowler
ISBN # 0764543725 Wrox

Amazon.com
Apache Jakarta-Tomcat
by James Goodwill
ISBN # 1893115364, APress

Amazon.com
Apache Tomcat Security Handbook
by Vivek Chopra, Ben Galbriaths, Brian Rickabaugh, Gotham Pollysetty, John Turner
ISBN # 1861008309, Wrox Press

Amazon.com
"JSP, Servlets, and MySQL"
by David Harms
ISBN # 0764547879, Hungry Minds, Inc

Amazon.com
"MySQL"
by Paul DuBois, Michael Widenius
ISBN # 0735709211, New Riders Publishing

Amazon.com
"Manageing and Using MySQL"
by George Reese, Randy Jay Yarger, Tim King
ISBN # 0596002114, O'Reilly

Amazon.com
PostgreSQL Essential Reference
by Barry Stinson
ISBN #0735711216, New Riders

Amazon.com
PostgreSQL: Developer's Handbook
by Ewald Geschwinde, Hans-Juergen Schoenig, Hans-Jurgen Schonig
ISBN #0672322609, SAMS

Amazon.com
Practical PostgreSQL
John C. Worsley, Joshua D. Drake
ISBN #1565928466, O'Reilly

Amazon.com
Beginning Databases with PostgreSQL
by Richard Stones, Neil Matthew
ISBN #1861005156, Wrox Press Inc

Amazon.com

Copyright © 2002 by Greg Ippolito