Web Server Programming phần 6 docx

63 282 0
Web Server Programming phần 6 docx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Client state and sessions 301 The CheckoutServlet gets invoked when the client follows one of the links in either a products form page or the response page produced by the PurchaseServlet Its doGet method uses private helper functions to produce a display of the contents of the ‘shopping cart’ vector // The usual imports public class CheckoutServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession current = request.getSession(false); if(current==null) { response.sendRedirect("/demo2/Login.html"); return; } listOrderItems(current, response); } private void listOrderItems(HttpSession current, HttpServletResponse response) throws ServletException, IOException { response.setContentType(”text/html”); PrintWriter out = response.getWriter(); out.println("Your order "); out.println(""); Vector v = (Vector) current.getAttribute("shoppingcart"); if(v!=null) { out.println("Items in your cart"); out.println("
    "); Enumeration e = v.elements(); while(e.hasMoreElements()) { String str = (String) e.nextElement(); out.print("
  • "); out.println(str); } out.println("
"); } else out.println("The shopping cart was empty"); out.println(""); out.println(""); } } 302 Java Servlets The LoginServlet made use of a SubscriberRecord’s ability to load itself from the members data table: import java.sql.*; public class SubscriberRecord { // As shown for the "members" example public boolean loadFromDatabase(int idNumber, Connection db) { // Try to load data for record with key idNumber // Clear private data members givenName = null; familyName = null; eMail = null; sex = null; age = 0; id = 0; try { // Claim exclusive use of database synchronized(db) { Statement stmt = db.createStatement (); String request = "select * from members " + "where membernumber=" + idNumber; // Run the query, if get a result copy data ResultSet rset = stmt.executeQuery(request); if(rset.next()) { givenName = rset.getString("GIVENNAME"); familyName = rset.getString("FAMILYNAME"); eMail = rset.getString("EMAIL"); sex = rset.getString("SEX"); age = rset.getInt("AGE"); id = idNumber; stmt.close(); } else stmt.close(); // Database in mode where require explicit commits db.commit(); } } catch (Exception e) { return false; } Client state and sessions 303 // Return success/failure result return id==idNumber; } } The deployment file continues to be quite simple It identifies the servlets and the URLs that are used when accessing them: loginservlet LoginServlet booksservlet BooksServlet loginservlet /login booksservlet /Books This servlet version has two advantages over the PHP script version of the same site First, when properly deployed in would be packaged as a single war file that contains all static pages and the WEB-INF subdirectory with the deployment file and its directory of class files This packaging makes the application simpler to move and re-deploy Second, the memory resident session object is a more efficient representation of the state data than the file that is used with PHP; and, further, the container takes responsibility for any abandoned sessions 304 Java Servlets 7.6 Images The PHP ‘Big Brother’ voting example illustrated how images are often the best way of presenting response data While the PHP image libraries seem a little easier to use than their Java counterparts, it is possible for a servlet to return a GIF image (or other format image) Generation of images requires the use of classes that are not in the standard Java libraries Standard Java awt code can create an image, but the image must be encoded in GIF or JPG format before it can be returned to a client Image encoders are available from Sun (in the package com.sun.image.codec.jpeg) or from http://www.acme.com/ The acme.com web site has links to a useful library of Java components that includes a GIF encoder A servlet can generate an image file as a response by: G Using the ServletOutputStream associated with the response rather than the usual PrintWriter A ServletOutputStream supports output of binary data G Setting the content-type of the response to image/gif (or image/jpg as appropriate) G Using an instance of Java’s BufferedImage class G Getting the associated Graphics object G Using this Graphics object to perform java.awt drawing operations G Encoding the resulting image (You may have problems running graphics examples on a shared Unix server with Xlib graphics; these are essentially configuration problems At some points, the Java awt code seeks information about the graphics devices available If none are defined, the image is not generated The Xlib graphics library relies on an environment variable, DISPLAY, referencing an X-server You should seek help from your system administrator regarding the setting of this environment variable Java 1.4 awt has some extra functionionality aimed at avoiding such problems.) The example generates a fixed image purportedly illustrating a histogram of utility usage; its output is illustrated in Figure 7.1 The image is GIF-encoded, using the package Acme.JPM.Encoders from http://www.acme.com/ The Acme package should be downloaded and installed in the classes directory where the servlet is defined (the package is quite large; you can save space by extracting just the GIF encoder and its support classes and changing the import statements in the example code) Figure 7.1 A simple graphic image response page from a servlet Images 305 The servlet code is: import import import import import import import java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*; java.awt.*; java.awt.image.*; Acme.JPM.Encoders.GifEncoder; public class HistogramServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Graphics g = null; try{ // Pick up output stream for binary data ServletOutputStream out = response.getOutputStream(); // Set the header type to say that we are returning an // image (gif encoded) response.setContentType("image/gif"); // Create work space for building image in memory BufferedImage bi = new BufferedImage( 400,600, BufferedImage.TYPE_4BYTE_ABGR); // Get the Graphics object that can be used to "draw" // in workspace image g = bi.getGraphics(); // Draw g.setColor(Color.white); g.fillRect(0,0,400,600); g.setColor(Color.black); g.drawString("Usage Histogram", 20,20); g.setColor(Color.black); g.drawString("Aug 2000", 10, 40); g.setColor(Color.blue); g.fillRect(80, 30, 100, 20); // When image is complete, get an encoder, // In this case, the Acme gif encoder // Arguments are image and stream to which will // write encoded version GifEncoder encoder = new GifEncoder(bi, out); 306 Java Servlets // encode and send to client encoder.encode(); } finally { // Always remember to tidy up after using a Graphics // object if(g!=null) g.dispose(); } } } 7.7 Security features Servlet containers incorporate security controls that are a limited extension and refinement of HTTP authentication Restrictions can be placed on servlets; only logged in users can access restricted servlets The restriction system can even differentiate among different servlet methods – some users might be able to use both get and post (read and update) methods of a servlet, while others might be restricted to get (read) access to the same servlet Security restrictions are primarily a deployment issue A servlet can be written and then deployed in different environments with or without security restrictions However, if a servlet is designed for use with security restrictions, its code can obtain details of the permissions pertaining to the current client; these details are obtained from the servlet container This allows a servlet to generate dynamic pages with content specifically selected for different classes of users Restrictions are not defined for individual users; instead they apply to ‘roles’ that users may fill Really, ‘roles’ are simply the same as user groups in HTTP authentication In HTTP authentication, users can have individual names and passwords in the password file, while a group file contains a list of ‘groups’ and the user-identifiers of the members of each group With servlets, ‘roles’ replace ‘groups’ The password files contain entries for each user; the entries comprise username, password and a list of the roles permitted to that user The deployment specification, the web.xml file, contains any restrictions on access to servlets The restrictions are composed of the following elements: G Security constraints: These identify the restricted servlets and methods Servlets are restricted to users who are acting in specified roles Login configuration: This element defines how the login process is handled The choices include use of the normal HTTP authentication dialog, a customized version of the standard dialog, and more elaborate schemes using digests or client authentication certificates G G Security roles: These elements simply list the role names that are referenced in the security constraints and in the associated password files Security features 307 Browser support for digests and client certificates is limited; usually, the login constraints for servlets are either ‘basic’ (use the default browser support for HTTP authentication) or ‘form’ (use a customized version of the HTTP authentication) The form style is preferred because it allows for a site-specific login page that can provide help information along with input fields for a user’s name and password The example for this section illustrates: G Form authentication G Using roles to adapt behavior of servlets G Using shared data held in an attribute of the servlet’s context The example is a web application that records the times that employees spend on different tasks and calculates pay The application comprises a number of servlets and associated static HTML pages There are three classes (roles) of user: ‘boss’, ‘manager’ and ‘worker’ The application has a simple database with three tables: one table records details of work times (employee identifier, hours, task), another records employee/manager relations (managers can inspect their employees’ records), and the third table contains pay rates for different types of task The servlets are: G Hours servlet G Rates servlet G ShowRecord servlet Employees in all roles can use the Hours servlet; however, its detailed behavior is roledependent The doGet method displays a form that can be used to enter the hours worked and task type The task type is chosen from a dynamically generated option list – while there are some overlaps, the types of tasks performed by workers, managers and the boss vary The doPost method is common to all users; it adds a work record to the work data table The ShowRecord servlet is similar in that it can be used by all employees, but its behavior is again role-dependent Employees in the worker role can use this servlet to obtain a display of their own individual records Managers can see their own records or the records of any employee that they manage A worker is immediately shown their personal data; a manager is presented with a form in which the name of an employee can be entered When this name is returned to the servlet, that employee’s record will be displayed (if the manager is permitted to see the data) Only an employee in the boss role can use the final servlet: Rates This servlet can be used to add new task types or change the pay rates associated with existing task types In total, the application comprises: G Static HTML pages: – Login page Customized login page for entry of name and password (see Figure 7.3 on p 310) 308 Java Servlets – Error page Users are redirected to this page if the entered name/password combination is invalid – Bad data Used to display error messages for erroneous inputs – No DB Used to display error messages if any database operation fails – No access Error report page for an attempt to view records without authority G Servlets and support classes: – RateChangeServlet – insert or update records in rates data table; also updates an inmemory copy – WorkerServlet – record hours worked and task – CheckRecords servlet – inspect records of self or subordinate – DBInfo Helper class for establishing connection with database – RatesRecord An object that contains an in-memory representation of data held in the main rates data table; held as an attribute of the context and available to all servlets in this application G Data tables (illustrated in Figure 7.2): – Work Fields: name and activity as varchar, hours as double This holds records of the time an employee spent on a task of a specified type – Manages Fields: Employee and manager (both varchar) This holds records identifying employees and their immediate manager – Rates Fields: task (varchar) and rate (double) This holds the defined task types and corresponding pay rates G Deployment controls – Web.xml ‘Web app’ deployment file with security controls – tomcat/conf/users.xml File in main Tomcat configuration directory that must be updated with names, passwords and roles of the users of the web application There should be a tomcat-users.xml file in the tomcat/conf directory The default file contains three records used in the Apache supplied example illustrating security constraints on servlets Additional entries must be created in this file for user accounts invented for this web application Each entry consists of a single XML ‘user’ tag with attributes that define a username, a password and a list of roles permitted to that user The role names allocated must correspond to those that are defined later in the web.xml Security features 309 Manages Rates Employee Manager Activity Rate Anne Claire Thinking 1.5 Susan Claire Designing 2.5 David Claire Documenting 2.5 Martin Samuel Coding 4.5 Leila Samuel Testing Keith Samuel Debugging 7.5 Claire Colin Meetings 20 Sales presentations 30 Customer contact 35 Conference 100 Business lunch 120 Golf 145 Client entertainment 180 Work table Name Activity Hours Anne documenting Colin business lunch Anne coding Claire meetings David coding Anne thinking Leila documenting Leila coding Leila testing Figure 7.2 Illustrative tables for the time management web application deployment file The updated version of the tomcat-users.xml file as used for this example is: 310 Java Servlets Figure 7.3 A simple customized form for HTTP authentication The default browser-supplied dialog used for HTTP authentication is rarely appropriate Most companies will wish to customize their login page The servlet container supports such customization; the customized login page must simply use specified names for fields and return the inputs for processing by a specified action element The following login form produces the simple login page illustrated in Figure 7.3 Acme Record's Login Enter your name and password Name: Password: The required names for inputs and form action are highlighted (the names j_security_check etc reference standard parts of the servlet container) The login page, and an error page that is displayed if the name and password not match an entry in the tomcatusers.xml file, must be named in the web.xml file The typical error page informs users that they have entered invalid data, and provides a link that takes them back to the login page In this example, each servlet manages a private connection to the database As usual, a lock controls a connection so that only one thread can use a connection These servlets all perform their database activities in private auxiliary functions called from their doGet or doPost methods; these auxiliary functions are defined as synchronized – so applying a lock to the entire function that accessed the database Membership example 349 } public void setAge(String AgeStr) { Age = 0; try { int val = Integer.parseInt(AgeStr); if((val>=MINAGE) && (val The forward and include tags both take a single page attribute; its value is the URI for the resource to which the request is being transferred If the forward tag is used, then any partial generated response is discarded, and the request (along with any beans attached as attributes) is forwarded to the specified resource If the include tag is used, the output buffers with partial results are flushed (so sending headers and committing the response) and the request is passed to the other resource (servlet or JSP) When the other resource finishes, the current JSP should resume its processing of the request 8.5 Servlet, bean and JSP examples Servlets and JSPs are now both reasonably mature technologies, having been around for about five years Developers have experimented with different ways of using and combining these technologies The preferred strategy for Java server-side applications is now to limit the code in a JSP to that required for the display of dynamic data, to have control code in a pre-processing servlet, and to have application specific business logic in helper bean classes Further, as far as practical, action tags are preferred over scriptlet coding within the JSP component The example for this section illustrates the construction of a web application with this preferred form (It is a very small example, but it does resemble real applications; you have to use your imagination to scale it up and see how the suggested problems and solutions might work for real.) The example is developed in stages; it Servlet, bean and JSP examples 357 starts with a JSP and bean solution, where the JSPs contain a relatively large amount of scriptlet control code The servlet is then added to take over the control functions, allowing some simplification of the JSP code Finally, various substitutions of action tags for scriptlet code are explored The example is a reworking of the soccer league example that was used in Section 6.6 to illustrate how PHP could work with a database The database has a single table with the results of games in some imaginary soccer league Each record has four fields – the two teams and the two scores In this version the system supports just the queries – list all matches, list drawn (tied) matches, list away wins and list home wins The first version of the application has the following components: G Soccer.html This is a simple static page that allows the user to request a search for results of interest G Soccer.jsp Supposedly a highly graphic, attractive page that presents the results of a search G Beans (and other support classes) in package soccer: – SoccerSearchBean An instance of this class handles the actual search request, submitting an SQL query and processing the result set Results are returned as a collection of SoccerGame objects – SoccerGame This is a simple bean that has data members corresponding to the four data elements in each row of the Soccer table – DBInfo A helper class used to create a database connection; holds data such as database URL, driver name, and username and password Database This holds a single table, Teams, containing the records for matches G The application is deployed in tomcat/webapps/jspeg, with a WEB-INF subdirectory that initially contains only a classes/soccer subdirectory to hold the three support Java classes The JSP: G Gets the query type from the submitted form data G Creates a bean to organize the search and sets a field identifying the search type G Requests that the bean perform the search G Retrieves an iterator with the search results G Uses the iterator to generate rows for an HTML table The Soccer.html page has a series of links for the different search options These embody query strings with the search code The JSP will pick up the data as the value of the searchType request parameter 358 JSP: Java Server Pages Soccer searcher Search the little soccer league table
  • List all games
  • List away wins
