JSP语法元素概述
首先,为了更清楚地说明问题,这里简要概述了JSP语法元素:
- 指令:这些指令传达有关JSP页面的整体信息。
- 脚本元素:这些是Java编码元素,如声明、表达式、脚本块和注释。
- 对象和作用域:JSP对象可以显式或隐式地创建,并且可以在给定的作用域内访问,例如从JSP页面或会话的任何位置。
- 动作:这些动作在JSP响应中创建对象或影响输出流(或两者兼有)。
JSP中如何包含内容
JSP文件中有几种机制可以重用内容。
以下4种将内容包含在JSP中的机制可以归类为直接重用:
(前3种机制引用自"Head First Servlets and JSP")
1) The include directive:
<%@ include file="header.html" %>
Static: adds the content from the value of the file attribute to the current page at translation time. The directive was
originally intended for static layout templates, like HTML headers.
2) The <jsp:include>
standard action:
<jsp:include page="header.jsp" />
Dynamic: adds the content from the value of the page attribute to the current page at request time. Was intended more for dynamic
content coming from JSPs.
3) The <c:import>
JSTL tag:
<c:import url=”http://www.example.com/foo/bar.html” />
Dynamic: adds the content from the value of the URL attribute to the current page, at request time. It works a lot like
<jsp:include>
, but it’s more powerful and flexible: unlike the
other two includes, the <c:import>
URL can be from outside the
web Container!
4) Preludes and codas:
Static: preludes and codas can be applied only to the beginnings and ends of pages.
You can implicitly include preludes (also called headers) and codas
(also called footers) for a group of JSP pages by adding
<include-prelude>
and <include-coda>
elements respectively within
a <jsp-property-group>
element in the Web application web.xml deployment descriptor.
Read more here:
• Configuring Implicit Includes at the Beginning and End of JSPs
• Defining implicit includes
标签文件是一种间接的内容重用方法,一种封装可重用内容的方式。
标签文件是一个包含可重用JSP代码片段的源文件,可作为自定义标签使用。
包含文件和标签文件的目的是不同的。
标签文件(JSP 2.0引入的概念)是创建自定义标签的选项之一。这是一种更快、更简便的构建自定义标签的方法。
自定义标签,也称为标签扩展,是允许将其他Java组件提供的自定义逻辑和输出插入到JSP页面中的JSP元素。通过自定义标签提供的逻辑由一个称为标签处理器的Java对象实现。
一些可以由自定义标签执行的任务的示例包括对隐式对象进行操作、处理表单、访问数据库和其他企业服务(如电子邮件和目录),以及实现流程控制。
关于您的编辑
也许在您的示例中(在您的“编辑”段落中),直接包含和标签文件之间没有区别。但是自定义标签具有丰富的功能。它们可以:
也可以从《Pro JSP 2》中阅读这篇文章:
了解 JSP 自定义标签。
有用的阅读
结论
为每个任务使用合适的工具。
使用标签文件是一种快速简便的方法,可以创建自定义标签,帮助您封装可重用的内容。
至于在JSP中包含内容(引用自这里):
- 如果文件很少更改,请使用包含指令。这是最快的机制。如果您的容器无法自动检测更改,您可以通过删除主页面类文件来强制生效更改。
- 仅在内容经常更改且在请求主页面之前无法确定要包含的页面时,请使用包含操作。
*
)。<jsp:include>
是标准的include动作,<%@ include file="" %>
是include指令。请阅读最后一节(灰色框中)以了解其优势(即何时选择其中之一的建议)。还可以查看这篇文章(http://sharat.wordpress.com/2006/08/28/10-what-is-the-difference-between-pagedirective-include-action-tag-include/)获取详细描述。希望对你有所帮助。 - informatik01include standard action
,每次我们“要求”包含的页面时都会进行翻译?因为如果只翻译一次,它就不会是动态的,对吧?我的意思是它看不到任何更改的内容。 - Stefan<jsp:include>
时生成代码的示例。此外,这是关于 "JSP 执行" 过程的非常有帮助的描述。 - informatik01