[ Team LiB ] |
JSP SyntaxJSP syntax can be divided into three classifications: directives, scripting elements, and actions. JSP syntax is modeled on the XML tag model. WebLogic's implementation of JSP 1.2 enables the use of either the standard JSP tags or equivalent XML tags. DirectivesDirectives are messages to the WebLogic JSP container, which provides instruction on what to do with the JSP page. Directives are used to control the process of translating the page into a servlet. There are three directives: page, include, and taglib. You may use multiple directives. Their location within the page is irrelevant, except for the include directive, which must be at the top of the page. Directives can contain name-value pairs in the form attribute="value". The syntax is as follows: WebLogic JSP <%@ directive-type directive-attribute="value" .. %> XML equivalent <jsp:directive-type directive-attribute="value" .. /> page Directivepage directives instruct WebLogic as to page-dependent properties. Multiple page directives are permissible, but name-value pairs must be unique. The syntax for setting page directives is as follows: WebLogic JSP
<% page page-directive_attr_list %>
XML equivalent <jsp:directive.page page_directive attr_list /> Valid page directive attributes are shown in Table 15.2.
Example <%@ page import="java.util.*, weblogic.db.jdbc.*" %> include DirectiveThe include directive inserts the contents of a designated file into the current JSP page at the location of the include tag. This insertion is accomplished at translation (parsing) time, as opposed to the JSP action include, which executes at request time. include directives are parsed (Java code is included in the translated servlet file); include actions are not parsed (code is not included in the translated servlet file). The syntax for the include directive is as follows: WebLogic JSP <%@ include file="relativeURLspec" %> XML equivalent <jsp:directive.include file="relativeURLspec" /> Example <%@ include file="login.html" %> taglib DirectiveThe taglib directive identifies a tag library to be used with this JSP page. Use of tag libraries is discussed in Chapter 17, "Using JSP Tag Libraries," and Chapter 18, "Creating JSP Tag Libraries." The syntax is as follows: WebLogic JSP <%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %> XML equivalent <jsp:directive.taglib uri="tagLibraryURI" prefix="tagPrefix" /> taglib attributes are detailed in Table 15.3. Example <%@ taglib uri="weblogic-tags" prefix="wl" %> (assumes uri registered in web.xml) Scripting ElementsScripting elements are used for computations within the JSP page. There are three types of scripting elements: declarations, scriptlets, and expressions. We also cover JSP comments under scripting elements. DeclarationsDeclarations are used to define page-level (class scope) variables and methods. These variables and methods are available at request time for use by other scripting elements within the page. The declaration must be a syntax-valid statement of the scripting language designated for the page (currently only Java). Declarations do not produce any output on their own. The syntax for declarations is as follows: WebLogic JSP <%! /* Initialization Java code */ %> XML equivalent <jsp:declaration> /* Initialization Java code */ </jsp:declaration> Example <%! int i=0; private void start() { //..do something.. } %> CAUTION To guard against corruption due to mismanaged threading, synchronization might be desirable. Setting the page directive attribute isThreadSafe to false will implement the Java single-thread model, javax.servlet.SingleThreadModel. ExpressionsExpressions are designated scripting language (Java) expressions that are executed, coerced into Java strings, and output inline to the JSP page. Expressions must be valid syntax, but do not end in a semicolon (;). Expressions are executed at request time. Expressions are normally used to dereference variables or execute get methods. Expression syntax is as follows: WebLogic JSP
<%= java_expr %>
XML equivalent
<jsp:expression>
java_expression
</jsp:expression>
Examples <%= number %> <%= myBean.getName() %>t ScriptletsScriptlets will comprise the main body of your embedded code. Scripting elements contain syntax-valid code of the designated page's scripting language (Java), to include declarations and the use of local variables. Multiple lines of code are permissible. You may implement as many scriptlet blocks as desired; however, when translated, the sum of all scriptlet blocks must produce valid syntax. Scriptlet code is executed at request time and may produce output depending on the specifics of the code implemented. If you're implementing intensive or complex logic, you should implement JavaBeans or tag libraries, as opposed to scriptlets, to minimize the amount of Java code in JSP pages, as we discuss later. The syntax for scriptlets is as follows: WebLogic JSP <% //..syntax–valid Java code.. %> XML equivalent <jsp:scriplet> //..syntax–valid Java code.. </jsp:scriplet> Example <html> <h1>Loop</h1> <% for (int i=1; i<=5; i++) { %> <h2>Loop Number: <%=i %> </h2> <% } %> </html> CommentsJSP comments enable you to include comments that are not viewable to clients executing a browser's View Source option. The comment construct is also useful during development and debugging. Java style comments may also be used within JSP pages. JSP comment syntax is as follows: <%-- comment text --%> Let's implement a JSP using some of the syntax presented so far. The code in Listing 15.3 presents a search view used within the global auction management system (GAMS). Listing 15.3 Menu.jsp1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 2 <%@ page import="com.gams.util.*" %> 3 4 <html> 5 <head> 6 <title>GAMS Menu</title> 7 </head> 8 9 <body bgcolor="#C0C0C0"> 10 11 <%-- Test to determine whether or not user is a seller --%> 12 <% if (session.getAttribute("CustomerName") != null && session.getAttribute("IsSeller") != null) { %> 13 <a href="seller/listItem.jsp" target="main">Sell An Item</a><br><br> 14 <% } %> 15 16 <a href="FindItemsServlet?featured=true" target="main">Browse Featured Items </a><br><br> 17 18 Browse By Keyword <form action="FindItemsServlet" target="main"><input type="text" name="keyword" size="10"><input type="submit" value="Submit"></form> 19 20 Browse By Category<br> 21 22 <%-- Calculate search key/value pair from category data object --%> 23 <% 24 Hashtable h = new Hashtable(); 25 h.put("BA1001", "furniture"); 26 h.put("BA2001", "automotive"); 27 h.put("BA3001", "jewelry"); 28 29 Enumeration enum = h.keys(); 30 while(enum.hasMoreElements()) { 31 String key = (String)enum.nextElement(); 32 String value = (String)h.get(key); 33 %> 34 <a href="FindItemsServlet?catid=<%=key%>" target="main"><%=value%></a><br> 35 <% } %> 36 37 </body> 38 </html> NOTE The code presented is intended to show examples of JSP syntactic elements. Proper implementation of MVC architecture would implement such logic shown within the Control layer (using an EJB, taglib, JavaBean, or other constructs). Efficient JSP pages should contain little if any implementation logic and no hard-coded data. Notice the use of page directive (import) in line 2, scriptlets in lines 11–14 and 22–35, comments in lines 11 and 22, and expressions in line 34. Also note line 34: The JSP page presents only a client view or portal into the application. The servlet referenced in line 34 receives the client input and processes workflow as needed; that is, the servlet in this case delegates the find task to a session EJB, which in turn requests the target data from a relational database. This is an example of the n-tiered MVC work that will be discussed in this chapter and the next. Relating this example to MVC, the JSP provides the client "view," the servlet "controls" the workflow, and the session EJB requests and receives data from a relational database housing the data "model." The client view produced by this JSP is presented in Figure 15.3. Figure 15.3. Browser view of Menu.jsp.To run this example, place the JSPs in your domain's applications\DefaultWebApp directory as discussed earlier. Deposit supporting classes (see Listing 15.3, line 2) in the WEB-INF\classes directory (subdirectory of applications\DefaultWebApp). Start your server and access the JSPs through your browser as shown at Figure 15.3. ActionsActions enable you to manipulate (use, modify, and create) objects, represented as JavaBeans. Actions are implemented using XML syntax only. The JSP 1.2 Specification identifies standard actions that must be implemented. Additional actions may be implemented using the taglib directive. There are nine standard actions: useBean, setProperty, getProperty, include, forward, param, plugin, params, and fallback. NOTE The new JSP 2.0 Specification introduces a new syntax for defining custom actions and a simple invocation protocol for implementing these actions. useBeanThe useBean action enables you to instantiate JavaBean objects and to refer to the object later within your code. Initial use of the useBean tag attempts to obtain a reference to an existing object. If an object isn't found, an object of the type specified will be instantiated. useBean attributes are detailed in Table 15.4. useBean scope attributes are detailed in Table 15.5. Refer to Chapter 16 for detailed information on JavaBeans. The useBean syntax is as follows: <jsp:useBean id="name" class="className" scope="page|request|session|application"/> or <jsp:useBean id="name" class="className" scope="page|request|session|application"> body (body may include actions or scriptlets) </jsp:useBean> Example <jsp:useBean id="account" class="com.globalAuctions.Account" scope="session"/> <jsp:useBean id="account" class="com.globalAuctions.Account" scope="session"> <jsp:setProperty name="account" property="AccountNumber" value="NDE4587"> </jsp:useBean>
setPropertyThe setProperty action defines values of properties within a JavaBean. The bean referenced by the name attribute must be defined prior to use. The setProperty syntax is as follows: <jsp:setProperty name="beanName" property="property_name" value="value"/> Note that "value" may be an expression. Example <jsp:setProperty name="account" property="AccountNumber" value="NDE4587"/> getPropertyThe getProperty action retrieves values of properties from a JavaBean. The values retrieved are coerced to a Java String and printed to output. The name (bean name) attribute must be defined prior to its use. The getProperty syntax is as follows: <jsp:getProperty name="beanName" property="property_name"/> Example <jsp:getProperty name="account" property="AccountNumber"/> includeThe include action includes any static or dynamic resource available to the JSP's context into the current page. The action is a de facto redirect; that is, the request or logic flow is redirected to another JSP page and returned. The other page can be a static HTML page, JSP page, or servlet that's available to the context. The include can also pass parameters. Any content produced by the included resource is inserted within the current page at the point of the include tag, where execution continues. (JavaBeans within the including page will have access to any resources defined within the included page.) The included resource may not set any HTTP header resources, such as the setCookie() method. CAUTION The URL displayed (included page or the including page?) may be an issue for some developers. That is, which page URL do you want displayed in the user's browser location window? Do you want to audit or track process flow? Do you want the actual processing URL revealed? Is business logic using the display URL? Are there security concerns? and so on. When using the include directive, the including page's URL will be displayed. Any attempts to set these methods (HTTP header resources) will either be ignored or an exception might be generated. In some situations, use of the forward action in conjunction with decision logic might be desirable over the include action. The include action syntax is as follows: <jsp:include page="relativeURL" flush="true|false"/> (flush (buffer) is optional, default is false) or
<jsp:include page="relativeURL" flush="true|false">
<jsp:param .. />
</jsp:include>
Examples <jsp:include page="./util/validateAcount.jsp" flush="true"/> <jsp:include page="./util/validateAcount.jsp" flush="true"> <jsp:param name="AccountNumber" value="JK45763"/> </jsp:include> forwardThe forward action executes a runtime dispatch of the current request to any static or dynamic resource within the same context as the current page. Execution of the current page terminates within the forwarding page. The forward action may also pass parameters. The request object is modified based on the value of the forward action's page attribute. The forward action's syntax is as follows:
<jsp:forward page="relativeURL"/>
or
<jsp:forward page="relativeURL">
<jsp:param .. />
</jsp:forward>
Examples <jsp:forward page="invalidAccount.jsp"/> <jsp:forward page="validAccount.jsp"/> <jsp:param name="accountNumber" value="<%=account.getAccountNumber()%>"/> ("account" previously defined) </jsp:forward> paramThe param action tag provides name-value pair information. This tag is used within the include, forward, and params actions. When executing an include or forward action, if the original request object has preexisting parameters, the request will be augmented with the new additional parameters. The new parameters will take precedence. All parameters will be passed. param syntax is as follows: <jsp:param name="name" value="value"/> For an example of param, see the previous example under the forward action. pluginThe plugin action generates HTML, which enables download of Java plug-in software. This construct enables execution of an applet or JavaBean component. The plugin tag is replaced by either an object or embed tag as appropriate for the designated plug-in. The plugin action also uses embedded params, param, and/or fallback action tags. The plugin action syntax is as follows: <jsp:plugin type="plugin_attribute(s)"> <jsp:params> <jsp:param name="name" value="value"/> </jsp:params> <jsp:fallback> text </jsp:fallback> </jsp:plugin> plugin attributes are detailed in Table 15.6. Example: <jsp:plugin type="applet" code="Catalogue.class" codebase="./classes"> <jsp:params> <jsp:param name="auctionNumber" value="AA389"/> </jsp:params> <jsp:fallback> Error Initiating Catalogue Applet </jsp:fallback> </jsp:plugin> paramsThe params action identifies plug-in parameters. The params tag is used only as a child of the plugin action. Refer to the "plugin" section presented earlier for the params tag syntax and an example. fallbackThe fallback action designates content display if the plug-in cannot be started. If the plug-in starts but the component cannot be found, a ClassNotFoundException will be thrown. The fallback tag is only used as a child of the plugin action. Refer to the "plugin" section presented earlier for the fallback tag syntax and an example. |
[ Team LiB ] |