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



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


Designated super class for this JSP page.


Java packages available to this page.


Whether or not page participates in HTTP session.


Buffering model for initial JspWriter (out).


Whether or not to flush output buffer automatically.


Level of thread safety. False supports single thread model.


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


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


Current page is URL target for exceptions.


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


Designates character encoding for current JSP page.


<%@ 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" />


<%@ 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




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


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.


<%@ 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 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

 /* Initialization Java code */


<%! int i=0;
  private void start() {
   //..do something..


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



<%= number %>

<%= myBean.getName() %>t

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

//..syntax–valid Java code..


  for (int i=1; i<=5; i++) {
   <h2>Loop Number: <%=i %> </h2>
<% }

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.*" %>
4 <html>
5 <head>
6    <title>GAMS Menu</title>
7 </head>
9 <body bgcolor="#C0C0C0">
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 <% } %>
16 <a href="FindItemsServlet?featured=true" target="main">Browse Featured Items </a><br><br>
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>
20 Browse By Category<br>
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");
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 <% } %>
37 </body>
38 </html>


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.


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.


The new JSP 2.0 Specification introduces a new syntax for defining custom actions and a simple invocation protocol for implementing these actions.


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


<jsp:useBean id="name" class="className" scope="page|request|session|application">
body (body may include actions or scriptlets)


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

Table 15.4. UseBean Attributes




Name used to identify object instance.


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


Fully qualified class name.

Table 15.5. UseBean Scope Attributes




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.


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


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


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


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.


<jsp:setProperty name="account" property="AccountNumber" value="NDE4587"/>

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


<jsp:getProperty name="account" property="AccountNumber"/>

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.


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)


<jsp:include page="relativeURL" flush="true|false">
 <jsp:param .. />


<jsp:include page="./util/validateAcount.jsp" flush="true"/>

<jsp:include page="./util/validateAcount.jsp" flush="true">
 <jsp:param name="AccountNumber" value="JK45763"/>

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


<jsp:forward page="relativeURL">
 <jsp:param .. />


<jsp:forward page="invalidAccount.jsp"/>

<jsp:forward page="validAccount.jsp"/>
 <jsp:param name="accountNumber" value="<%=account.getAccountNumber()%>"/>  ("account"
graphics/ccc.gif previously defined)

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.


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:param name="name" value="value"/>

plugin attributes are detailed in Table 15.6.

Table 15.6. Plugin Attributes




Component type: JavaBean or Applet.


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


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


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


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.


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


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


Component required JRE version. Default is 1.2.


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


Specifies amount of space to insert above and below component.


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


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


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


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


<jsp:plugin type="applet" code="Catalogue.class" codebase="./classes">
  <jsp:param name="auctionNumber" value="AA389"/>
  Error Initiating Catalogue Applet

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.


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