JSP手册
JavaServer Pages (JSP)
可以让你从静态的HTML中隔离页面的动态部分。你可以用任何Web页面编辑器,如通常方式一样写HTML。
然后用特殊的标记来附上动态部分的代码,许多时候都是以
"<% "开头 "%> "结尾的。例如,URL
http://host/OrderConfirmation.jsp?title=Core+Web+Programming 访问的结果为"Thanks
for ordering Core Web Programming",下面是这个JSP页面的一部分,
:
Thanks for ordering
<I><%= request.getParameter("title") %></I>
一般情况下文件是以 .jsp为扩展名,并放在一般的web页面所放的地方,虽然你写的更象一个正常的HTML文件而不是一个servlet,但在幕后JSP页面被转换成正常的servlet,
静态HTML 印到输出流与servlet的 service 方法联系起来。页面被第一次请求的时候,JSP页面被翻译成servlet
,接着 servlet被编译和装载。
除了正常的HTML, 有三种主要类型的JSP结构嵌入到你的页面:脚本要素,
指令, 行为。脚本要素让你指定作为servlet部分结果的Java代码,指令让你控制servlet的总结构,
行为让你可以使用现存的components并控制JSP的行为。
为了简化脚本要素,你可以使用预定义的变量。
该教程含概了JSP 1.0的规格说明,
从版本0.92起JSP已经发生了戏剧性的变化,虽然这些改变几乎完全是好,但是你应该注意到1.0版本的JSP页,
几乎和早期的JSP引擎完全不相容。
JSP 要素 |
语法 |
解释 |
注解 |
JSP 表达式 |
<%= expression %>
|
表达式被置于输出 |
XML equivalent is
<jsp:expression>
expression
</jsp:expression> .预先定义的变量可以被 request ,
response , out , session , application ,
config , and pageContext (也可以用在脚本中). |
JSP scriptlets |
<% code %>
|
代码被插入service方法中 |
XML equivalent is
<jsp:scriptlet>
code
</jsp:scriptlet> . |
JSP 声明 |
<%! code %>
|
代码被插入service方法外的,servlet class 主题部分 |
XML equivalent is
<jsp:declaration>
code
</jsp:declaration> . |
JSP page 指令 |
<%@ page att="val" %>
|
指向servlet引擎. |
XML equivalent is
<jsp:directive.page att="val"\> .
Legal attributes, with default values in bold, are:
- import="package.class"
- contentType="MIME-Type"
- isThreadSafe="true|false"
- session="true|false"
- buffer="sizekb|none"
- autoflush="true|false"
- extends="package.class"
- info="message"
- errorPage="url"
- isErrorPage="true|false"
- language="java"
|
JSP include 指令 |
<%@ include file="url" %>
|
当JSP页面被翻译成servlet时把本地系统的文件包含进来. |
XML equivalent is
<jsp:directive.include
file="url"\> .
The URL must be a relative one. Use the jsp:include
action to include a file at request time instead of translation
time. |
JSP 注解 |
<%-- comment --%>
|
注解,在JSP被翻译成servlet将被忽略 |
If you want a comment in the resultant HTML, use regular HTML
comment syntax of <-- comment --> . |
The jsp:include 行为 |
<jsp:include
page="relative URL"
flush="true"/>
|
Includes a file at the time the page is requested. |
If you want to include the file at the time the page is
translated, use the page directive with the include
attribute instead. Warning: on some servers, the included
file must be an HTML file or JSP file, as determined by the server
(usually based on the file extension). |
The jsp:useBean 行为 |
<jsp:useBean att=val*/> or
<jsp:useBean att=val*>
...
</jsp:useBean> |
Find or build a Java Bean. |
Possible attributes are:
- id="name"
- scope="page|request|session|application"
- class="package.class"
- type="package.class"
- beanName="package.class"
|
The jsp:setProperty Action |
<jsp:setProperty att=val*/>
|
Set bean properties, either explicitly or by designating that
value comes from a request parameter. |
Legal attributes are
- name="beanName"
- property="propertyName|*"
- param="parameterName"
- value="val"
|
The jsp:getProperty Action |
<jsp:getProperty
name="propertyName"
value="val"/>
|
Retrieve and output bean properties. |
|
The jsp:forward Action |
<jsp:forward
page="relative URL"/>
|
Forwards request to another page. |
|
The jsp:plugin Action |
<jsp:plugin
attribute="value"*>
...
</jsp:plugin>
|
Generates OBJECT or EMBED tags, as
appropriate to the browser type, asking that an applet be run
using the Java Plugin. |
|
在很多情况下,你的JSP页面大部分都是由静态HTML组成的,
除了HTML更象一般的HTML之外,都有相同的语法规则。不仅HTML确实看起来象通常的,而且她可以用任何web页面工具来建立。例如,在我的教程中都是用
Allaire的 HomeSite来建立 JSP 页面的。
这个最小的区别就是,如果你想在文本中有“<%”输出,那么你需要把“</%”放在标准的文本中。
JSP 脚本要素是让你把Java代码插入当前的JSP页面将产生的servlet中。有三中方式:
<%= expression %> 形式的表达是被用来赋值和插入输出,
<% code %> 形式的脚本是插入到servlet的service方法中
<%! code %> 形式的声明是插入servlet类的主体当中,但是在所存在的方法之外。
下面将更具体地描述它们
4.1 JSP Expressions
JSP 表达式是直接把java值输出。它有下列的形式:
<%= Java 表达式 %>
Java
表达式是一个值,转换成字符串后插入到页面中。
这个值是运行时产生的。例如下面请求是去显示日期和时间:
Current time: <%= new java.util.Date() %>
简化这些表达式,这个是你能够使用的预先定义的变量。这些隐含的对象,不是表达式用途,在以后更多的细节中讨论,更为重要的一个是:
request , the HttpServletRequest ;
response , the HttpServletResponse ;
session , 是HttpSession 与 request
相连的;
out , the PrintWriter (a buffered version
of type JspWriter )用来送出到客户端
这是一个例子:
你的主机名: <%= request.getRemoteHost() %>
在 XML中也有 JSP 表达式的类似语法:
<jsp:expression>
Java Expression
</jsp:expression>
记住 XML 要素不象HTML,它是很敏感的,那样务必要使用小写字母的。
4.2 JSP scriptlets
如果你想做一些比插入简单表达式更复杂的事, JSP
scriptlets可以让你随心所欲在将产生页面的servlet方法中插入代码。
scriptlets有这样的形式:
<% Java 代码 %>
scriptlets也可以象表达式那样随意定义变量。例如,
你可以用out变量在结果页面中输出显示。
<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
Note that code inside a scriptlet gets inserted exactly as
written, and any static HTML (template text) before or after a scriptlet
gets converted to print statements. 这意味着scriptlets不必要包含完整的java代码,
在scriptlets外部留下影响静态HTML的开放块。例如,下列JSP块包容了标准文本和scriptlets
<% if (Math.random() < 0.5) { %>
Have a <B>nice</B> day!
<% } else { %>
Have a <B>lousy</B> day!
<% } %>
它将转换成这样:
if (Math.random() < 0.5) {
out.println("Have a <B>nice</B> day!");
} else {
out.println("Have a <B>lousy</B> day!");
}
如果你想在scriptlet中用字符 "%> "
, 那么用 "%\> " 代替。最后,指出 XML相当的
<% Code %> 是
<jsp:scriptlet>
Code
</jsp:scriptlet>
4.3 JSP 声明
JSP 声明让你定义插入servlet类主体中的方法和域(在service方法之外处理这个请求).
它有下列的形式:
<%! Java Code %>
既然声明不能产生任何输出,它通常用作JSP表达式和scriptlets之间的连接。例如,这里的JSP块输出的是服务器启动后当前页被访问的次数:
<%! private int accessCount = 0; %>
Accesses to page since server reboot:
<%= ++accessCount %>
和scriptlets一样, 如果你想用 "%> "字符,
输入 "%\> " 代替。最后,指出 XML
相当的 <%! Code %> 是
<jsp:declaration>
Code
</jsp:declaration>
JSP directive 影响 servlet
类的整个结构。 它通常有下列的形式:
<%@ directive attribute="value" %>
在一个directive中可以兼有都个属性设置,例如:
<%@ directive attribute1="value1"
attribute2="value2"
...
attributeN="valueN" %>
有两种主要类型的指令: page ,
让你象 import 一个类一样,定制 servlet 超类; include ,
在JSP被翻译成servlet时引入一个文件到servlet种。在规格说明种也提到过
taglib 指令, 在JSP 1.0版本中,已经不再支持了,但是想让
JSP 编程人员定义自己的标志。这个可能在 JSP 1.1中实现。
5.1 JSP page 指令
page
指令可以让你定义下列情况中的一个或多个敏感的属性:
import="package.class" or import="package.class1,...,package.classN" .
这个让你指定将引入哪些包。例如:
<%@ page import="java.util.*" %>
contentType="MIME-Type" or
contentType="MIME-Type; charset=Character-Set"
指定 MIME 类型的输出。缺省是text/html . 例如
<%@ page contentType="text/plain" %>
跟scriptlet中的 <%
response.setContentType("text/plain"); %>
有相同效果
isThreadSafe="true|false" . 如果为 true (缺省)
表明是正常的 servlet 处理,
假定有多个请求访问实例变量的时候,多重请求都可以被单个servlet实例同时处理。为
false 表明servlet应该贯彻单线程模式,每个请求分配给一个独立的servlet实例。
session="true|false" . 如果为 true
(缺省) 表明预先定义的session 变量(HttpSession 类型)
将被结合现存的session(如果有的话), 否则一个新的session将被建立和结合。为
false 表明没有session会被使用, 在JSP翻译成servlet时候,试图去访问session变量将导致出错。
buffer="sizekb|none" . 为JspWriter
输出指定缓冲器的大小。
缺省是由服务器指定,但必须不小于8kb .
autoflush="true|false" . 缺省情况下为
true ,表明当缓冲器中满的时候将会被 flushed(这个不知道该怎么翻译),
如果为 false,这个很少用到,
表明当存储器溢出的时候例外被抛出。当用buffer="none"
,值为false是不合法的
extends="package.class" . 这个表明servlet的超类将被生成。
使用这个应该非常谨慎。
info="message" .
这是定义一个可以通过 getServletInfo
方法检索到的字符串。
errorPage="url" . 指定一个JSP页面处理那些没有被抓住的抛出异常。
isErrorPage="true|false" .
这表明当前的页面是否能够充当另外的JSP页面的出错页。
缺省为false。
language="java" .
在一些方面,这是指定下面打算要用的语言。
不用为这个费心,java是缺省的,而且是唯一合法的选择。
The XML syntax for defining directives is
<jsp:directive.directiveType attribute=value />
For example, the XML equivalent of
<%@ page import="java.util.*" %>
is
<jsp:directive.page import="java.util.*" />
5.2 The JSP includeDirective
这个指令让你可以在JSP翻译成servlet的时候可以包含进一些文件。这个指令是这样的:
<%@ include file="relative url" %>
这个指定的URL通常是指向它的JSP页面的相关解释。包含的文件内容被当作JSP文本来分析,因此可以包含静态
HTML, scripting elements, directives, and actions.
例如,很多站点的每个页面上都包含有小的导航条。这个
include
是做这个的很好方法,省得开发者经常拷贝HTML到不同的文件中。这是一些
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Servlet Tutorial: JavaServer Pages (JSP) 1.0</TITLE>
<META NAME="author" CONTENT="webmaster@somesite.com">
<META NAME="keywords" CONTENT="...">
<META NAME="description" CONTENT="...">
<LINK REL=STYLESHEET
HREF="Site-Styles.css"
TYPE="text/css">
</HEAD>
<BODY>
<%@ include file="/navbar.html" %>
<!-- Part specific to this page ... -->
</BODY>
</HTML>
既然文件是在页面被翻译的时候插入的,如果导航条改变了,你需要去重新翻译它所指向的所有JSP页面。
既然导航条不是经常改变的,而且你想要整个过程尽可能高效,那么在这样的环境下这是好的妥协。
如果这个 included 文件经常改变,你应该用 jsp:include
行为来代替。
这是一个简单的展示JSP表达式、scriptlets、声明和指令的使用例子。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Using JavaServer Pages</TITLE>
<META NAME="author" CONTENT="Marty Hall -- hall@apl.jhu.edu">
<META NAME="keywords"
CONTENT="JSP,JavaServer Pages,servlets">
<META NAME="description"
CONTENT="A quick example of the four main JSP tags.">
<LINK REL=STYLESHEET
HREF="My-Style-Sheet.css"
TYPE="text/css">
</HEAD>
<BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE"
VLINK="#551A8B" ALINK="#FF0000">
<CENTER>
<TR><TH CLASS="TITLE">
Using JavaServer Pages
</CENTER>
<P>
Some dynamic content created using various JSP mechanisms:
<UL>
<LI><B>Expression.</B><BR>
Your hostname: <%= request.getRemoteHost() %>.
<LI><B>Scriptlet.</B><BR>
<% out.println("Attached GET data: " +
request.getQueryString()); %>
<LI><B>Declaration (plus expression).</B><BR>
<%! private int accessCount = 0; %>
Accesses to page since server reboot: <%= ++accessCount %>
<LI><B>Directive (plus expression).</B><BR>
<%@ page import = "java.util.*" %>
Current date: <%= new Date() %>
</UL>
Here's a typical result: %201_0.files/JspTest-IE.gif)
为了简化JSP表达式和scriptlet中的代码,你可以使用被提供的八中自定义变量,或叫隐含变量,这些可用的变量是:request,response,out,session,application,config,pageContext和page。具体细节如下:
7.1 request
是HttpservletRequest把这个同request联系起来,让你可用看到request参数(通过getParameter),request类型(GET,POST,HEAD等),和得到的
HTTP 头 (cookies, Referer )。 严格的说,如果request用的协议是其他的协议,而不是HTTP,那么request是servletRequest的基类而不是HttpservletRequest。
这个在实际中没有用。
7.2 response
是HttpServletResponse把这个和客户端的response联系起来。
Note that, since the output stream (see out below) is
buffered, it is legal to set HTTP status codes and response
headers, even though this is not permitted in regular servlets once any
output has been sent to the client.
7.3 out
这个是用PrintWrite来输出到客户端。但是,为了使 response
对象有用, this is a buffered version of PrintWriter
called JspWriter . 通过page指令的缓冲器属性的使用,你可以调整缓存器的大小,
甚至离开缓冲器。 This was discussed in Section
5.那out几乎被专门用在scriptlets中, since JSP expressions
automatically get placed in the output stream, and thus rarely need to
refer to out explicitly.
7.4 session
This is the HttpSession object associated with the
request. Recall that sessions are created automatically, so this variable
is bound even if there was no incoming session reference. The one
exception is if you use the session attribute of the page
directive (see Section
5) to turn sessions off, in which case attempts to reference the
session variable cause errors at the time the JSP page is translated into
a servlet.
7.5 application
This is the ServletContext as obtained via getServletConfig().getContext() .
7.6 config
This is the ServletConfig object for this page.
7.7 pageContext
JSP introduced a new class called PageContext to
encapsulate use of server-specific features like higher performance JspWriter s.
The idea is that, if you access them through this class rather than
directly, your code will still run on "regular" servlet/JSP
engines.
7.8 page
This is simply a synonym for this , and is not very useful
in Java. It was created as a placeholder for the time when the scripting
language could be something other than Java.
JSP actions use constructs in XML syntax to control the behavior
of the servlet engine. You can dynamically insert a file, reuse JavaBeans
components, forward the user to another page, or generate HTML for the
Java plugin. Available actions include:
jsp:include - Include a file at the time the page is
requested. See Section
8.1.
jsp:useBean - Find or instantiate a JavaBean. See Section
8.2 for an overview, and Section
8.3 for details.
jsp:setProperty - Set the property of a JavaBean. See Section
8.4.
jsp:getProperty - Insert the property of a JavaBean
into the output. See Section
8.5.
jsp:forward - Forward the requester to a new page. See Section
8.6.
jsp:plugin - Generate browser-specific code that makes
an OBJECT or EMBED tag for the Java plugin.
See Section
8.7.
These actions are described in more detail below. Remember that, as
with XML in general, the element and attribute names are case sensitive.
This action lets you insert files into the page being generated. The
syntax looks like this:
<jsp:include page="relative URL" flush="true" />
Unlike the include
directive, which inserts the file at the time the JSP page is
translated into a servlet, this action inserts the file at the time the
page is requested. This pays a small penalty in efficiency, and precludes
the included page from containing general JSP code (it cannot set HTTP
headers, for example), but it gains significantly in flexibility. For
example, here is a JSP page that inserts four different snippets into a
"What's New?" Web page. Each time the headlines change, authors
only need to update the four files, but can leave the main JSP page
unchanged.
WhatsNew.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<CENTER>
<TABLE BORDER=5 BGCOLOR="#EF8429">
<TR><TH CLASS="TITLE">
What's New at JspNews.com</TABLE>
</CENTER>
<P>
Here is a summary of our four most recent news stories:
<OL>
<LI><jsp:include page="news/Item1.html" flush="true"/>
<LI><jsp:include page="news/Item2.html" flush="true"/>
<LI><jsp:include page="news/Item3.html" flush="true"/>
<LI><jsp:include page="news/Item4.html" flush="true"/>
</OL>
</BODY>
</HTML>
Here's a typical result: %201_0.files/WhatsNew-NS.gif)
This action lets you load in a JavaBean to be used in the JSP page.
This is a a very useful capability because it lets you exploit the
reusability of Java classes without sacrificing the convenience that JSP
adds over servlets alone. The simplest syntax for specifying that a bean
should be used is:
<jsp:useBean id="name" class="package.class" />
This usually means "instantiate an object of the class specified
by class , and bind it to a variable with the name specified
by id ." However, as we'll see shortly, you can specify a
scope attribute that makes the bean associated with more than
just the current page. In that case, it is useful to obtain references to
existing beans, and the jsp:useBean action specifies that a
new object is instantiated only if there is no existing one with the same id
and scope . Now, once you have a bean, you can modify its
properties via jsp:setProperty , or by using a scriptlet and
calling a method explicitly on the object with the variable name specified
earlier via the id attribute. Recall that with beans, when
you say "this bean has a property of typeX called foo ",
you really mean "this class has a method called getFoo
that returns something of type X, and another method called setFoo
that takes an X as an argument." The jsp:setProperty
action is discussed in more detail in the next section, but for now note
that you can either supply an explicit value , give a param
attribute to say that the value is derived from the named request
parameter, or just list the property to indicate that the value should be
derived from the request parameter with the same name as the property. You
read existing properties in a JSP expression or scriptlet by calling the
appropriate getXxx method, or more commonly, by using
the jsp:getProperty action.
Note that the class specified for the bean must be in the server's regular
class path, not the part reserved for classes that get automatically
reloaded when they change. For example, in the Java Web Server, it and all
the classes it uses should go in the classes directory or be
in a jar file in the lib directory, not be in the servlets
directory.
Here is a very simple example that loads a bean and sets/gets a simple String
parameter.
BeanTest.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Reusing JavaBeans in JSP</TITLE>
<LINK REL=STYLESHEET
HREF="My-Style-Sheet.css"
TYPE="text/css">
</HEAD>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">
Reusing JavaBeans in JSP</TABLE>
</CENTER>
<P>
<jsp:useBean id="test" class="hall.SimpleBean" />
<jsp:setProperty name="test"
property="message"
value="Hello WWW" />
<H1>Message: <I>
<jsp:getProperty name="test" property="message" />
</I></H1>
</BODY>
</HTML>
SimpleBean.java
Here's the source code for the bean used in the BeanTest JSP page.
package hall;
public class SimpleBean {
private String message = "No message specified";
public String getMessage() {
return(message);
}
public void setMessage(String message) {
this.message = message;
}
}
Here's a typical result: %201_0.files/BeanTest-NS.gif)
The simplest way to use a bean is to use
<jsp:useBean id="name" class="package.class" />
to load the bean, then use jsp:setProperty and jsp:getProperty
to modify and retrieve bean properties. However, there are two other
options. First, you can use the container format, namely
<jsp:useBean ...>
Body
</jsp:useBean>
to indicate that the Body portion should be executed only when the
bean is first instantiated, not when an existing bean is found and used.
As discussed below, beans can be shared, so not all jsp:useBean
statements result in a new bean being instantiated. Second, in addition to
id and class , there are three other attributes
that you can use: scope , type , and beanName .
These attributes are summarized in the following table.
Atribute |
Usage |
id |
Gives a name to the variable that will reference the bean. A
previous bean object is used instead of instantiating a new one if
one can be found with the same id and scope . |
class |
Designates the full package name of the bean. |
scope |
Indicates the context in which the bean should be made
available. There are four possible values: page , request ,
session , and application . The default, page ,
indicates that the bean is only available on the current page
(stored in the PageContext of the current page). A
value of request indicates that the bean is only
available for the current client request (stored in the ServletRequest
object). A value of session indicates that the object
is available to all pages during the life of the current HttpSession .
Finally, a value of application indicates that it is
available to all pages that share the same ServletContext .
The reason that the scope matters is that a jsp:useBean
entry will only result in a new object being instantiated if there
is no previous object with the same id and scope .
Otherwise the previously existing object is used, and any jsp:setParameter
elements or other entries between the jsp:useBean
start and end tags will be ignored. |
type |
Specifies the type of the variable that will refer to the
object. This must match the classname or be a superclass or an
interface that the class implements. Remember that the name
of the variable is designated via the id attribute. |
beanName |
Gives the name of the bean, as you would supply it to the instantiate
method of Beans . It is permissible to supply a type
and a beanName , and omit the class
attribute. |
You use jsp:setProperty to give values to properties of
beans that have been referenced earlier. You can do this in two contexts.
First, you can use jsp:setProperty after, but outside of, a jsp:useBean
element, as below:
<jsp:useBean id="myName" ... />
...
<jsp:setProperty name="myName"
property="someProperty" ... />
In this case, the jsp:setProperty is executed regardless
of whether a new bean was instantiated or an existing bean was found. A
second context in which jsp:setProperty can appear is inside
the body of a jsp:useBean element, as below:
<jsp:useBean id="myName" ... >
...
<jsp:setProperty name="myName"
property="someProperty" ... />
</jsp:useBean>
Here, the jsp:setProperty is executed only if a new object
was instantiated, not if an existing one was found.
There are four possible attributes of jsp:setProperty :
Attribute |
Usage |
name |
This required attribute designates the bean whose property will
be set. The jsp:useBean element must appear before
the jsp:setProperty element. |
property |
This required attribute indicates the property you want to set.
However, there is one special case: a value of "*"
means that all request parameters whose names match bean property
names will be passed to the appropriate setter methods. |
value |
This optional attribute specifies the value for the property.
String values are automatically converted to numbers, boolean ,
Boolean , byte , Byte , char ,
and Character via the standard valueOf
method in the target or wrapper class. For example, a value of "true"
for a boolean or Boolean property will
be converted via Boolean.valueOf , and a value of "42"
for an int or Integer property will be
converted via Integer.valueOf . You can't use both value
and param , but it is permissible to use neither. See
the discussion of param below. |
param |
This optional attribute designates the request parameter from
which the property should be derived. If the current request has
no such parameter, nothing is done: the system does not
pass null to the setter method of the property. Thus,
you can let the bean itself supply default values, overriding them
only when the request parameters say to do so. For example, the
following snippet says "set the numberOfItems
property to whatever the value of the numItems
request parameter is, if there is such a request parameter.
Otherwise don't do anything."
<jsp:setProperty name="orderBean"
property="numberOfItems"
param="numItems" />
If you omit both value and param , it
is the same as if you supplied a param name that
matches the property name. You can take this idea of
automatically using the request property whose name matches the
property one step further by supplying a property name of "*"
and omitting both value and param . In
this case, the server iterates through available properties and
request parameters, matching up ones with identical names.
|
Here's an example that uses a bean to create a table of prime numbers.
If there is a parameter named numDigits in the request data,
it is passed into the bean's numDigits property. Likewise for
numPrimes .
JspPrimes.jsp
To download the JSP source, right click on the
source code link. You can also download the
source code for the NumberedPrimes bean referenced by the
jsp:useBean element. Browse the source
code directory for other Java classes used by NumberedPrimes .
The best way to try it out on-line is to start with the
HTML page that acts as a front end to it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Reusing JavaBeans in JSP</TITLE>
<LINK REL=STYLESHEET
HREF="My-Style-Sheet.css"
TYPE="text/css">
</HEAD>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">
Reusing JavaBeans in JSP</TABLE>
</CENTER>
<P>
<jsp:useBean id="primeTable" class="hall.NumberedPrimes" />
<jsp:setProperty name="primeTable" property="numDigits" />
<jsp:setProperty name="primeTable" property="numPrimes" />
Some <jsp:getProperty name="primeTable" property="numDigits" />
digit primes:
<jsp:getProperty name="primeTable" property="numberedList" />
</BODY>
</HTML>
Here's a typical result:
%201_0.files/JspPrimes-IE.gif)
This element retrieves the value of a bean property, converts it to a
string, and inserts it into the output. The two required attributes are
name, the name of a bean previously referenced via jsp:useBean, and
property, the property whose value should be inserted. Here's an example;
for more examples, see Sections 8.2
and 8.4.
<jsp:useBean id="itemBean" ... />
...
<UL>
<LI>Number of items:
<jsp:getProperty name="itemBean" property="numItems" />
<LI>Cost of each:
<jsp:getProperty name="itemBean" property="unitCost" />
</UL>
This action lets you forward the request to another page. It has a
single attribute, page , which should consist of a relative
URL. This could be a static value, or could be computed at request time,
as in the two examples below.
<jsp:forward page="/utils/errorReporter.jsp" />
<jsp:forward page="<%= someJavaExpression %>" />
This action lets you insert the browser-specific OBJECT or
EMBED element needed to specify that the browser run an
applet using the Java plugin.
There are a small number of special constructs you can use in various
cases to insert comments or characters that would otherwise be treated
specially. Here's a summary:
Syntax |
Purpose |
<%-- comment --%>
|
A JSP comment. Ignored by JSP-to-scriptlet translator. Any
embedded JSP scripting elements, directives, or actions are
ignored. |
<!-- comment -->
|
An HTML comment. Passed through to resultant HTML. Any embedded
JSP scripting elements, directives, or actions are executed
normally. |
<\%
|
Used in template text (static HTML) where you really want "<% ". |
%\>
|
Used in scripting elements where you really want "%> ". |
\'
|
A single quote in an attribute that uses single quotes.
Remember, however, that you can use either single or double
quotes, and the other type of quote will then be a regular
character. |
\"
|
A double quote in an attribute that uses double quotes.
Remember, however, that you can use either single or double
quotes, and the other type of quote will then be a regular
character. |
%\>
|
%> in an attribute. |
<\%
|
<% in an attribute. |
|