Lesson 8 - Swing and JDBC: Notes
Lesson 8 - Swing and JDBC: Notes
CONTENTS
Learning Objectives
Overview
8.1 Basics of Swing
8.2 JDBC
Summary
Keywords
Self-Assessment Questions
Further Readings
LEARNING OBJECTIVES
After studying this lesson, you should be able to:
z Learn basics of swing in Java
z Understand the JDBC and its working
OVERVIEW
In the previous lesson, you have learnt about generic methods, generic classes
arrays and working with applets and applet GUI.
In this lesson, you will study the JDBC, it is a Java-based data access
technology (Java Standard Edition platform) from Oracle Corporation. Do you
know that this technology is an API for the Java programming language that
defines how a client may access a database. It provides methods for querying
and updating data in a database.
In this lesson, you will also learn about the basics of swing in Java and
working with JDBC in detail.
147
Web Programming
Notes z Extensible
z Configurable
z Lightweight
The Swing API has 18 public packages. They are as follows:
z javax.accessibility
z javax.swing
z javax.swing.border
z javax.swing.colorchooser
z javax.swing.event
z javax.swing.filechooser
z javax.swing.plaf
z javax.swing.plaf.basic
z javax.swing.plaf.metal
z javax.swing.plaf.multi
z javax.swing.plaf.synth
z javax.swing.table
z javax.swing.text
z javax.swing.text.html
z javax.swing.text.html.parser
z javax.swing.text.rtf
z javax.swing.tree
z javax.swing.undo
Swing is an advanced GUI toolkit. It has a rich set of widgets. From basic
widgets like buttons, labels, scrollbars to advanced widgets like trees and
tables. Swing itself is written in Java.
148
Lesson 8 - Swing and JDBC
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public SimpleExample() {
setTitle("Simple example");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
149
Web Programming
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
SimpleExample ex = new SimpleExample();
ex.setVisible(true);
}
});
}
}
While this code is very short, the application window can do quite a lot. It can
be resized, maximized, minimized. All the complexity that comes with it has
been hidden from the application programmer.
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
Here, we import Swing classes that will be used in the code example.
public class Example extends JFrame {
The example class inherits from the JFrame widget. JFrame is a toplevel
container. In the container, we put other widgets.
setTitle("Simple example");
Here, we set the title of the window using the setTitle() method.
setSize(300, 200);
This code will resize the window to be 300px wide and 200px tall.
setLocationRelativeTo(null);
This line will center the window on the screen.
setDefaultCloseOperation(EXIT_ON_CLOSE);
This method will close the window, if we click on the close button of the
titlebar. By default nothing happens.
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
SimpleExample ex = new SimpleExample();
ex.setVisible(true);
}
});
We create an instance of our code example and make it visible on the screen.
150
Lesson 8 - Swing and JDBC
Notes
The invokeLater() method places the application on the Swing
Event Queue.
It is used to ensure that all GUI updates are concurrency-safe. In other words, it
is to prevent GUI from hanging in certain situations.
Quit Button
In our next example, we will have a button. When we click on the button, the
application terminates.
package com.zetcode;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class QuitButtonExample extends JFrame {
public QuitButtonExample() {
initUI();
}
private void initUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
JButton quitButton = new JButton("Quit");
quitButton.setBounds(50, 60, 80, 30);
quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
151
Web Programming
Notes System.exit(0);
}
});
panel.add(quitButton);
setTitle("Quit button");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
QuitButtonExample ex = new QuitButtonExample();
ex.setVisible(true);
}
});
}
}
We position a JButton on the window. We will add an action listener to this
button.
public QuitButtonExample() {
initUI();
}
It is a good programming practice to put the code that creates the GUI inside a
specific method.
JPanel panel = new JPanel();
getContentPane().add(panel);
We create a JPanel component. It is a generic lightweight container. We add
the JPanel to the JFrame.
panel.setLayout(null);
By default, the JPanel has a FlowLayout manager. The layout manager is used
to place widgets onto the containers.
152
Lesson 8 - Swing and JDBC
Learning Activity
Suppose there is a class inherited from the JFrame widget. How it
can be positioned in the screen effectively?
8.2 JDBC
The Java JDBC API enables Java applications to connect to relational
databases via a standard API, so your Java applications become independent
(almost) of the database the application uses.
153
Web Programming
154
Lesson 8 - Swing and JDBC
155
Web Programming
Notes z Driver: This interface handles the communications with the database
server. You will interact directly with Driver objects very rarely. Instead,
you use DriverManager objects, which manage objects of this type. It also
abstracts the details associated with working with Driver objects.
z Connection: This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all
communication with database is through connection object only.
z Statement: You use objects created from this interface to submit the SQL
statements to the database. Some derived interfaces accept parameters in
addition to executing stored procedures.
z ResultSet: These objects hold data retrieved from a database after you
execute an SQL query using Statement objects. It acts as an iterator to
allow you to move through its data.
z SQLException: This class handles any errors that occur in a database
application.
The JDBC 4.0 Packages
The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the
latest JDBC version at the time of writing this tutorial. It offers the main
classes for interacting with your data sources.
The new features in these packages include changes in the following areas:
z Automatic database driver loading
z Exception handling improvements
z Enhanced BLOB/CLOB functionality
z Connection and statement interface enhancements
z National character set support
z SQL ROWID access
z SQL 2003 XML data type support
z Annotations
After you've installed the appropriate driver, it's time to establish a database
connection using JDBC.
The programming involved to establish a JDBC connection is fairly simple.
Here are these simple four steps:
z Import JDBC Packages: Add import statements to your Java program to
import required classes in your Java code.
z Register JDBC Driver: This step causes the JVM to load the desired driver
implementation into memory so it can fulfill your JDBC requests.
156
Lesson 8 - Swing and JDBC
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch(ClassNotFoundException ex) {
157
Web Programming
158
Lesson 8 - Swing and JDBC
Following table lists down popular JDBC driver names and database URL. Notes
Table 8.1: Popular JDBC Drivers
RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port
Number:databaseName
DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port
Number/databaseName
All the highlighted part in URL format is static and you need to change only
remaining part as per your database setup.
Create Connection Object
Using a Database URL with a Username and Password
Here is listed down three forms of DriverManager.getConnection() method
to create a connection object. The most commonly used form of
getConnection() requires you to pass a database URL, a username, and a
password.
Assuming you are using Oracle's thin driver, you'll specify a
host:port:databaseName value for the database portion of the URL.
If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood,
and your Oracle listener is configured to listen on port 1521, and your database
name is EMP, then complete database URL would then be:
jdbc:oracle:thin:@amrood:1521:EMP
Now you have to call getConnection() method with appropriate username and
password to get a Connection object as follows:
String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);
159
Web Programming
Learning Activity
To ensure that a connection is closed, you could provide a finally
block in your code. What is it? Discuss with example.
SUMMARY
z Swing is an advanced GUI toolkit. It has a rich set of widgets.
160
Lesson 8 - Swing and JDBC
z From basic widgets like buttons, labels, scrollbars to advanced widgets like Notes
trees and tables. Swing itself is written in Java.
z JDBC stands for Java Database Connectivity, which is a standard Java API
for database-independent connectivity between the Java programming
language and a wide range of databases.
z JDBC is a specification that provides a complete set of interfaces that
allows for portable access to an underlying database.
z The JDBC API supports both two-tier and three-tier processing models for
database access but in general JDBC Architecture consists of two layers
JDBC API and JDBC Driver API.
z The JDBC API uses a driver manager and database-specific drivers to
provide transparent connectivity to heterogeneous databases.
z The JDBC driver manager ensures that the correct driver is used to access
each data source.
z The driver manager is capable of supporting multiple concurrent drivers
connected to multiple heterogeneous databases.
KEYWORDS
Swing: It is an advanced GUI toolkit. It has a rich set of widgets.
JDBC: It is a specification that provides a complete set of interfaces that
allows for portable access to an underlying database.
JDBC API: It uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.
SELF-ASSESSMENT QUESTIONS
Short Answer Questions
1. What are the different swing API public packages?
2. List any three characteristics of swing toolkit.
3. What all types of executable can be written by Java?
4. Write a short note on JDBC Architecture.
5. List some new features of JDBC package 4.0.
Long Answer Questions
1. What do you mean by JDBC API? How it differs from JDBC driver API?
2. Explain the different components of JDBC.
3. Explain the process involved in establishing JDBC connection.
161
Web Programming
Notes 4. How can you use a database URL with a username and password to create
a connection?
5. What do you mean by swing library? Give an example also.
FURTHER READINGS
162
Lesson 9 - Servlets
UNIT V Notes
LESSON 9 - SERVLETS
CONTENTS
Learning Objectives
Overview
9.1 Java Servlets
9.1.1 Servlets Architecture
9.1.2 Servlets Tasks
9.1.3 Servlets Packages
9.2 Servlets API
9.3 Servlet Life Cycle
9.4 Servlet Configuration
Summary
Keywords
Self-Assessment Questions
Further Readings
LEARNING OBJECTIVES
After studying this lesson, you should be able to:
z Learn about Java Servlets
z Understand the Servlets API
z Know the Servlets Life Cycle
z Illustrate the Servlet Configuration
OVERVIEW
In the previous lesson, you have learnt about basics of swing in Java and
working with JDBC in detail.
In this lesson, you will study about Java Servlets. Java Servlets are the
programs that run on a Web or Application server. They act as a middle layer
between requests coming from a Web browser or other HTTP client and
databases or applications on the HTTP server.
163
Web Programming
Notes In this lesson, you will also learn about Servlets API, Servlets Life Cycle and
finally you will understand about Servlet Configuration.
164
Lesson 9 - Servlets
z Read the implicit HTTP request data sent by the clients (browsers). This Notes
includes cookies, media types and compression schemes the browser
understands, and so forth.
z Process the data and generate the results. This process may require talking
to a database, executing an RMI or CORBA call, invoking a Web service,
or computing the response directly.
z Send the explicit data (i.e., the document) to the clients (browsers). This
document can be sent in a variety of formats, including text (HTML or
XML), binary (GIF images), Excel, etc.
z Send the implicit HTTP response to the clients (browsers). This includes
telling the browsers or other clients what type of document is being
returned (e.g., HTML), setting cookies and caching parameters, and other
such tasks.
9.1.3 Servlets Packages
Java Servlets are Java classes run by a web server that has an interpreter that
supports the Java Servlet specification.
165
Web Programming
Notes There are many interfaces in javax.Servlet package. They are as follows:
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
Classes in javax.Servlet Package
There are many classes in javax.Servlet package. They are as follows:
1. Generic Servlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
Interfaces in javax.Servlet.http Package
There are many interfaces in javax.Servlet.http package. They are as follows:
1. HttpServletRequest
2. HttpServletResponse
166
Lesson 9 - Servlets
3. HttpSession Notes
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
Classes in javax.Servlet.http Package
There are many classes in javax.Servlet.http package. They are as follows:
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
Learning Activity
Servlets can be created using the javax.servlet and
javax.servlet.http packages. Can it be created using any other
package also? Find out.
167
Web Programming
Notes The servlet is normally created when a user first invokes a URL corresponding
to the servlet, but you can also specify that the servlet be loaded when the
server is first started.
The init() method simply creates or loads some data that will be
used throughout the life of the servlet.
public void init(ServletConfig config) throws ServletException
This method is called once when the servlet is loaded into the servlet engine,
before the servlet is asked to process its first request. The init method has a
ServletConfig parameter. The servlet can read its initialization arguments
through the ServletConfig object. How the initialization arguments are set is
servlet engine dependent but they are usually defined in a configuration file.
A typical example of an initialization argument is a database identifier.
A servlet can read this argument from the ServletConfig at initialization and
then use it later to open a connection to the database during processing of a
request:
private String databaseURL;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
databaseURL = config.getInitParameter("database");
}
service() Method
The service() method is the main method to perform the actual task. The
servlet container (i.e. web server) calls the service() method to handle requests
coming from the client( browsers) and to write the formatted response back to
the client.
public void service(ServletRequest request, ServletResponse
response) throws
ServletException, IOException
This method is called to process a request. It can be called zero, one or many
times until the servlet is unloaded.
Once a servlet is loaded, it remains in the server’s memory as a single object
instance. Thereafter, the server invokes the servlet to handle a request using a
simple, lightweight method invocation. Unlike with CGI, there’s no process to
168
Lesson 9 - Servlets
spawn or interpreter to invoke, so the servlet can begin handling the request Notes
almost immediately. Multiple, concurrent requests are handled by separate
threads, so servlets are highly scalable. Servlets are naturally enduring objects.
Because a servlet stays in the server’s memory as a single object instance, it
automatically maintains its state and can hold on to external resources, such as
database connections, that may otherwise take several seconds to establish. The
following servlet presents information about how many times it has been
accessed:
import java.io.*;
import javax.Servlet.*;
import javax.Servlet.http.*;
public class SimpleCounter extends HttpServlet {
int count = 0;
public void doGet(HttpServletRequest req, HttpServletResponse
res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
count++;
out.println("Since loading, this servlet has been accessed " +
count + " times.");
}
}
Each time the server receives a request for a servlet, the server
spawns a new thread and calls service.
The variable count is shared by all the threads each corresponding to a single
request. So this provides a way for the threads to communicate with each other.
Unfortunately the concurrency that multiple threads (one per request) can
execute this method in parallel also brings problems. Imagine that one thread
increments the count and just afterward, before the first thread prints the count,
the second thread also increments the count. Each thread will print the same
count value, after effectively increasing its value by 2. The order of execution
goes something like this:
count++ // Thread 1
count++ // Thread 2
out.println // Thread 1
out.println // Thread 2
169
Web Programming
Notes Now, in this case, the inconsistency is not a real problem, but many other
servlets have more serious opportunities for errors. To prevent these types of
problems and the inconsistencies that come with them, we can add one or more
synchronized blocks to the code.
Anything inside a synchronized block or a synchronized method is guaranteed
not to be executed concurrently by another thread. Before any thread begins to
execute synchronized code, it must obtain a monitor (lock) on a specified
object instance. If another thread already has that monitor – because it is
already executing the same synchronized block or some other block with the
same monitor – the first thread must wait.
For example, we may wrap the addition and print operations in a synchronized
blocks as follows:
PrintWriter out = res.getWriter();
synchronized(this) {
count++;
out.println("Since loading, this servlet has been accessed " +
count + " times.");
}
The javax.Servlet.SingleThreadModel interface provides another approach to
avoid race condition.
If a servlet implements this interface, you are guaranteed that no two threads
will execute concurrently in the servlet’s service method. The servlet container
can make this guarantee by synchronizing access to a single instance of the
servlet, or by maintaining a pool of servlet instances and dispatching each new
request to a free servlet.
If a servlet implements this interface, the servlet will be thread safe. However,
this interface does not prevent synchronization problems that result from
servlets accessing shared resources such as static class variables or classes
outside the scope of the servlet.
destroy() Method
The destroy() method is called only once at the end of the life cycle of a
servlet. This method gives your servlet a chance to close database connections,
halt background threads, write cookie lists or hit counts to disk, and perform
other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage
collection.
public void destroy()
This method is called once just before the servlet is unloaded
and taken out of service.
170
Lesson 9 - Servlets
The following gives an servlet example with both init() and Notes
destroy() methods:
3
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class InitDestroyCounter extends HttpServlet {
int count;
public void init() throws ServletException {
// Try to load the initial count from our saved persistent
state
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
fileReader = new FileReader("InitDestroyCounter.initial");
bufferedReader = new BufferedReader(fileReader);
String initial = bufferedReader.readLine();
count = Integer.parseInt(initial);
return;
}
catch (FileNotFoundException ignored) { } // no saved state
catch (IOException ignored) { } // problem during read
catch (NumberFormatException ignored) { } // corrupt saved
state
finally {
// Make sure to close the file
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException ignored) { }
}
An object of ServletConfig is created by the web container for each servlet.
This object can be used to get configuration information from web.xml file.
171
Web Programming
172
Lesson 9 - Servlets
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletConfig config=getServletConfig();
Enumeration<String> e=config.getInitParameterNames();
String str="";
while(e.hasMoreElements()){
str=e.nextElement();
out.print("<br>Name: "+str);
out.print(" value: "+config.getInitParameter(str));
}
out.close();
173
Web Programming
Notes }
}
web.xml
<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>system</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>oracle</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
Advantage of ServletConfig
The core advantage of ServletConfig is that you don't need to edit the servlet
file if information is modified from the web.xml file.
Methods of ServletConfig Interface
Methods of ServletConfig Interface are as follows:
1. public String getInitParameter(String name): Returns the parameter value
for the specified parameter name.
2. public Enumeration getInitParameterNames(): Returns an enumeration of
all the initialization parameter names.
3. public String getServletName(): Returns the name of the servlet.
4. public ServletContext getServletContext(): Returns an object of
ServletContext.
174
Lesson 9 - Servlets
<init-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</init-param>
......
</servlet>
</web-app>
Learning Activity
Do research on the use of servlet configuration by taking any MNC
framework as an example and compare?
SUMMARY
z Java Servlets are programs that run on a Web or Application server and act
as a middle layer between requests coming from a Web browser or other
HTTP client and databases or applications on the HTTP server.
z Using Servlets, you can collect input from users through web page forms,
present records from a database or another source, and create web pages
dynamically.
z Java Servlets often serve the same purpose as programs implemented using
the Common Gateway Interface (CGI).
z Java Servlets are Java classes run by a web server that has an interpreter
that supports the Java Servlet specification.
175
Web Programming
KEYWORDS
Java Servlets: They are programs that run on a Web or Application server and
act as a middle layer between requests coming from a Web browser or other
HTTP client and databases or applications on the HTTP server.
Servlet Life Cycle: It can be defined as the entire process from its creation till
the destruction.
init() Method: It is called when the servlet is first created, and not called again
for each user request.
SELF-ASSESSMENT QUESTIONS
Short Answer Questions
1. Write a short note on Java Servlets.
2. State the path followed by a Servlet.
3. What type of task are Servlet tasks?
4. List the different interfaces in javax.servlet package.
5. Differentiate between dopost() and doget() methods.
176
Lesson 9 - Servlets
FURTHER READINGS
177