Transcript JDBC
CG0093 Weeks 9-10
Networking, JDBC and
Servlets
Sajjad Shami
Michael Brockway
School of Computing, Engineering & Information Sciences
Northumbria University
1
Networking in Java
Deitel: 6e: Chapter 24
2
Networking
•
•
•
•
•
•
•
Introduction
Manipulating URLs; Java plug-in
Reading a file on a Web server
Connecting a client to a server with Sockets
Connectionless client/server interaction
An example using a multithreaded server
Security
3
Introduction
• The Client/Server model
• The JEditorPane swing component
– allows an application to down-load a web page
• Java’s socket-based communications
– connection-based client/server interaction
• stream sockets use Transmission Control Protocol (TCP)
– connectionless, packet-based client/server interaction
• datagram sockets use User Datagram Protocol (UDP)
4
Manipulating URLs
• The java.net package’s URL class
http://1www.ncsa.uiuc.edu2:80804/demoweb/url-primer.html3
1. protocol (eg http)
2. host machine
3. file
4. port on host machine for TCP connection (optional)
• The applet package’s AppletContext interface
– methods which retrieve information from the browser in which the
applet is running.
– an applet’s getAppletContext() method retrieves an object
implementing this
– methods showdocument(URL url) , getImage(URL url) etc
5
Manipulating URLs
• Example: SiteSelector applet
– takes as applet parameters pairs consisting of a Title and a URL
– populates a drop-down list with the titles
– when the user selects a title, loads the contents of the corresponding URL into the
browser
• uses getAppletContext().showDocument(url)
• features a ListSelectionListener object to handle selection from drop-down
list
– valueChanged( ) responds to event
– the HTML file which runs this applet needs to be run from within the browser if
the appropriate Java “plugin” is installed.
– Otherwise must be converted using the HTML converter for your version of Java
6
Site Selector Output
7
Java Plug-ins
• JVMs built into Netscape, Microsoft IE do not support Swing
• Sun used to provide a plug-in JVM for each of these
– At http://java.sun.com/products/plugin
– down-load BOTH the Java Run -time environment (JRE) (and install it)
AND the HTML file converter for your version of Java.
– Also down-load the documentation!
– Any HTML file with <APPLET> tags referring to applets which use Swing
(or otherwise require the plug-in) must be run through the HTML converter.
• Currently www.java.com -> GET IT NOW button
– (browser gets optimised with the latest plugins)
• HTML for the SiteSelector applet -- see the listings in Fig 24.1, p.1109.
8
Reading a File on a Web server
• A JEditorPane object is a kind of JTextComponent with
functionality to download content from a web site given a url
• The example ReadServerFile application (Deitel fig. 24.3) features – A JEditorPane
– A JTextField where you type the url whose content you wish to view;
an ActionListener calls private method getThePage() when you
press ENTER
– The JEditorPane has a HyperLinkListener which calls
getThePage() when you click a hyperlink in the page
– private method getThePage(url) does the donkey-work, using the
JEditorPane’s setPage() function.
9
File on Web Server
10
Client-Server connection with Sockets
•
To Establish and Run a Simple Server
Step 1: Construct a ServerSocket object (you may, for example, specify a TCP port number and a
maximum number of simultaneous client connections
Step2: This ServerSocket object listens indefinitely for a request for a client connection. It
accepts a client connection with its accept() method, which returns a Socket object to
manage the connection.
Step 3: This Socket object has methods getOutputStream() and getInputStream()
which return an OutputStream for the server to send to the client and an InputStream for
the server to receive from the client.
• More specialised streams can be chained to these: e.g.
ObjectInputStream obIn = new
ObjectInputStream(connection.getInputStream());
Step 4: Processing phase: client and server communicate via OutputStream and InputStream
objects.
Step 5: To end the client connection, the server uses the Socket object’s close() method.
– Example: See Deitel Fig. 24.5
11
Client-Server connection with Sockets
• To Establish and Run a Simple Client
– Step 1: The client requests a connection to a server by constructing a Socket
object, specifying the server address. Failure throws an IOException.
– Step 2: Use this Socket’s methods getOutputStream() and
getInputStream() to return an OutputStream for the client to send to the
server and an InputStream for the client to receive from the server. Again, more
sophisticated stream objects can be chained to these if numeric data or objects are
to be communicated to/from the server
12
Client-Server connection with Sockets
• To establish and run a simple client (ctd)
– Step 3: Processing phase using InputStream and OutputStream objects
– Step 4: The client closes the connection at its end with a call to the close()
method on its Socket object. The program must determine when the server has
done sending data -- e.g. InputStream.read() returns -1 (EOF).
• Example: Deitel Fig 24.7. See commentary in Deitel section 24.6
– An InetAdress object encapsulates IP address information
– Exercise: what modifications are needed for the client and the server to
run on different machines?
13
14
Connectionless Client/Server Interaction
• Client and Server classes are implemented similarly
– Each uses a DatagramSocket object to manage communication by
DatagramPackets by UDP protocol.
• Packets sent from one machine to another do not necessarily arrive in the
order they were sent.
– Each uses a DatagramPacket object to encapsulate a a packet of data.
Includes an array of bytes to hold that data, and length and address
information.
15
Connectionless Client/Server Interaction
• Example: Deitel: Figs 24.9 (server), 24.11 (client)
– In the client, the user enters text into a JTextField; on pressing
ENTER, it is copied into a byte array in a datagram packet and sent to the
server.
– The server waits for a packet to arrive, receives it and echoes it back to the
client.
– On receiving the packet, the client displays its contents.
– Exercise: what modifications are needed for the client and the server to
run on different machines?
16
Connectionless Client/Server Interaction
17
An Example using a Multithreaded
Server
• Deitel Example -- Fig 24.13
• Two clients play Tic-Tac-Toe by talking to a server which maintains
the state of the game
– TicTacToeServer is the server application class.
– Before the game can get under way, two clients must connect to the server.
The server creates a Player object for each client (one for player X, one
for the player O). Each Player object processes a client in a separate thread
of execution (Player extends Thread).
– TicTacToeServer.java implements TicTacToeServer and Player
18
Tic-Tac-Toe Server
19
Multithreaded server .. Contd.
• Deitel Example -- Fig 24.15
– TicTacToeClient is the client application class.
– Each client maintains a graphical representation of the state of the game
using a 3 X 3 array of Square objects
– TicTacToeClient.java implements TicTacToeClient and Square.
– See commentary in Deitel pp 1147.
– Exercises (1) what modifications are needed for the client and the server
to run on different machines?
– Exercises (2) Can you add functionality so that a message is sent to the
clients when a game is won, lost or drawn?
20
21
22
Security
•
Java applets are downloaded to your machine from all over
•
So applets are prohibited from doing file processing on the machines on which
they run, such as your machine.
•
An applet is usually restricted to be able to connect only to the machine from
which it downloaded.
– Now there are signed applets from which a browser can determine if the applet is
from a trusted source; if so, the applet can be given additional access.
• EXERCISES:
• Examples
• 24.13, 24.14, 24.17, 24.23
23
Java and Databases: JDBC
Deitel 6e Chapter 25
24
Database Tables
• A relational database can be seen as a set of tables
– field names are column headings
– records are rows in a table
– tables can be combined on common field names
FirstName
Alun
Pooh
Tigger
Eore
Roo
LastName
Location
Moon
Newcastle
Bear
Corner
Trees
House
Kanga
Kanga’s house
WorkPhone
email
0191 227 3643 [email protected]
1623
[email protected]
976
[email protected]
eore@ pooh.corner.ac.uk
23423
[email protected]
People
25
SQL (simply)
• SELECT picks the fields to report
– * or comma separated list of field names
• FROM specifies the table to get the data from
• WHERE introduces the selection criterion for field
values
– numerical tests using <, >, <=, >=, =, <>
– LIKE for pattern matching
26
SQL…contd.
SELECT FirstName FROM People WHERE email
LIKE ‘*corner*'
SELECT LastName,FirstName FROM People
WHERE 'WorkPhone=23423'
Pooh
Tigger
Eore
Kanga Roo
27
JDBC
• connecting to a database
1. Load the Drivers
2. Make the connection
• submitting a query
• interpreting the results
– what is returned
– extracting the result data
28
Connecting to a database
Loads the driver
class for the
database
connection
String url = "jdbc:odbc:books";
String username = "anonymous";
String password = "guest";
Connection connection;
// Load the driver to allow connection to the database
try {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
connection = DriverManager.getConnection(
url, username, password );
}
Establishes a
connection to the
database
29
Connecting to a database…contd.
Database URL
The ODBC SubProtocol (Microsoft)
jdbc:odbc:books
The JBDC
Protocol
The Data source
name
The sub-protocol scheme will
change depending on the host
database used.
30
Queries
Statement statement;
ResultSet resultSet;
try {
String query = "SELECT * FROM Authors";
statement = connection.createStatement();
resultSet = statement.executeQuery( query );
• The statement created is an object that implements the Statement
interface.
– This allows interaction with the database, queries can be made
• The executeQuery() method takes the query string, passes this to the
database via the jdbc connection.
• The results of the query (if any) are held in the resultSet
31
Results: MetaData
• The contents of the ResultSet will vary
• The ResultSetMetaData object describes the data in the
ResultSet
– number of columns of data
– title of each column
// get column heads
ResultSetMetaData rsmd = rs.getMetaData();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
columnHeads.addElement( rsmd.getColumnName( i ) );
– type of data in each column
java.sql.Types
switch( rsmd.getColumnType( i ) ) {
case Types.VARCHAR:
currentRow.addElement( rs.getString( i ) );
32
Results: Getting the data
• Each row is handled in turn
– iterate over the rows
// position to first record
boolean moreRecords = rs.next();
// get row data
do {
rows.addElement( getNextRow( rs, rsmd ) );
} while ( rs.next() );
– Different methods for each data type
case Types.VARCHAR:
currentRow.addElement( rs.getString( i ) ); break;
case Types.INTEGER:
currentRow.addElement( new Long( rs.getLong( i ) ) );
break;
33
Example: DisplayAuthors.java
• Deitel: Fig 25.25
• Database ‘books’
• Created using MySQL database management system (sec. 25.5)
• Exercises: 25.2 - 4
34
Servlets
Deitel 6e Chapter 26
35
Basic Concepts
• Client Application: Applets
• Server Side: Servlets
• Base class is extended HttpServlet
• Methods need to be overridden
• No user interface (graphical or console) …. Unlike
applets
36
Main Roles
• Inside a Web server
• 1. Servlets generate HTML ‘on the fly’
• 2. Servlets generate web pages in response to CGI requests
from forms (CGI = Common Gateway Interface)
• Without servlets, pages are static
• With servlets, dynamic web pages_ content can vary every
time page is delivered by the server
37
About CGI Requests
•
•
•
•
Common Gateway Interface (CGI) is a specification for transferring
information between a World Wide Web server and a CGI program,
which is any program designed to accept and return data that conforms
to the CGI specification. CGI scripts, or programs that run on the user's
machine, are becoming another common way to provide dynamic
feedback for Web users.
Uses for CGI scripts include search engine request forms and
image maps that contain links to other Internet sites. When a user
enters a search engine request or clicks on an image map, the CGI
script in the Web page automatically generates a new Web site
request.
The following example shows a URL generated by a search engine
when the term "Websense" was entered as the search request.
CGI Request: http://search.yahoo.com/bin/search?p=Websense
38
CGI Request…contd
•
•
•
•
•
CGI-generated site requests contain a question mark in the URLs
indicating to the Web server where the parameters of the search begin.
Following the question mark is the characteristic information used to
run the search, which typically includes the text of the user's search
request, the URL of a linked site, or a combination of templates,
names and values.
Because the result of each search engine request may be unique,
Websense ignores the "?" and everything beyond it when comparing a
CGI-requested site to the Master Database. When filtering the example
above, Websense matches the requested URL to the Master Database
listing even though the requested site has a CGI string
("?p=Websense") appended to it.
CGI Request: http://search.yahoo.com/bin/search?p=Websense
Master Database match: http://search.yahoo.com/bin/search
To provide additional filtering for sites requested via CGI, Websense
lets you block keywords in CGI strings appended to a URL.
39
HTTP and CGI
• define how data from a web form is encoded and
transmitted to the web server
• two types of requests for pages:
get
Web
Server
Client App
post
40
Get and Post
• Get: information is placed in the URL
• http://localhost/servlets/generatePage?no=234&id=john
• Post: URL just points to the resource
• http://localhost/servlets/generatePage
data is placed in the body of the request
• Analogy: email with data in subject line and
email with the data in the body of the email
• Advantages and disadvantages
• Get method can be book marked, linked to from a page, or entered
directly …………data is visible in transit
• Post method: a lot more data can be sent, plus better security
41
Servlet configuration
• Classes are in javax.servlet
• Servlet interface declares but does not implement
• GenericServlet is an implementation
• javax.servlet.http.HttpServlet is the base class
• Interface Servlet
• GenericServlet, HTTPServlet have methods
• void init ( ServletConfig config ) called once upon
initialisation of resources
• void destroy ( ) called upon termination, and releases
resources
42
HttpServlet
• public void doGet ( HttpServletRequest request,
HttpServletResponse response )
– is called by server in response to http get request
• public void doPost ( HttpServletRequest request,
HttpServletResponse response )
– is called by server in response to http post request
• Writing a servlet:
– Need to extend the HttpServlet class and override and implement the required
methods
– public class TestServlet extends HttpServlet { …
…
}
– Parameters are HttpServletRequest methods and
HttpServletResponse methods
43
Servlet Output
• Need to set the content-type.
• Recognised MIME type for material being sent in response to the
request.
• Text/html for a web page or image/jpeg for an image.
• MIME: Multipurpose Internet Mail Extensions
– MIME extends the format of Internet mail to allow non-US-ASCII textual
messages, non-textual messages, multipart message bodies, and non-USASCII information in message headers.
44
Text Output
• e.g. for an HTML page
public void doGet (HttpServletRequest request,
HttpServletResponse response ) {
Printwriter output;
response.setContentType( “text/html” );
output = response.getWriter();
output.println(“<html><head>\n”);
output.println(“<title>FormRequest</title>\n”);
output.println(“<head><body>\n”);
output.println( createForm() );
output.println(“</body></html\n”);
output.close();
}
45
Binary Output (image)
public void doGet ( HttpServletRequest request,
HttpServletResponse response ) {
ServletOutputStream output;
response.setContentType( “image/jpeg” );
output = response.getOutputStream();
JPEGImageEncoder encoder =
JPEGCodec.createJPEGEncoder (output);
encoder.encode ( generateGraph() );
output.close();
}
46
Servlet Parameters
• can be used to generate the appropriate output
• are passed in the URL for get and in the request body for post
• are in the form of name-value pairs
• a parameter name can have several values
• several methods in HttpServletRequest parameter to get the
values
47
Methods to get parameter values
• public String getParameter( String name )
http://www.library.org/search?name=nature&volume=32
String journal = request.getParameter (“name” );
int volume = Integer.ParseInt(request.getParameter (“volume”) );
• public String[] getParameterValues(String name )
String[] students = request.getParameterValues( “name”);
• public java.util.Enumeration getParameterNames ( )
– returns a list of all the parameter names that have values set.
•
Note: these methods return null if parameter was not set
48
Points
•
•
•
•
•
Servlets are compiled and called by the server as needed
Multi-threaded servlets can handle simultaneous requests
Servlets can use any other Java API
Servlet UI is the web page form
The form should be kept in sync with the servlet that handles the
response
49
Tomcat and Servlets
• Apache Tomcat provides complete implementation of Servlets
• Downloadable from www.jakarta.apache.org
• Environment variables:
– JAVA_HOME should point to Java SDK installation
– CATALINA_HOME should point to Tomcat root folder
• To start Tomcat server, open command prompt
– C:\Program Files\Apache Group\ Tomcat 4.1\bin > Startup.bat
• [To stop Tomcat server, open another command prompt
– C:\Program Files\Apache Group\ Tomcat 4.1\bin > Shutdown.bat ]
• To verify Tomcat is executing, open browser (IE) and enter url:
– http://localhost:8080 or
– http://127.0.0.1:8080
– should display Tomcat homepage.
50
Tomcat Homepage
51
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Outline
// Fig. 24.5: WelcomeServlet.java
// A simple servlet to process get requests.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
Import the javax.servlet and
javax.servlet.http packages.
public class WelcomeServlet extends HttpServlet {
// process "get" requests from clients
protected void doGet( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
// send XHTML page to client
// start XHTML document
out.println( "<?xml version = \"1.0\"?>" );
out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD
"XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
"/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
WelcomeServlet
Lines 4-5
Extends HttpServlet to
Line
8
handle HTTP get
requests
and HTTP post requests.
Override methodLines
doGet11-42
to
provide custom get request
processing.
Line 15
Uses the response object’s
Line
16
Uses
the response
object’s
setContentType
method
to
getWriter
method
to of
obtain
a to
specify the content
type
the data
Lines
21-40
reference
PrintWriter
be sent as to
thethe
response
to the client.
object that enables the servlet to send
content to the client.
Create the XHTML document
by writing strings with the out
" + object’s println method.
52
2003 Prentice Hall, Inc.
All rights reserved.
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
// head section of document
out.println( "<head>" );
out.println( "<title>A Simple Servlet Example</title>" );
out.println( "</head>" );
Outline
WelcomeServlet
Line 41
// body section of document
out.println( "<body>" );
out.println( "<h1>Welcome to Servlets!</h1>" );
out.println( "</body>" );
// end XHTML document
out.println( "</html>" );
out.close(); // close stream to complete the page
}
}
Closes the output stream,
flushes the output buffer
and sends the information
to the client.
2003 Prentice Hall, Inc.
53
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 24.6: WelcomeServlet.html -->
Outline
WelcomeServlet.
html
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Handling an HTTP Get Request</title>
</head>
<body>
<form action = "/jhtp5/welcome1" method = "get">
<p><label>Click the button to invoke the servlet
<input type = "submit" value = "Get HTML Document" />
</label></p>
</form>
</body>
</html>
54
2003 Prentice Hall, Inc.
All rights reserved.
Example: WelcomeServlet
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Deitel: Fig 26.7
To execute WelcomeServlet, the following structure is needed:
Note: (…) is a folder.
(Tomcat 4.1)
(webapps)
(jhtp5)
(servlets)
WelcomeServlet.html
(WEB-INF)
web.xml
(classes)
WelcomeServlet.class
55
WelcomeServlet…contd
• Now enter this URL in browser:
– http://localhost:8080/jhtp5/servlets/WelcomeServlet.html
– this will load WelcomeServlet.html into web browser
•
click the button GET HTML DOCUMENT
56
WelcomeServlet…contd
• Examples
• Exercises 26.5-7
57