2014年4月16日 星期三

JSP Syntax and Structure

JSP Syntax and Structure
Before writing your first JSP, you need to gain an understanding of the syntax and the
structure of a JSP.As you have seen, JSP elements are embedded in static HTML. Like HTML, all JSP ele-
ments are enclosed in open and close angle brackets (< >). Unlike HTML, but like XML,
all JSP elements are case sensitive.

JSP elements are distinguished from HTML tags by beginning with either <% or <jsp:.
JSPs follow XML syntax, they all have a start tag (which includes the element name) and
a matching end tag. Like XML tags, a JSP tag with an empty body can combine the start
and end tags into a single tag. The following is an empty body tag:
<jsp:useBean id=”agency” class=”web.AgencyBean”>
</jsp:useBean>

The following tag is equivalent to the previous example:
<jsp:useBean id=”agency” class=”web.AgencyBean”/>
Optionally, a JSP element may have attributes and a body. You will see examples of all
these types during today’s lesson. See Appendix C, “An Overview of XML,” for more
information on XML and the syntax of XML elements.

JSP Elements
The basic JSP elements are summarised in Table 13.1.
TABLE 13.1 JSP Elements
Element Type JSP Syntax Description
Directives <%@Directive…%> Information used to control the translation of the
JSP text into Java code
Scripting <%    %> Embedded Java code
Actions <jsp:   > JSP-specific tags primarily used to support
JavaBeans
You will learn about scripting elements first and then cover directives and actions later in
today’s lesson.
Scripting Elements
Scripting elements contain the code logic. It is these elements that get translated into a
Java class and compiled. There are three types of scripting elements—declarations,
scriptlets, and expressions. They all start with <% and end with %>.

Declarations
Declarations are used to introduce one or more variable or method declarations, each one
separated by semicolons. A variable must be declared before it is used on a JSP page.
Declarations are differentiated from other scripting elements with a <%! start tag. An
example declaration that defines two variables is as follows:
<%! String color = “blue”; int i = 42; %>

You can have as many declarations as you need. Variables and methods defined in decla-
rations are declared as instance variables outside of any methods in the class.
Expressions
JSP expressions are single statements that are evaluated, and the result is cast into a
string and placed on the HTML page. An expression is introduced with <%= and must
not be terminated with a semi-colon. The following is an expression that will put the
contents of the i element in the items array on the output page.
<%= items[i] %>

JSP expressions can be used as values for attributes in JSP tags. The following example
shows how the i element in the items array can be used as the value for a submit button
on a form:
<INPUT type=submit value=”<%= items[i] %>”>

沒有留言:

張貼留言