Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 63 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
63
Dung lượng
670,55 KB
Nội dung
<servlet-mapping> <servlet-name>SoccerServlet</servlet-name> <url-pattern>/SoccerInfo</url-pattern> </servlet-mapping> </web-app> In this example, the role of the PreprocessServlet is simply to handle HTTP get requests. It could have been given responsibility for a persistent database connection; but this responsibility has been left in the SoccerSearchBean.ThedoGet function creates a SoccerSearchBean, sets its search type from the request parameter data and invokes its doSearch method. Depending on the results of the search, the doGet function uses one or other of the private auxiliary methods, doSuccess or doSearchFail, to deal with for - warding of the request to the appropriate JSP for final p rettying up. // The usual Servlet imports and import soccer.*; public class PreprocessServlet extends HttpServlet { // Constant strings; // The first few are different forms of failure message that can be // forwarded to a JSP that reports failed searches private static final String allstr = "We couldn't show you any results, the season hasn't started!"; private static final String drawstr = "There haven't been any drawn games yet this season."; private static final String homestr = "There haven't been any home wins yet this season."; private static final String awaystr = "There haven't been any away wins yet this season."; // These strings define the URLs for the JSPs that pretty // up the final response. private static final String jspFailPage = "NoResult.jsp"; private static final String jspReportPage = "MatchReport.jsp"; public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get form data from request String search = request.getParameter("searchType"); // Create and initialize the bean SoccerSearchBean ssb = new SoccerSearchBean(); ssb.setSearchType(search); // Run the search ssb.doSearch(); // Select appropriate reporting stage 364 JSP: Java Server Pages if(ssb.numGames()==0) doSearchFail(search, request, response); else doSuccess(ssb, request, response); } private void doSearchFail(String search, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // A failure results in a explanatory message being // forwarded along with the request to the "No Result" JSP // Pick the appropriate message string String reason = allstr; if("drawn".equals(search)) reason = drawstr; else if("home".equals(search)) reason = homestr; else if("away".equals(search)) reason = awaystr; // Add message as attribute of request request.setAttribute("Message", reason); // Prepare to forward RequestDispatcher dispatch = request.getRequestDispatcher(jspFailPage); // Forward request and error message dispatch.forward(request, response); } private void doSuccess(SoccerSearchBean ssb, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // The SoccerSearchBean has a vector of results for display // to the client. Add this bean as an attribute of the request, // and forward to the "Match Result" JSP request.setAttribute("theLeague", ssb); RequestDispatcher dispatch = request.getRequestDispatcher(jspReportPage); dispatch.forward(request, response); Servlet, bean and JSP examples 365 } } The data placed as attributes of the request (the String with a message, or the SoccerSearchBean) will be available to the JSP components as request-scope beans. The NoResult.jsp has to embed an error message into an ‘interesting’ response page. The interesting features can be left to a web designer. The minimal code for this JSP is: <% Imagine this to be a page filled with graphic pretties, along with the small amount of dynamic content as shown! %> <html><head><title>Soccer League Results</title></head> <body bgcolor=white> <h1 align=center><font color=red>No Results</font></h1> <p> <jsp:useBean scope="request" id="Message" class="String" /> <p> <%= Message %> </body></html> MatchReport.jsp has to format a table with th e resu lts of interest. It can obtain the SoccerSeachBean from the request and get the Iterator from the bean. Then it can have scriptlet code again to handle generation of the table rows: <% The usual apology - "this is really a pretty page with lots of HTML" %> <%@ page import="java.util.*" %> <%@ page import="soccer" %> <html><head><title>Soccer League Results</title></head> <body bgcolor=white> <h1 align=center><font color=red>Search Results</font></h1> <p> <% Pick up SoccerSearchBean with the data %> <jsp:useBean scope="request" id="theLeague" class="soccer.SoccerSearchBean" /> <table align=center border=2> <caption>Results</caption> <tr> <th align=center>Home Team</th> <th align=center>Away Team</th> <th align=right>Home Team Score</th> <th align=right>Away Team Score</th> </tr> <% Get Iterator from bean, use it to control while loop %> <% 366 JSP: Java Server Pages Iterator it = theLeague.games(); while(it.hasNext()) { SoccerGame sg = (SoccerGame) it.next(); %> <% Body of while loop, %> <% Once again a mix of template text and expressions %> <tr> <td><%= sg.getTeam1() %></td> <td><%= sg.getTeam2() %></td> <td><%= sg.getScore1() %></td> <td><%= sg.getScore2() %></td> </tr> <% Scriptlet tag closing the block started at while %> <% } %> </table></body></html> These changes have improved the JSPs. These now focus solely on presentation; there is no application logic and no comp lex nested con ditional code. But there is still scriptlet code for the loop and expressions for accessing data held in SoccerGame objects. You might have expected jsp:getProperty action tags to be used instead of the expres- sion, i.e. someth ing like <jsp:getProperty name="sg" property="team1" /> rather than <$%= sg.getTeam1() %> However, you cannot use jsp:getProperty tags on arbitrary scriptlet variables because of the way th e action tags are translated. An action like <jsp:getProperty name="x" property="y" /> does not translate to the Java code x.getY(). Instead, the code is some - thing along the following lines: ● Look up something called x in the ‘page context’ and find out what it is. ● Use reflection to find whether it has a getY() function. ● Build a Method object that will call this getY() on the appropriate x object. ● Run the Method object. If you want to use the action tag style on an ordinary scriptlet variable, you must first ‘promote’ th e variable – making its name and class known to the PageContext object that manages page context data. This can be done as follows: Servlet, bean and JSP examples 367 <% Iterator it = theLeague.games(); while(it.hasNext()) { SoccerGame sg = (SoccerGame) it.next(); pageContext.setAttribute("sg",sg,PageContext.PAGE_SCOPE); %> <tr><td> <jsp:getProperty name="sg" property="team1" /> </td> The PageContext.setAttribute method takes as arguments the identifier that will be used to name the object in getProperty and setProperty actions, a reference to the actual object, and the scope in which it is to be registered. (You can register variables in session scope, request scope or application scope.) Once registered, the script variables can be used in action tags. If you limit yourself to the standard jsp tag library, you cannot further simplify the code. The JSP still has to have that scriptlet co de for the iterative cons truct: <% Iterator it = theLeague.games(); while(it.hasNext()) { SoccerGame sg = (SoccerGame) it.next(); pageContext.setAttribute("sg",sg,PageContext.PAGE_SCOPE); %> <tr> <jsp:getProperty name="sg" property="score2" /> </td> </tr> <%}%> But there is no need to limit yourself to the jsp tag library. There are other libraries that are more versatile. 8.6 Tag libraries The iterative loop in the example from the last section can be defined using action tags. For example, using the tag libraries from Apache, you could have: <logic:iterate id="sg" collection="<%= theLeague.games() %>" > <tr> <td><bean:write name="sg" property="team1" /></td> <td><bean:write name="sg" property="team2" /></td> <td><bean:write name="sg" property="score1" /></td> 368 JSP: Java Server Pages <td><bean:write name="sg" property="score2" /></td> </tr> </logic:iterate> The action tag style suits JSPs. The clear matching ‘begin’and ‘end’ XML style tags are probably understood by the web designer’s web page editing tool; they may even be vaguely understood by the web designer. Code implemented u sing tags is far less likely to be broken when page layouts are adjusted. The logic:iterate tag comes from the Apache ‘struts’ tag library. Struts is comprised of several subsections. There is the ‘beans’ tag library, which contains utility components such as the bean:write tag used in the code fragment above. The ‘html’ tags provide an alternative approach to the composition of HTML fo rms. The ‘template’ tags assist in the transfer of data among JSPs. The ‘logic’ tags, of which logic:iterate is the pre-eminent example, allow you to avoid most scriptlet coding. The Apache struts library is rather sophisticated, so it is worth looking first at a simple example that illustrates th e definition and use of a customized action tag. 8.6.1 Defining a simple customized action tag Action tags are defined as Java classes. These classes extend base classes that are defined in the javax. servlet.jsp.tagext package provided by Sun. When an action tag is used in a JSP, the JSP to servlet translation replaces the tag with expanded template code. This code will instantiate an instance of th e tag class, in itialize it an d invoke various operations on the new ‘action tag’ object. Tags are used in JSPs in one or other of the following styles. The first style simply invokes the action, applying it to data supplied as attributes: <lib:tag attribute=" " attribute=" " /> The second style includes a ‘body’ between a start and an end tag: <lib:tag attribute=" " > Some other stuff </lib:tag> Both get translated into code in the servlet along the lines of the following pseudo-code: Create an instance of the action tag class Perform operations to set attributes, add to page context etc. Invoke the 'doStartTag' operation of the action tag object // More stuff here relating to any 'body' Invoke the 'doEndTag' operation of the action tag object Release the action tag object Tag libraries 369 There are two kinds of tag, based either on the TagSupport class or on the BodyTagSupport class. The code expansion of the simpler kind of tag, based on the TagSupport class, is: Create instance of the action tag class Invoke operations to set attributes, page context, etc. if(actionTagObject.doStartTag()== EVAL_BODY) { // Code obtained by translation of body (if any body is present) } if(!actionTagObject.doEndTag==EVAL_PAGE) { Abort processing of rest of this page } Release The doStartTag operation can output some HTML content and perform other opera - tions; it returns an int that indicates whether the content of any body part is to be included in the generated page (thus you can build simple conditional constructs from TagSupport objects). The doEndTag operation can generate additional HTML page output; its other role is to check for any failure conditions that might indicate that further processing of the page was to be abandoned. The BodyTagSupport base class is designed for more complex cases. It has additional methods: setBodyContent, doInitBody and doAfterBody.ThedoInitBody method can be used to introduce control variables, such as loop counters, and perform other initialization tasks. The doAfterBody method returns either the result EVAL_BODY_TAG or SKIP_BODY;ifit returns EVAL_BODY_TAG, the body of the action construct is re-evaluated – this is the basis for constructing loops. The most elaborate feature of the BodyTagSupport class is its buffering of any output produced during the evaluation of the body. A BodyContent object collects any HTML and content text written by the body. These data are then available for further editing in the doEndTag method, or are used for final output. This rather complex mecha - nism allows for tags that filter output in various ways. This feature is used in sophisticated tag libraries such as the xsl tags used to convert XML to HTML. The following example defines a simple action tag for date stamping an HTML docu - ment. This tag, mytag:DateStamper, is an example of a class that extends the TagSupport class. It takes a single attribute and produces a couple of lines of output; for example, the following line in a JSP: <mytag:DateStamper comment="This is a Test" /> could result in the following output in the HTML page: <hr> This page, entitled This is a Test, was generated on Mon Dec 10 11:55:37 GMT+11:00 2001. <br> 370 JSP: Java Server Pages (The date shown would be the date on which the example was run.) The DateStamper class extends javax.servvlet.jsp.tagext.TagSupport. It defines a setComment method th at will be u sed to set th e value of its comment attribute, and a doEndTag method that outputs the generated text to the HTML page. package mine; import java.util.*; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class DateStamper extends TagSupport { protected String comment = null; public String getComment() { return comment; } public void setComment(String cm) { comment = cm; } public int doEndTag() { try { String datestr = (new Date()).toString(); pageContext.getOut().println( "<hr>This page entitled, " + comment + ", was printed on " + datestr + "<br>"); } catch(Exception e) { } return EVAL_PAGE; } } An action tag object like this gets its (buffered) output stream from its PageContext (a reference to this PageContext is set in one of the initialization methods). The class is defined as part of a package (the mine package). I t is the only class in this package. The .class files for a tag library are normally supplied as a Java archive containing all the classes in a package; for this example, it would be a mine.jar archive file. The deploymen t of a tag library can be more involved than its coding. A JSP must first specify that it wants to use tags from the mytag tag library; this is done via a taglib direc - tive that specifies the prefix, mytag, and a URI. Depending on its form, this URI can be complete or may be interpreted relative to d ata p rovided in a deployment web.xml file. The web-app specification in the web.xml file must specify the location of an XML d ocu - ment, the ‘tag library descriptor’, which contains data describing the tags in the tag Tag libraries 371 library. Normally, this file would be placed in a tlds subdirectory of the web application’s WEB-INF directory. The code (.class files) for the tag library classes themselves must be in the CLASSPATH when compiling the servlet that is obtained from the JSP. An example could use something like the following JSP that specifies the tag library, and uses a mytag:DateStamper action: <%@ taglib uri="/mytaglib" prefix="mytag" %> <html><head><title>My Tag Test</title></head> <body bgcolor=white> <h1 align=center>Test Document</h1> <p> Hello Work, Hi Mom, and other standard greetings. <mytag:DateStamper comment="My Tag Test" /> </body></html> This JSP would be deployed as part of a web application; this would require a WEB-INF subdirectory containing the web.xml deployment file and other data. In this case, the web.xml data have to define only the tag library; this is done using a taglib tag that has taglib-uri and taglib-location nested tags. The taglib-uri entry matches the uri used in th e JSP; its location tag identifies the mytaglib.tld file. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN' 'http://java.sun.com/j2ee/dtds/web-app_2.2.dtd'> <web-app> <taglib> <taglib-uri> /mytaglib </taglib-uri> <taglib-location> /WEB-INF/tlds/mytaglib.tld </taglib-location> </taglib> </web-app> A taglib description document contains details of all the tags in a library; in this case there is only the one tag – the DateStamper tag. Each tag has to have defined its name ( DateStamper) and its class (mine.DateStamper), along with restrictions on any ‘body’ that may be used with the tag, and details of the attributes. The DateStamper tag should not be used with a body; so its bodycontent is defined as empty. The tag requires a single attribute named comment. <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" 372 JSP: Java Server Pages "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>mytag</shortname> <tag> <name>DateStamper</name> <tagclass>mine.DateStamper</tagclass> <bodycontent>empty</bodycontent> <attribute> <name>comment</name> <required>true</required> </attribute> </tag> </taglib> Typically, a Java archive file containing the mine package would be located in the WEB- INF/lib directory of the web application. In a simple case such as this, it is sufficient to copy DateStamper.class file in to the WEB-INF/classes directory. 8.6.2 Using tag libraries While you can define your own action tags, this is a fairly arcane area for development work. Mostly, you can use tags from the existing libraries, such as Apache’s struts or Taglib tag lib raries. The Taglib library contains tags for manipulating things like java.util.Date objects, java.sql Statement and Connection objects, for handling email and so forth. The struts library has su bsections like its HTML section, its beans section and its logic section. The struts HTML tags can be used to help construct HTML forms and other portions of HTML documents. For example, instead of the JSP containing standard HTML tags and contents like <a href="/vallink.jsp?name=newValues">Display of values</a> You could use the HTML action tag set and have the following: <html:link page="/vallink.jsp" name="newValues"> Display of values </html:link> This tag set includes tags for creating buttons, checkboxes, textareas and other compo - nents of forms. Each action tag takes a host of both required and optional arguments. In the typical case, you would not want to use the HTML tags because they make the directives for content layout more ‘programmatic’ and less amenable to the visual editors that will be favored by your web designer. However, these tags might be useful if you have Tag libraries 373 [...]... the specified elements must appear in the order shown in the DTD A complete web. xml document such as would have to be validated against this DTD is: servlet1 GreetingsServlet... is part of the DTD that defines the correct form for web. xml files as used for servlets: web- app (icon?, display-name?, description?, distributable?, context-param*, servlet*, servlet-mapping*, session-config?, mime-mapping*, , security-role*, )> XML and friends 3 87 web application For supervisors, it directs the Records object to load all records that have been submitted but which have not yet been assessed (records with status=1) For accountants, it directs the Records object to G Exercises 377 load all records that have been approved by a supervisor but which have not yet been... file with mapping data The tag library descriptor files, struts-bean.tld and struts-logic.tld, would have to be copied from the struts main directory into the WEB- INF directory for the application The struts.jar file would have to be copied into a WEB- INF/lib directory The struts libraries are available in source form If you really do need to learn how to write code for the more complex types of tag,... exercise continues with use of the Apache Tomcat engine employed in the exercises for Chapter 7 There are a couple of additional servlet/JSP exercises at the end of Chapter 9; those exercises combine servlet/JSP technologies with the use of XML and other markup languages (1) This exercise involves creating a servlet/JSP web application with two versions of the JSP components; one version of the JSPs should... auxiliary table as illustrated in earlier examples) G an integer status field, (0=rejected, 1=submitted waiting approval, 2=approved by supervisor waiting accountant, 3=processed by accountant) 376 JSP: Java Server Pages G a string naming the requestor G a string with details of the request G the date that the request was submitted G a string naming the supervisor who processed the request G an integer... records can be added via the web application that you develop You will also need to add a number of users to your Tomcat users–password–role file Most of your users should be in role ‘staff’; there should be a couple of users in each of the ‘supervisor’ and ‘accountant’ roles The roles are mutually exclusive These Workflow record data are accessed via a security controlled web application that comprises... 374 JSP: Java Server Pages a fairly complex system that has some programmed element that generates the source code for the JSPs that you intend to use The bean group of the struts taglib tags is really a reworking... table should also identify the supervisor, his or her decision, the comment and the review date If an accountant has also reviewed the request, the table should again show the relevant review data 378 JSP: Java Server Pages The form for entering additional funding requests appears below this table This form has a single text input field, ‘Description’, used to enter details of the staff member’s latest... to other servlets/JSPs (2) Explain the ‘JSP Model 2 or MVC’ architecture for a web application (3) Why are action tags preferable to scriptlet coding for JSPs? (4) Explain how Java reflection mechanisms and ‘bean’ coding conventions make it possible for bean manipulation code to be generated automatically 380 JSP: Java Server Pages Explorations (1) Research ‘JSP tag libraries’ Write a short report . would be deployed as part of a web application; this would require a WEB- INF subdirectory containing the web. xml deployment file and other data. In this case, the web. xml data have to define only. encoding="UTF-8"?> <!DOCTYPE web- app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN' 'http://java.sun.com/j2ee/dtds /web- app_2.2.dtd'> < ;web- app> <taglib> <taglib-uri> /mytaglib </taglib-uri> <taglib-location> /WEB- INF/tlds/mytaglib.tld </taglib-location> </taglib> < /web- app> A. the visual editors that will be favored by your web designer. However, these tags might be useful if you have Tag libraries 373 374 JSP: Java Server Pages a fairly complex system that has some