Date post: | 28-Jan-2016 |
Category: |
Documents |
Upload: | willis-robertson |
View: | 215 times |
Download: | 0 times |
1
CG0093 Weeks 9-10
Networking, JDBC and Servlets
Sajjad Shami
Michael Brockway
School of Computing, Engineering & Information Sciences
Northumbria University
2
Networking in Java
Deitel: 6e: Chapter 24
3
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
4
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)
5
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 machine3. 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
6
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
7
Site Selector Output
8
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.
9
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.
10
File on Web Server
11
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
12
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
13
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?
14
15
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.
16
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?
17
Connectionless Client/Server Interaction
18
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
19
Tic-Tac-Toe Server
20
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?
21
22
23
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
24
Java and Databases: JDBC
Deitel 6e Chapter 25
25
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 LastName Location WorkPhone email Alun Moon Newcastle 0191 227 3643 [email protected] Pooh Bear Corner 1623 [email protected] Tigger Trees 976 [email protected] Eore House eore@ pooh.corner.ac.uk Roo Kanga Kanga’s house 23423 [email protected]
People
26
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
27
SQL…contd.
SELECT FirstName FROM People WHERE email LIKE ‘*corner*' SELECT FirstName FROM People WHERE email LIKE ‘*corner*'
Pooh Tigger Eore
SELECT LastName,FirstName FROM People WHERE 'WorkPhone=23423' SELECT LastName,FirstName FROM People WHERE 'WorkPhone=23423'
Kanga Roo
28
JDBC
• connecting to a database1. Load the Drivers
2. Make the connection
• submitting a query• interpreting the results
– what is returned
– extracting the result data
29
Connecting to a databaseLoads the driver class for the database connection
Establishes a connection to the database
String url = "jdbc:odbc:books"; String username = "anonymous";String password = "guest";Connection connection;// Load the driver to allow connection to the databasetry { Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
connection = DriverManager.getConnection( url, username, password );}
30
Connecting to a database…contd.
Database URLDatabase URL
jdbc:odbc:books
The JBDC Protocol
The ODBC Sub-Protocol (Microsoft)
The Data source name
The sub-protocol scheme will change depending on the host database used.
31
QueriesStatement statement;ResultSet resultSet; try { String query = "SELECT * FROM Authors";
statement = connection.createStatement(); resultSet = statement.executeQuery( query );
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
32
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 headsResultSetMetaData rsmd = rs.getMetaData(); for ( int i = 1; i <= rsmd.getColumnCount(); ++i ) columnHeads.addElement( rsmd.getColumnName( i ) );
// get column headsResultSetMetaData rsmd = rs.getMetaData(); for ( int i = 1; i <= rsmd.getColumnCount(); ++i ) columnHeads.addElement( rsmd.getColumnName( i ) );
– type of data in each column
switch( rsmd.getColumnType( i ) ) { case Types.VARCHAR: currentRow.addElement( rs.getString( i ) );
switch( rsmd.getColumnType( i ) ) { case Types.VARCHAR: currentRow.addElement( rs.getString( i ) );
java.sql.Types
33
Results: Getting the data• Each row is handled in turn
– iterate over the rows
// position to first recordboolean moreRecords = rs.next(); // get row datado { rows.addElement( getNextRow( rs, rsmd ) ); } while ( rs.next() );
// position to first recordboolean moreRecords = rs.next(); // get row datado { 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;
case Types.VARCHAR: currentRow.addElement( rs.getString( i ) ); break;case Types.INTEGER: currentRow.addElement( new Long( rs.getLong( i ) ) ); break;
34
Example: DisplayAuthors.java
• Deitel: Fig 25.25
• Database ‘books’
• Created using MySQL database management system (sec. 25.5)
• Exercises: 25.2 - 4
35
Servlets
Deitel 6e Chapter 26
36
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
37
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
38
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
39
• 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.
CGI Request…contd
40
HTTP and CGI
• define how data from a web form is encoded and transmitted to the web server
• two types of requests for pages:
Web ServerClient App
get
post
41
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
42
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
43
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
44
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-US-ASCII information in message headers.
45
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();
}
46
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();
}
47
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
48
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
49
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
50
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.
51
Tomcat Homepage
52 2003 Prentice Hall, Inc.All rights reserved.
Outline
WelcomeServlet
Lines 4-5
Line 8
Lines 11-42
Line 15
Line 16
Lines 21-40
1 // Fig. 24.5: WelcomeServlet.java2 // A simple servlet to process get requests.3
4 import javax.servlet.*; 5 import javax.servlet.http.*;6 import java.io.*;7
8 public class WelcomeServlet extends HttpServlet { 9
10 // process "get" requests from clients 11 protected void doGet( HttpServletRequest request, 12 HttpServletResponse response ) 13 throws ServletException, IOException 14 {15 response.setContentType( "text/html" ); 16 PrintWriter out = response.getWriter(); 17
18 // send XHTML page to client19
20 // start XHTML document 21 out.println( "<?xml version = \"1.0\"?>" );22
23 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +24 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +25 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 26
Import the javax.servlet and javax.servlet.http packages.
Extends HttpServlet to handle HTTP get requests and HTTP post requests.Override method doGet to provide custom get request processing.
Uses the response object’s setContentType method to specify the content type of the data to be sent as the response to the client.
Uses the response object’s getWriter method to obtain a reference to the PrintWriterobject that enables the servlet to send content to the client.
Create the XHTML document by writing strings with the outobject’s println method.
53 2003 Prentice Hall, Inc.All rights reserved.
Outline
WelcomeServlet
Line 41
27 out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
28 29 // head section of document
30 out.println( "<head>" );31 out.println( "<title>A Simple Servlet Example</title>" );
32 out.println( "</head>" );33
34 // body section of document35 out.println( "<body>" );
36 out.println( "<h1>Welcome to Servlets!</h1>" );37 out.println( "</body>" );
38 39 // end XHTML document
40 out.println( "</html>" );41 out.close(); // close stream to complete the page
42 } 43 }
Closes the output stream, flushes the output buffer and sends the information to the client.
54 2003 Prentice Hall, Inc.All rights reserved.
Outline
WelcomeServlet.html
1 <?xml version = "1.0"?>2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">4
5 <!-- Fig. 24.6: WelcomeServlet.html -->6
7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Handling an HTTP Get Request</title>10 </head>11
12 <body>13 <form action = "/jhtp5/welcome1" method = "get">14
15 <p><label>Click the button to invoke the servlet16 <input type = "submit" value = "Get HTML Document" />17 </label></p>18
19 </form>20 </body>21 </html>
55
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•
56
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
57
WelcomeServlet…contd
• Examples
• Exercises 26.5-7