http://www.yolinux.com/TUTORIALS/LinuxTutorialTomcat.html
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:
* ?.html#JAVAJDK”>Java JDK 1.4 - Installation, configuration
* ?.html#TOMCAT”>Jakarta Project: Tomcat 4.0 - Installation, configuration
* ?.html#SERVLET1″>Simple Java Servlet Example
* ?.html#APACHETOMCAT”>Apache 1.3 - Tomcat 4.0 Configuration
(Note: Apache 2.0 re-architected the way it handles modules. It will be incompible with the mod_jk module used in this tutorial.)
* ?.html#DATABASE”>Using a Servlet to connect and retrieve data from a database
* ?.html#LINKS”>Links
* ?.html#BOOKS”>Books
Note: Make sure your computer has massive amounts of memory!!!!
Related YoLinux? Tutorials:
°?.html”>Java on Linux
°?.html”>IBM Websphere
°YoLinux? Tutorials Index
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 ?.html”>YoLinux? JAVA for a list of available JDK’s for Linux.
Download the Sun JDK:
* JAVA 2 Standard Edition - Main page and info
* Java 2 Platform (J2SE), Standard Edition version 1.4
* http://java.sun.com/j2se/1.4/download.html> - Actual Download
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/j2sdk1.4.0/.
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:
* Sun.com: J2SE 1.4 installation instructions
* J2SE 1.4 Documentation
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.
The Jakarta Project: Apache Tomcat JAVA Servlet and JSP container home page
Download: Tomcat 4.0 RPMs (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:
* Tomcat 4.0 Documentation
* Also look at local documentation: /usr/share/doc/tomcat4-4.0.3/ for release notes.
* Local app documentation files: /var/tomcat4/webapps/tomcat-docs/
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:
o CATALINA_HOME: Tomcat installation directory
o CATALINA_OPTS example: export CATALINA_OPTS=”-Djava.ext.dirs=/dummy_dir”
Command line switches to pass to the Java Runtime Environment
o 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:
* http://localhost:8180/>
* http://localhost:8180/examples/jsp/index.html> - JSP samples
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.
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:
o Servlets and utility classes: /var/tomcat4/webapps/examples/WEB-INF/classes/
o 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:
Then restart: service tomcat4 restart
Use URL to list web applications: http://localhost:8180/manager/list>
Note:
* Do NOT make a login error. It does not forgive easily. Access from a different host to recover.
* Do not access before configuring tomcat-users.xml because of this.
* Documentation: http://localhost:8180/tomcat-docs/manager-howto.html> - [Web]
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(”“);
out.println(”
out.println(”“);
out.println(”“);
out.println(”“);
out.println(”“);
out.println(”
Hello World!
“);
out.println(”“);
out.println(”“);
}
}
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 “
* 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
o Unpack: tar -xzf jakarta-tomcat-connectors-4.0.2-01-src.tar.gz
o cd jakarta-tomcat-connectors-4.0.2-01-src/jk/native/apache-1.3/
o 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
o 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.
o 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.)
o 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:
o module to load for communication with Tomcat. (Add to httpd.conf)
o 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 or blackdown
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:
…
Define listener:
acceptCount="10" debug="0"/>
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.)
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”
Options Indexes FollowSymLinks?
# 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
AllowOverride? None
deny from all
…
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
DocumentRoot? /web/host1
ServerName? host1.yolinux.com
JkMount? /*.jsp ajp13
JkMount? /servlet/* ajp13
AllowOverride? None
deny from all
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:
…
…
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:
o Test Tomcat servlet: ?”>http://localhost/examples/servlet/MyHelloWorld>
o Test static page with Apache: http://localhost/>
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:
o /var/log/httpd/access_log
o /var/log/httpd/error_log
* Tomcat: /var/tomcat4/logs/…
* Apache-Tomcat module mod_jk: /var/log/httpd/mod_jk.log
Links:
* The AJP Connector and Tomcat 4.0: http://localhost:8180/tomcat-docs/config/ajp.html> - [Web]
* Working with mod_jk - Tomcat 3.2 - By Gal Shachor
* ?.html”>Sun Java: Getting Started With Tomcat
The Database:
We will cover connectivity to two databases:
1. ?.html#POSTGRESQL”>PostgreSQL?
2. ?.html#MYSQL”>MySQL?
Note: If connecting to Oracle, use the JDBC driver: oracle.jdbc.driver.OracleDriver?
1) PostgreSQL?:
Install and configure a database. See: ?.html”>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(”
out.println(”
Bedrock
“); 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(”
| ” + m_name + “ | ” + m_dept + “ | ” + m_jobtitle + “ |
“);
statement.close();
}
catch(Exception ex)
{
out.println(”” +
“
“Bedrock: Error” +
“
“
SQL error in doGet: ” +
ex.getMessage() + “
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:
o jdbc:postgresql:bedrock - bedrock is the PostgreSQL? database name. See PostgreSQL? tutorial.
o jdbc:postgresql://localhost/bedrock
o 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:
* Tomcat only: ?”>http://localhost:8180/examples/servlet/ShowBedrock>
* Apache Request: ?”>http://localhost/examples/servlet/ShowBedrock>
Results:
Bedrock
Fred Flinstone Quarry Worker Rock Digger
Wilma Flinstone Finance Analyst
Barney Rubble Sales Neighbor
Betty Rubble IT Neighbor
JDBC/PostgreSQL? Links:
* PostgreSQL?.org: JDBC
2) MySQL?:
Install and configure a database: ?.html”>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(”
out.println(”
Bedrock
“); // 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(”
| ” + m_name + “ | ” + m_dept + “ | ” + m_jobtitle + “ |
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(”” +
“
“Bedrock: Error” +
“
“
SQL error in doGet: ” +
ex.getMessage() + “
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:
* Tomcat only: ?”>http://localhost:8180/examples/servlet/ShowBedrock>
* Apache Request: ?”>http://localhost/examples/servlet/ShowBedrock>
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:
* JDBC MySQL? driver “mm” - [Alt]
* JDBC MySQL? driver “Resin”
* Sun.com: JAR file basics
* Nusphere.com: Discussion and explanation of simple JDBC mm.MySQL? servlet
* MySQL? JDBC Examples
* MySQL? Links - Lots of JDBC links as well.
* mm.MySQL? guide
* MySQL/JDBC? example
JAVA JDBC:
JAVA JDBC programs require the package: java.sql. Contained within this package are:
* Classes:
o Date
o DriverManager?
o DriverPropertyInfo?
o Time
o Timestamp
o Types
* Interfaces:
o CallableStatement?
o Connection
o DatabaseMetaData?
o Driver
o PreparedStatement?
o ResultSet?
o ResultMetaData?
o Statement
JDBC Links:
* Sun’s database of JDBC database drivers
* List of JDBC drivers for various databases
* Sun.com: JDBC
* Sun.com: JDBC Basics
JAVA Server Pages (JSP):
Basic JSP elements:
*
Example:
Year: is
Month: is
* <% ... %> : 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’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:
