[ Team LiB ] Previous Section Next Section

JSP Syntax

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

Directives

Directives 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 Directive

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

Table 15.2. page Directive Attributes

Name-Value Pair

Description

language="scriptingLanguage"

Scripting language to use within JSP tags. Only "java" is valid for this entry.

extends="className"

Designated super class for this JSP page.

import="importPackageList"

Java packages available to this page.

session="true|false"

Whether or not page participates in HTTP session.

buffer="none|sizekb"

Buffering model for initial JspWriter (out).

autoFlush="true|false"

Whether or not to flush output buffer automatically.

isThreadSafe="true|false"

Level of thread safety. False supports single thread model.

info="info_text"

String made available to the Servlet.getServletInfo() method.

errorPage="error_url(filename)"

Designated target destination for exceptions thrown but not caught by implementing page.

isErrorPage="true|false"

Current page is URL target for exceptions.

contentType="ctinfo"

Designates character encoding for current JSP page and response. Also designates MIME type for response.

pageEncoding="peinfo"

Designates character encoding for current JSP page.

Example


<%@ page import="java.util.*, weblogic.db.jdbc.*" %>
include Directive

The 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 Directive

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

Table 15.3. taglib Directive Attributes

Attribute

Description

Uri

Absolute or relative URI of tag library registered in web.xml.

TagPrefix

Defines prefix string used to identify custom tags; that is, <myPrefix:myTag>. Prefixes starting with jsp, jspx, java, javax, servlet, sun, and sunw are reserved. Prefix must follow XML namespaces specification. WebLogic prefix is wl.

Example


<%@ taglib uri="weblogic-tags" prefix="wl" %> (assumes uri registered in web.xml)

Scripting Elements

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

Declarations

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


Expressions

Expressions 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
Scriptlets

Scriptlets 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>
Comments

JSP 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.jsp
1 <!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")
graphics/ccc.gif != 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"
graphics/ccc.gif 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.

graphics/15fig03.gif

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.

Actions

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


useBean

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

Table 15.4. UseBean Attributes

Attribute

Description

Id

Name used to identify object instance.

scope

Scope in which object reference is available. Refer to Table 15.5.

class

Fully qualified class name.

Table 15.5. UseBean Scope Attributes

Scope

Description

Page

Object stored in PageContext and available only to current page. The object is not available to other pages and is discarded upon completion of page request.

Request

Object stored in current ServletRequest and available to pages included within the current request. Object is discarded upon completion of request.

Session

Object stored in HTTP session and is available to JSP pages used within the current session.

Application

Object stored in Web application and is available to any servlet or JSP pages running within the application.

setProperty

The 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"/>
getProperty

The 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"/>
include

The 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
graphics/ccc.gif 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>
forward

The 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"
graphics/ccc.gif previously defined)
</jsp:forward>
param

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

plugin

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

Table 15.6. Plugin Attributes

Attribute

Description

type

Component type: JavaBean or Applet.

code

Defines the name or absolute pathname of the component with respect to code base.

codebase

Defines base URI for the component. If unspecified, defaults to current URI. Can refer only to subdirectories of current URI.

align

Specifies the position of the component (bottom, top, middle, left, right).

archive

Comma-separated list of URI(s) containing Java classes or other resources supporting component defined by code attribute. Archives using relative pathing are defined with respect to the codebase attribute.

height

Defines the initial height of component display. Defined height does not define height of subsequent windows or other displays created by component.(accepts runtime parameter).

hspace

Specifies amount of space to insert left and right of component.

jreversion

Component required JRE version. Default is 1.2.

name

Refers to contextual name of Java object. Used by other Java objects within the context to reference the named object.

vspace

Specifies amount of space to insert above and below component.

title

Specifies advisory information about component. Information displayed during mouse operations.

width

Defines initial width of component display. Defined width does not define width of windows or other displays created by component. Accepts runtime parameter.

nspluginurl

URL where Netscape version of JRE may be downloaded. Default is implementation defined.

iepluginurl

URL where IE version of JRE may be downloaded. Default is implementation defined.

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

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

fallback

The 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 ] Previous Section Next Section