- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Working with Derby & Apache Tomcat
In this chapter, we will show how we can put together Derby with Apache Tomcat web container.
Apache Tomcat is a web container for the Java programming language. It is used to serve JSP pages and servlets. Apache Tomcat can be easily put together to work with Derby. Derby has a derby.war
file in its lib
subdirectory. This web archive is simply used to control the Derby database. Both Tomcat and Derby are projects of the Apache Software foundation.
$ pwd /home/janbodnar/bin/tomcat $ ls lib/derby* lib/derbyclient.jar lib/derby.jar lib/derbynet.jar
First we have to copy the derbyclient.jar
, derby.jar
and derbynet.jar
files into the lib
subdirectory of the Tomcat installation directory.
$ ls webapps derby.war docs examples host-manager manager ROOT
Then we have to copy the derby.war file into the webapps
subdirectory file of the Tomcat installation directory. When the Tomcat starts, the file is unpacked and deployed.
$ export JAVA_OPTS=-Dderby.system.home=/home/janbodnar/programming/derby/dbs
When we start Derby via Tomcat, the DERBY_OPTS variable is not taken into account. The derby.system.home
must be set prior to starting the Tomcat and Derby servers. We can set the Derby system directory in the JAVA_OPTS
variable.
$ bin/startup.sh Using CATALINA_BASE: /home/janbodnar/bin/tomcat Using CATALINA_HOME: /home/janbodnar/bin/tomcat Using CATALINA_TMPDIR: /home/janbodnar/bin/tomcat/temp Using JRE_HOME: /home/janbodnar/bin/jdk1.6.0_30 Using CLASSPATH: /home/janbodnar/bin/tomcat/bin/bootstrap.jar: /home/janbodnar/bin/tomcat/bin/tomcat-juli.jar
With the startup.sh
script we start the Tomcat server.

We see the Tomcat welcome page when we navigate to localhost:8080
which is the default URL on which Tomcat listens.

