Tài liệu XML, XSLT, Java, and JSP: A Case Study in Developing a Web Application- P5 pptx

50 691 0
Tài liệu XML, XSLT, Java, and JSP: A Case Study in Developing a Web Application- P5 pptx

Đ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

182 Chapter 7 JavaServer Pages: The Browseable User Interface birds with one stone: It would solve the refresh problem and give us material for our chapter about applets, Chapter 9, “Java Applet Plugged In: bonForumRobot.” Because we also wanted to avoid using scripting languages on the client side, we decided not to pursue the experimentation with HTML pragma, buffering pages, and so on. Instead, the robot applet idea was born and provided an alternative, Java-related solution to the problems inherent in frequent refreshes of a page. For all the gory details of how it works, read Chapter 9. We pointed out that the robot applet on the _robot JSP we are discussing gets its parameter values from session attribute values that are set on the top page in the group of pages handling the “host executes chat” phase of the Web application host_exe- cutes_chat.jsp. If we look there again, we will see by the value used to set the document session attribute that this particular applet instance will continually try to display the file named host_executes_chat_frame.jsp. This means that it is going to refresh the display of the chat messages that the host sees.That is something that we would like to do as frequently as possible, allowing for the bandwidth and physical manifestation of such a repeatedly fired Web page.When a guest in the chat adds a message, we want it to show up in the display of all the users as soon as possible. How does the user break out of the frameset that is representing the “host executes chat”Web application phase? We saw before, in host_executes_chat_controls.jsp, that the host can do one of three things: send a message to the chat guests, exit from this chat, or enter command mode. Again, this choice is presented in the code as follows: <table border=”0” cellspacing=”0” cellpadding=”0” rows=”4” cols=”1” width=”100%” ➥ bgcolor=”#00FFFF”> <tr> <label for=”bonCommand”>send this message</label><input type=”radio” name=”bonCommand” value=”host_executes_chat_controls” CHECKED></input> </tr> <tr> <label for=”bonCommand”>exit this chat</label><input type=”radio” name=”bonCommand” value=”host_executes_chat_ready”></input> </tr> <tr> <label for=”bonCommand”>enter command mode</label><input type=”radio” name=”bonCommand” value=”host_executes_chat_console”></input> </tr> <tr> <input type=”hidden” name=”actorReturning” value=”yes”></input> <input type=”submit” value=”Do it!” name=”submit”></input> </tr> </table> One of these Web app destinations, the “host executes command” state, will be dis- cussed only briefly here. If you have followed the discussion so far, you will possess the information needed to understand the following seven interrelated JSP pages that are 07 1089-9 CH07 6/26/01 7:32 AM Page 182 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 183 7.2 Viewing bonForum from Its JSP Documents together involved in offering the chat host some commands to execute.You will have noticed that we have not provided many commands yet, but we have set up the frame- work and the manner in which more host (and other actor) commands will be added later. host_executes_command.jsp host_executes_command_frame.jsp host_executes_command_controls.jsp host_executes_command_ready.jsp host_executes_command_robot.jsp host_increases_rating.jsp host_decreases_rating.jsp The three commands now available for the host to execute do the following: n Increase the status of a guest n Decrease the status of a guest n Change the number of messages displayed to the host A host can select one guest in the chat from a list of guests displayed by the _frame JSP host_executes_command_frame.jsp. That list is being produced by an XSLT transformation of the information con- tained in the hashtable -based database of the BonForumEngine class. For a relevant dis- cussion, see Section 10.13, “Displaying the Guests in a Chat,” in Chapter 10. The overall idea is that the Web application will automatically remove from a chat any guest whose rating has decreased to 0. Furthermore, the Web application will automatically change the role of an actor from that of chat guest to that of chat host as soon as the rating of that guest reaches some set value, such as 10 points. The design envisions these multihosted chats, as well as multichat forums and mul- tiforum chat networks. However, the code for these was not considered as high of a priority as those more fleshed-out portions of the Web application. When you are trying out this part of the Web application (you are doing that, aren’t you?), you should definitely try increasing and decreasing a guest’s rating, changing the number of chat messages being displayed, and exercising the navigator buttons in con- junction with smaller lists. (You may even discover that showing the first page of sev- eral is still a bit rough, although it works.) This simple exercise in user feedback in JSP should make you aware of the possibilities of control mechanisms that can be designed with similar techniques. Notice that there is again a robot applet on a JSP: host_executes_command_robot.jsp. In a manner similar to the one discussed for the host executes chat bonForum state, this JSP works in conjunction with its top-level JSP, host_executes_command.jsp.Together, they refresh the list of chat guests on the HTML produced by the JSP host_executes_command_frame.jsp. 07 1089-9 CH07 6/26/01 7:32 AM Page 183 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 184 Chapter 7 JavaServer Pages: The Browseable User Interface At this point in this chapter, you should know enough about the bonForum Web application to be able to decipher the functioning of the rest of the JSP files in the folder TOMCAT_HOME\webapps\bonForum\jsp\forum. Some of these files are better discussed in other contexts, such as the use of Java servlets in Java-and- XML–based software, so they will be visited in later chapters. 7.2.13 visitor_joins_chat_frame.jsp We next briefly discuss visitor_joins_chat_frame.jsp, which is of considerable interest in the context of XML and XSLT.We concentrate on presenting things from the JSP point of view. We first make sure that we can use our tag library from this page by referring to the taglib URL: <%@ taglib uri=”http://www.bonForum.org/taglib/bonForum-taglib” prefix=”bon” %> The Tomcat Server will know how to resolve this reference and will be capable of using the .tld file to find the tag classes when it translates the JSP file into a Java servlet source file. Look at one of these sometime for a JSP with a custom tag on it, to better understand how tags merge your tag class code into the code produced by a JSP. The JSP now being discussed simply lists all the available chats to the bonForum visitor, allowing that user to select and submit a chat to join.To actually join it, the user must then click a button on the controls frame. Too Many Clicks? As an aside, this has been criticized as a stupid design—why so many clicks just to join a chat? Our answer is that we are not trying to design the simplest and best user interface now, but instead we’re trying to design a prototype that will enable us to explore and solve problems. For example, we are inter- ested in the problems encountered when several cooperating JSP reside in frames. We are essentially in the business here of creating problems! That does get criticized for being an academic exercise rather than a serious, practical example of a Web application. We would rather call it R&D than academic, but we also recognize that the way we research software technologies is not everyone’s cup of tea. As to whether it is practical, that depends on whether you can learn anything practical from it (we certainly have!). As to whether it is serious, that depends on whether you are having fun yet (seriously!). We first developed the code to display available chat topics with XSLT by writing JSP scriptlets directly on the JSP document.After we had the code working (at least, for one or two users), we moved it all into a custom tag class.The code ended up finally in the TransformTag class, defined by the file TransformTag.java. (See Figure 7.5.) Prototyping the XSLT custom tag to produce a chat list display is discussed in section 10.10, “XSLT and the bonTransform Command,” in Chapter 10. 07 1089-9 CH07 6/26/01 7:32 AM Page 184 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 185 7.2 Viewing bonForum from Its JSP Documents What we designed is a way to call the Apache Xalan XSLT processor to apply an XSL style sheet to the chat room data that the Web application contains at runtime. The outcome of such a process will be an XML document, which (in this case) is used to display to the user the list of chats that can be joined in bonForum. Here is how the TransformTag is used to generate that list: <bon:transform type=”bonTransform” inDoc=”bonForumXML” styleSheet=” \\webapps\\bonForum\\mldocs\\bonChatItems.xsl” outDoc=”output”> <%=output%> </bon:transform> We have already discussed the way we first put the results of the XSLT into the HTML produced by the JSP. (See section 6.1.13, “Including Documents in a JSP,” and section 6.5.1, “Including XSLT Output on JSP Output,” in Chapter 6.) We now out- put the resulting select list of available chats not to a file, but to a string named output that is created by the BonForumTagExtraInfo class.This gives us the possibility of reusing the results elsewhere, if we change the setting of the extra tag information so that it is visible outside the custom tag body. Figure 7.5 HTML displayed by visitor_joins_chat.jsp and related JSP documents. In the following code scriptlet, you can see how this JSP page gets the value of the currently chosen chatItem to display to the user.When the user clicks the Submit but- ton to choose the selected chat, the form is sent by an HTTP POST method to the BonForumEngine servlet.The request makes a round-trip because of the value of the bonCommand request parameter.That refreshes the HTML produced by the JSP and 07 1089-9 CH07 6/26/01 7:32 AM Page 185 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 186 Chapter 7 JavaServer Pages: The Browseable User Interface updates the selected chatItem —the chat that was just chosen from the selection list. <% String chatItem = (String)session.getAttribute(“chatItem”); String chatItemMessage = “chat: &lt;none&gt;”; if(chatItem != null && chatItem.trim().length() > 0) { chatItemMessage = “chat: “ + chatItem; } %> Finally, the current chat is displayed to the user using the following JSP expression: <%=chatItemMessage%> 7.2.14 All Those Other JSP Files By now, you should have the information required to understand all the other JSP pages in the Web application.They are just variations on the themes we have been dis- cussing here. You can read functional descriptions of all the JSP pages in Section 6.1.5, “The States of the Forum,” in Chapter 6. Figure 7.6 shows the HTML dsplayed by guest_executes_chat.jsp. Some of the JSP pages not discussed are quite simple.They only forward the request to the next page using the following JSP trick: <jsp:forward page=”visitor_executes_choice.jsp”/> Figure 7.6 HTML displayed by guest_executes_chat.jsp and related JSP documents. It might seem that these pages are not needed, but remember that this version of bonForum is really just a framework for building a complete Web chat application. These pages that just forward the request (such as host_exits_forum.jsp) represent one Actor-Action-Thing state in the Web application. It will be far easier to add function- 07 1089-9 CH07 6/26/01 7:32 AM Page 186 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 187 7.3 Further Discussion About the JSP in bonForum ality later, if we have the entire design represented in the JSP pages. For example, later we will change things so that, when a host leaves the bonForum, most of the data that was added for that host will be deleted.We can do this very con- veniently from our host_exits_forum.jsp page. Quite a bit more complex is the processing that is done by the JSP servlet com- piled from the JSP page bonForum.jsp.There we use the bon:Transform tag command again, this time to use XSLT to get a list of available bonForum locations.The style sheet produces these in the form of a list of Web hyperlinks.We will discuss that more fully in Chapter 10 because the XSLT transform is handled by the code of the TransformTag class. 7.3 Further Discussion About the JSP in bonForum Before we leave this chapter, we want to further discuss two interrelated topics: n Using session attributes to pass data between JSPs n Reducing versus increasing the number of JSP files We are aware that we may be improperly using session objects when we use them to pass values for our applet parameters from one JSP to another.The criteria is whether these applet parameter values qualify as information about a specific user of the appli- cation and, thus, session information.They probably are better treated as thread-spe- cific information instead, and we should develop a way to use beans to pass the information in a thread-safe manner between these JSPs. Furthermore, why do we need to pass the applet parameter values into the _robot page at all? Why not just put the values directly into the applet parameters right on the _robot page? Using the same target parameter as we did in the last section as an example, that would mean doing this: <jsp:param name=”target” value=”display”/> The various other applet parameters would then also be hard-wired. Of course, that would work as well.The applet doesn’t care where it gets its strings. If we did it this way, we would have no need to use the session attributes to pass values from the JSP that creates the frameset to the JSP with the embedded robot applet. In fact, we could just put the jsp:plugin element in the _controls JSP and not even have a third frame.We would then get rid of all the _robot JSP files except for actor_leaves_frameset_robot.jsp. It all comes down to a balancing act. On one hand, especially in a chat application, performance is important, and “simpler” usually means “better performance.”That would argue in favor of reducing the number of frames, objects, and files—no need for all the robot session attributes, nor all the _robot JSP files. On the other hand, a key purpose of JSP is to create dynamic Web pages that are easily expandable and customizable.We see the design of bonForum as being a lot like one of those new and empty land subdivisions that will later become an entire suburb. Each JSP can be seen as Web real estate that can later be filled in with content.The 07 1089-9 CH07 6/26/01 7:32 AM Page 187 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 188 Chapter 7 JavaServer Pages: The Browseable User Interface application pages could certainly use more and better content. You will also no doubt have noticed, for example, that there is very little difference among many of the JSP files in the bonForum project. If that is so, why not just replace every group of similar JSP files with just one? We could take care of any differ- ences that exist some other way. For example, we could replace this lot of files: guest_executes_chat_robot.jsp guest_executes_command_robot.jsp host_executes_chat_robot.jsp host_executes_command_robot.jsp visitor_joins_chat_robot.jsp visitor_starts_chat_robot.jsp These six JSPs could all be replaced by one file, which we could call actor_refreshes_frame_robot.jsp. The only other changes needed would be to the top-level JSP files in each bonForum state that uses a refresh robot, which are these files: guest_executes_chat.jsp guest_executes_command.jsp host_executes_chat.jsp host_executes_command.jsp visitor_joins_chat.jsp visitor_starts_chat.jsp We would replace the entire robot frame element in all these files.Those are now all similar to this: <frame src=”/bonForum/jsp/forum/host_executes_chat_robot.jsp” name=”robot”/> They would now all contain the same robot frame element, which would be like this: <frame src=”/bonForum/jsp/forum/actor_refreshes_frame_robot.jsp” name=”robot”/> On the face of it, replacing six files with one seems like a no-brainer. However, if you look at each one of those replaceable _robot JSP files as defining a customizable piece of Web real estate that is related to a particular state of a Web application (for example, the user is joining, starting, chatting, commanding, hosting, and being a guest), then you can argue that having all those files is a better framework to build upon than hav- ing just the one file. It is a bit like biodiversity being favorable for evolution. 07 1089-9 CH07 6/26/01 7:32 AM Page 188 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Java Servlet and Java Bean: BonForumEngine and BonForumStore 8 I N THIS CHAPTER , YOU LEARN ABOUT TWO classes central to the bonForum Web application. BonForumEngine is a servlet in charge of handling HTTP requests and responses. BonForumStore is a nonvisual bean that implements chat logic and encapsu- lates the XML chat database.You will want to have the source code and javadocs for the project—and a large cup of java—available because the discussion here will not shy away from the details.The chapter also illustrates some themes common to using Java servlets and beans in Web applications. 8.1 The BonForumEngine Servlet This chapter is divided into two parts:The first covers the BonForumEngine servlet, and the second covers the BonForumStore bean.The servlet will be discussed in more detail because the problems that it solves are more universally encountered by developers of Web applications. After a brief introduction to the purposes of the servlet and its con- text in the Web application, we proceed to a discussion of its two major methods, the service() method and the processRequest() method.Whenever possible, code that is not dependent on the nature of the application (chatting) has been placed in the service() method, while code that is more related to the specific needs of the Web application (chatting) has been put in the processRequest() method. 08 1089-9 CH08 6/26/01 7:33 AM Page 189 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 190 Chapter 8 Java Servlet and Java Bean: BonForumEngine and BonForumStore 8.1.1 Purpose of the BonForumEngine Class The main purpose of the BonForumEngine class is to connect and coordinate all the JSP documents in the Web application. By extending the HttpServlet abstract class, it can receive the many simultaneous HTTP requests being generated by the browser user interface discussed in Chapter 7, “JavaServer Pages:The Browseable User Interface.” BonForumEngine forwards each request it receives to a “destination” JSP.This servlet is the engine that moves every instance of bonForum from one state to the next. Before forwarding each request, it can also process it, which it does in relation to the bonForum Web application.That “chat” processing relies heavily on the methods of the BonForumStore class, which is the subject of the second part of this chapter (see Section 8.2, “The BonForumStore Class”). Here is a listing of most of the functions of BonForumEngine : n Provides multiple, simultaneous contexts for Web application n Allows multiple simultaneous user threads to be serviced n Prevents entry to an application except from login page n Enforces unique nicknames within application instance n Acts as a switchyard for different HTTP request categories n Manages the Web application s ession objects n Processes HTTP request objects as a Web (chat) application n Processes and forwards applet-generated JSP requests n Processes information from all JSPs in the Web application n Initializes the XML data wrapper, a BonForumStore instance n Sets up an application scope reference to BonForumStore n Makes user input available to chat processes, by session n Processes chat messages from JSP users to other JSP users n Manages XML data items for multiple simultaneous users n Forwards users from JSP to JSP with programmatic control n Provides extension and customization mechanism for Web app n Provides some examples of user input verification The best way to understand any distributed application is perhaps from the point of view of the host (or hosts) that connect the clients.These connections create contracts that define the allowable transactions: between the clients, between the clients and databases, and so on. Just trying out the bonForum chat software as a chat host or as a chat guest will not reveal the mechanics of this Web application.The following discus- sion of the BonForumEngine and BonForumStore classes will hopefully make clear some of the Ozian wizardry behind the curtain. 08 1089-9 CH08 6/26/01 7:33 AM Page 190 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 191 8.1 The BonForumEngine Servlet 8.1.2 Web Application Context for this Servlet Although Tomcat is a complete HTTP server, its specialty is handling Java servlets and JavaServer Pages (JSP).The Tomcat configuration file web.xml determines what Tomcat does with the various requests that it gets, whether directly from a browser or from another server such as Apache.The following document type links the web.xml configuration file to a definition of what a Web application should look like: <!DOCTYPE web-app PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN” ➥ “http://java.sun.com/j2ee/dtds/web-app_2.2.dtd”> According to that definition, a Web application description is enclosed in a pair of matching root element tags, <web-app> and </web-app> . Among the many element types that can exist within that Web app element are child elements enclosed within the tag pair <servlet> and </servlet> .These servlet elements enclose other elements that can contain the name, class, and parameter infor- mation for each servlet that the Web app should know about. Web Application Deployment Descriptor for bonForum The web.xml Web application deployment descriptor for bonForum can be found in the following file: TOMCAT_HOME\webapps\bonForum\web-inf\web.xml Servlet Element This is the servlet element for the BonForumEngine Java servlet, as found in that con- figuration file: <servlet> <servlet-name> BonForumEngine </servlet-name> <servlet-class> de.tarent.forum.BonForumEngine </servlet-class> <init-param> <param-name> bonfoo47 </param-name> <param-value> bonbar47 </param-value> </init-param> </servlet> This servlet element in the web.xml file tells Tomcat that within the context of the Web app that is being configured (bonForum), the name “ BonForumEngine ” will refer to the Java class: de.tarent.forum.BonForumEngine 08 1089-9 CH08 6/26/01 7:33 AM Page 191 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... parameter named Logging has a value of all, which turns on the logging output both to logfiles (one for each major object) and to the console (the standard error output, actually) Here is how we make that Web app global information available: Logging all To access context-initialization parameters from within a servlet,... nearly as much as we would have otherwise You probably noticed that not all the JSP pages in the application are being requested via the servlet mapping, but they are nevertheless represented in this “switchyard.”We added all the pages in the Web app to make experimenting easier Working with JSP can be quite fast and interactive, and we like things that make it more so One final point: Instead of having... 9, the login page would end up being displayed inside the frame!) The applet came in handy here, even though its real jobs are refreshing JSP-generated HTML frames and switching application framesets, as explained in Chapter 7 and Chapter 9,“Java Applet Plugged In: BonForumRobot.” After this look at the overall tasks and design of the service() method, and the details of a few key characteristics, we... 7:33 AM Page 192 192 Chapter 8 Java Servlet and Java Bean: BonForumEngine and BonForumStore Servlet Initialization Parameters To illustrate how you can pass initialization parameters to a servlet, we have included a purely illustrative parameter name, bonfoo47, and value bonbar47.To access this parameter from within the BonForumEngine servlet, you could use something like either of these two equivalent... can last only as long as the session that creates it (More accurately, a chat can outlive the session that created it, but it will no longer have a host, and so is not fully functional.) A session can last until it is inactive for more than a maximum inactivity interval, which can be set using the setMaxInactiveInterval session method.We set that to allow chats to withstand inactivity longer than they... request forwarded to another JSP destination in the Web app.The bonCommand originates on a JSP-generated form and is available to the service() method as a request parameter Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 08 1089-9 CH08 6/26/01 7:33 AM Page 198 198 Chapter 8 Java Servlet and Java Bean: BonForumEngine and BonForumStore 2 You can think of bonForumCommand as the... with a URI of BonForumEngine and a valid bonCommand value automatically gets a BonForumEngine with the same value as the bonCommand.That is how a JSP form can select the next JSP in the Web application 5 Other requests transiting the service() method have arrived only because of a servlet mapping for URIs that end in tfe (as discussed in the previous section, “Servlet-Mapping elements”) For example,... using a unique identifier, a session can “brand” all the requests that come from one browser instance over a period of relative activity If you need to learn more about how Java handles sessions, we recommend reading Chapter 9, “Session Tracking,” of Marty Hall’s book, Core Servlets and JavaServer Pages Another excellent and very interesting way to learn more is to study the source code in Tomcat that... Processing,” some incoming requests get a serviceStatus of CheckInAtEntrance.The service() method makes sure that each of these requests has a session object (and gets its ID for later use).The maximum inactivity interval for each session is set from a user-supplied value Finally, the serviceStatus is changed to ProcessRequest Until we add a user manager and chat data persistence, a chat in bonForum can... URI”) In that case, information that is equivalent to that of bonCommand can instead be found embedded in the URI itself.) CheckInAtEntrance Requests that have bonCommand values end up classified in the ProcessRequest service status, unless they fall in either of two special categories.The first belong to the CheckInAtEntrance service status By design, only the first page of the Web app creates a boncommand . the user is joining, starting, chatting, commanding, hosting, and being a guest), then you can argue that having all those files is a better framework to. and encapsu- lates the XML chat database.You will want to have the source code and javadocs for the project and a large cup of java—available because the

Ngày đăng: 14/12/2013, 22:15

Từ khóa liên quan

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

  • Đang cập nhật ...

Tài liệu liên quan