1 / 57

CG0093 Weeks 9-10 Networking, JDBC and Servlets

CG0093 Weeks 9-10 Networking, JDBC and Servlets. Sajjad Shami Michael Brockway School of Computing, Engineering & Information Sciences Northumbria University. Networking in Java. Deitel: 6e: Chapter 24. Networking. Introduction Manipulating URLs; Java plug-in

doria
Télécharger la présentation

CG0093 Weeks 9-10 Networking, JDBC and Servlets

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CG0093 Weeks 9-10Networking, 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 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

  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. 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. 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

  21. Java and Databases: JDBC Deitel 6e Chapter 25

  22. 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 People

  23. 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

  24. SQL…contd. SELECT FirstName FROM People WHERE email LIKE ‘*corner*' SELECT LastName,FirstName FROM People WHERE 'WorkPhone=23423'

  25. JDBC • connecting to a database • Load the Drivers • Make the connection • submitting a query • interpreting the results • what is returned • extracting the result data

  26. Loads the driver class for the database connection Connecting to a database 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

  27. Connecting to a database…contd. Database URL The ODBC Sub-Protocol (Microsoft) The Data source name jdbc:odbc:books The sub-protocol scheme will change depending on the host database used. The JBDC Protocol

  28. 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

  29. 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 ) );

  30. 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;

  31. Example: DisplayAuthors.java • Deitel: Fig 25.25 • Database ‘books’ • Created using MySQL database management system (sec. 25.5) • Exercises: 25.2 - 4

  32. Servlets Deitel 6e Chapter 26

  33. 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

  34. 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

  35. 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

  36. 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. 

  37. 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

  38. Get and Post • Post: URL just points to the resource • http://localhost/servlets/generatePage • Get: information is placed in the URL • http://localhost/servlets/generatePage?no=234&id=john 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 • Getmethod 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

  39. 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

  40. HttpServlet • public void doGet ( HttpServletRequest request, HttpServletResponse response ) • is called by server in response to http getrequest • 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

  41. 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.

  42. 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(); }

  43. 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(); }

  44. Servlet Parameters • can be used to generate the appropriate output • are passed in the URL for getand 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

  45. 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

  46. 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

  47. 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.

More Related