To start the Derby database, we navigate to localhost:8080/derby/derbynet
. This will start the Derby. We have several buttons which can be used to start/stop the server, enable/disable logging or tracing.
<load-on-startup>0</load-on-startup>
We have to navigate to the above mentioned URL each time, we start the Tomcat server. To automatically start Derby, we can add the above line inside the the <servlet>
tag of the web.xml
file. The file is located in webapps/derby/WEB-INF
directory.
Creating the testdb database
For those, who did not follow the tutorial from the beginning, we will create the testdb
database again. We will add one table into the database. You can skip the creation of the database and the table if it already exists.
$ cat cars.sql CREATE SCHEMA USER12; CREATE TABLE CARS(ID INT PRIMARY KEY, NAME VARCHAR(30), PRICE INT); INSERT INTO CARS VALUES(1, 'Audi', 52642); INSERT INTO CARS VALUES(2, 'Mercedes', 57127); INSERT INTO CARS VALUES(3, 'Skoda', 9000); INSERT INTO CARS VALUES(4, 'Volvo', 29000); INSERT INTO CARS VALUES(5, 'Bentley', 350000); INSERT INTO CARS VALUES(6, 'Citroen', 21000); INSERT INTO CARS VALUES(7, 'Hummer', 41400); INSERT INTO CARS VALUES(8, 'Volkswagen', 21600);
We will need this SQL file.
$ cat dbs/derby.properties derby.stream.error.logSeverityLevel=0 derby.database.fullAccessUsers=user12 derby.database.defaultConnectionMode=readOnlyAccess derby.connection.requireAuthentication=true derby.user.user12=34klq* derby.user.user13=33kl33 derby.user.user14=14kl14 derby.user.user15=35rr++ derby.authentication.provider=builtin
Inside the Derby system directory, we have the derby.properties file. In this file, we configure some options. We set the log severity level to 0 to report all possible problems. This is done in test environments. We enable authentication. We create four users with corresponding passwords. Only one of them, user12, has full access priviliges. The others have only readOnlyAccess.
$ java -Dderby.system.home=/home/janbodnar/programming/derby/dbs \ -Dij.protocol=jdbc:derby: -jar $DERBY_HOME/lib/derbyrun.jar ij ij version 10.8 ij>
We start the ij
command line tool. We will use it to create a database and a table. The Derby system directory is located at /home/janbodnar/programming/derby/dbs
.
ij> CONNECT 'jdbc:derby://localhost:1527/testdb;create=true; user=user12;password=34klq*';
We create the testdb
database and connect to it. We provide user credentials.
ij> run 'cars.sql';
We execute the cars.sql
script, which creates a CARS
table and fills it with data.
ij> SELECT * FROM CARS; ID |NAME |PRICE ------------------------------------------------------ 1 |Audi |52642 2 |Mercedes |57127 3 |Skoda |9000 4 |Volvo |29000 5 |Bentley |350000 6 |Citroen |21000 7 |Hummer |41400 8 |Volkswagen |21600 8 rows selected
This is our CARS
table. Next we will create a Java servlet, which will display these values in a web browser.
The project
We will create a simple web application that will connect to the Derby database. One Java servlet will connect to the Derby and retrieve all data from the CARS
table.
$ tree . ├── build.xml ├── context.xml ├── lib │ └── servlet-api.jar ├── src │ └── zetcode │ └── SelectAllCars.java └── web.xml 3 directories, 5 files
In our current working directory, we have an Ant build.xml
file, the context.xml
configuration file, the web.xml
deployment descriptor file, and the src and lib subdirectories. The build.xml
file is the Ant build file, which describes the tasks to build, deploy or clean the project. The web.xml
defines the structure of the web application. In the lib directory we have the servlet-api.jar
file, which is needed to compile the source file. (It can be found in the lib subdirectory of the Tomcat installation directory.) In the src directory, we have the Java source file.
The web.xml
file defines the structure of the web application.
<?xml version="1.0" encoding="UTF8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0" metadata-complete="true"> <description> Servlet which connects to Derby </description> <display-name>Derby, Tomcat</display-name> <servlet> <servlet-name>SelectAllCars</servlet-name> <servlet-class>zetcode.SelectAllCars</servlet-class> </servlet> <servlet-mapping> <servlet-name>SelectAllCars</servlet-name> <url-pattern>/SelectAllCars</url-pattern> </servlet-mapping> </web-app>
These are the contents of the the web.xml
file. In this file, we register the SelectAllCars
servlet.
<?xml version="1.0" encoding="UTF-8"?> <Context> <Resource name="jdbc/testdb" auth="Container" type="javax.sql.DataSource" username="user12" password="34klq*" driverClassName="org.apache.derby.jdbc.ClientDriver" url="jdbc:derby://localhost:1527/testdb" maxActive="10" maxIdle="4"/> </Context>
In the context.xml
file, we define the JDBC datasource. The context.xml
file can be defined for all web applications or for a single application. The latter is our case.
We will show the Ant build file which will be used to build and deploy our tiny application.
<?xml version="1.0" ?> <project name="allcars" default="deploy"> <property name="src.dir" value="src"/> <property name="build.dir" value="build"/> <property name="dist.dir" value="dist"/> <property name="deploy.dir" value="/home/janbodnar/bin/tomcat/webapps"/> <echo>${ant.project.name}</echo> <target name="init"> <mkdir dir="${build.dir}/classes" /> <mkdir dir="${dist.dir}"/> <echo>Directories created.</echo> </target> <target name="compile" depends="init"> <javac srcdir="${src.dir}" destdir="${build.dir}/classes" includeantruntime="false"> <classpath path="lib/servlet-api.jar"/> </javac> <echo>Source files compiled.</echo> </target> <target name="archive" depends="compile"> <war destfile="${dist.dir}/${ant.project.name}.war" webxml="web.xml"> <classes dir="${build.dir}/classes"/> <metainf file="context.xml"/> </war> <echo>Archive created.</echo> </target> <target name="deploy" depends="archive"> <copy file="${dist.dir}/${ant.project.name}.war" todir="${deploy.dir}"/> <echo>Project deployed.</echo> </target> <target name="clean"> <delete dir="${dist.dir}"/> <delete dir="${build.dir}"/> <echo>Project cleaned.</echo> </target> </project>
The build file comprises five tasks. The initialization task will create the necessary directories. The compile task will compile the source code. The archive task will create a web archive. The deploy task will deploy the archive to the Tomcat server. Finally, the clean task will do the cleaning.
The following is the SelectAllCars
servlet.
package zetcode; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; public class SelectAllCars extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = null; Connection con = null; Statement st = null; ResultSet rs = null; try { out = response.getWriter(); Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/testdb"); con = ds.getConnection(); st = con.createStatement(); out.println("<html>"); out.println("<head>"); out.println("<title>SimpleServlet</title>"); out.println("</head>"); out.println("<body>"); rs = st.executeQuery("SELECT * FROM CARS"); while (rs.next()) { out.print(rs.getInt(1)); out.print(" "); out.print(rs.getString(2)); out.print(" "); out.print(rs.getString(3)); out.print("<br>"); } out.println("</body>"); out.println("</html>"); } catch (NamingException | SQLException ex) { Logger lgr = Logger.getLogger(SelectAllCars.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } finally { try { if (rs != null) { rs.close(); } if (con != null) { con.close(); } if (out != null) { out.close(); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(SelectAllCars.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } }
In the above servlet, we connect to the Derby testdb database and fetch all rows from the CARS
table.
Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/testdb");
We use the JNDI naming lookup to obtain the datasource. From the datasource, we create the connection object.
rs = st.executeQuery("SELECT * FROM CARS"); while (rs.next()) { out.print(rs.getInt(1)); out.print(" "); out.print(rs.getString(2)); out.print(" "); out.print(rs.getString(3)); out.print("<br>"); }
We use the SQL statement to retrieve all data from the CARS
table. We print the data from the result set object.
$ ant Buildfile: /home/janbodnar/programming/derby/servlet/build.xml [echo] allcars init: [mkdir] Created dir: /home/janbodnar/programming/derby/servlet/build/classes [mkdir] Created dir: /home/janbodnar/programming/derby/servlet/dist [echo] Directories created. compile: [javac] Compiling 1 source file to /home/janbodnar/programming/derby/ servlet/build/classes [echo] Source files compiled. archive: [war] Building war: /home/janbodnar/programming/derby/servlet/dist/allcars.war [echo] Archive created. deploy: [copy] Copying 1 file to /home/janbodnar/bin/tomcat/webapps [echo] Project deployed. BUILD SUCCESSFUL Total time: 1 second
We launch the ant to build and deploy the project.

We navigate to the localhost:8080/allcars/SelectAllCars URL and receive the output.
In the chapter, we have worked with Derby and Apache Tomcat.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论