The DBInfo class is essentially the same as that illustrated in Section 6.6 It provides a connectToDatabase method that returns a connection to the database identified by a URL string defined as a constant in the DBInfo class The SoccerGame class is not a true bean (it has no setX() mutator methods) It is really just a holder for the two String and two int data elements that hold details of a game It does have a set of getX() accessor methods, and it also has a method for copying data from a ResultSet object into its data members package soccer; import java.sql.*; public class SoccerGame { private String team1; private String team2; private int score1; private int score2; public public public public String String String String getTeam1() { return team1; } getTeam2() { return team2; } getScore1() { return Integer.toString(score1); } getScore2() { return Integer.toString(score2); } public void loadFromResultSet(ResultSet rset) throws SQLException { team1 = rset.getString("TEAM1"); team2 = rset.getString("TEAM2"); score1 = rset.getInt("SCORE1"); score2 = rset.getInt("SCORE2"); } } Servlet, bean and JSP examples A SoccerSearchBean: G Owns: – A string data member to hold the type of the search – A vector to hold a collection of retrieved SoccerGame objects – Some string constants for SQL queries G Does: – Allows setting of search type – Perform search, collecting results in memory – Reports on number of items found for search – Returns an iterator allowing access to retrieved items package soccer; import java.sql.*; import java.util.*; public class SoccerSearchBean { private static final String allstr = "select * from TEAMS"; private static final String drawstr = "select * from TEAMS where SCORE1=SCORE2"; // Similar SQL queries for home wins and for away wins private String searchType; private Vector results; public void setSearchType(String typ) { searchType = typ; } public Iterator games() { if(results!=null) return results.iterator(); else return null; } public int numGames() { if(results!=null) return results.size(); else return 0; } public void doSearch() { 359 360 JSP: Java Server Pages results = new Vector(); try { Connection db = DBInfo.connectToDatabase(); Statement stmt = db.createStatement(); String request = allstr; if("drawn".equals(searchType)) request = drawstr; else // Similar code to select query string // for other options ResultSet rset = stmt.executeQuery(request); while(rset.next()) { SoccerGame sg = new SoccerGame(); sg.loadFromResultSet(rset); results.addElement(sg); } rset.close(); stmt.close(); db.close(); } catch(Exception e) { } } } The JSP supposedly embodies ‘pretties’ – artwork, advertisements, links to related pages, some client-side JavaScript code for rollovers, pop-ups and other entertainments These elements are left to creative web designers Here, the focus is on the JSP scripting The Soccer.jsp file contains: Soccer League Results Little league soccer results Servlet, bean and JSP examples 361

There haven't been any such games yet But the season is young; come back again soon Results Home Team Away Team Home Team Score Away Team Score The JSP starts with a page directive with an import attribute The scriptlet code is going to be using a java.util.Iterator This dependence on the java.util package must be specified: 362 JSP: Java Server Pages The page starts with a fairly typical set of tags, specifying a bean that is to be used and copying form data into the new bean (you can put the setProperty action in the body of the useBean action, or have it as a separate entity – it really makes no difference): Scriptlet code is then used to invoke the search operation: Next, there is the large conditional construct: if (theLeague.numGames()==0) { } else { } The then clause in this conditional involves simple output of fixed HTML tags and content text The else clause is more elaborate; here the table of results must be formatted This involves some template text and the iterative loop that generates rows for the HTML table The embedded scriptlet coding is not too overwhelming But even in this simple case there are constructs like: Servlet, bean and JSP examples 363 The first scriptlet here is closing the while block; then there is a fragment of conditionally included template text (the tag); and finally, a second scriptlet fragment closes the block opened in the else clause above Such code is obviously fragile A non-programming web designer who is improving this page is quite likely to move or remove one of those scriptlet tags, resulting in code that will not compile Really, the application involves a request for a search that results in one of two different responses If there are results that match the search query, e.g the client requested ‘away wins’ and there have been some away wins, their details should be listed in a well-presented table If there are no results, a different response should be generated This is basically the approach taken in the next version of this web application A pre-processing servlet is used to handle the initial request It creates and runs the SoccerSearchBean The servlet then transfers control to one or other of two different JSPs to generate appropriate responses The components in the revised version are: G Soccer.html The links now reference the servlet’s URL, as specified in a web.xml deployment file MatchReport.jsp, NoResult.jsp These separate JSP components present the different styles of response for the different search outcomes G G web.xml A web.xml deployment file is required in any more sophisticated JSP system – either one using specialized libraries, or as here working with a servlet G PreprocessServlet.java This servlet has the control logic that runs the request and forwards results to the appropriate JSP display component (Code goes in the WEB-INF/classes directory.) G SoccerGame.java , SoccerSearchBean.java and DBInfo.java These helper classes are unchanged; they are in the WEB-INF/classes/soccer directory The deployment file, web.xml, is once again a simple one It defines the servlet and the URL that will be used to reference it in the Soccer.html page: SoccerServlet PreprocessServlet ... AcmeCompany < /web- resource-name> /Rates GET POST < /web- resource-collection>... time (j) In tom/demo /WEB- INF create a file web. xml with content such as:

Ngày đăng: 14/08/2014, 12:20

Tài liệu cùng người dùng

Tài liệu liên quan