JSTL的 c:import应用介绍



JSTL的 c:import应用介绍。c:import 与jSP的include原理相似。但深入研究 c:import (或任何JSTL标记),会发现许多其它功能。除分配参数并管理本地文件内容外, c:import标签 还可以引入外部站点的内容。与 jsp:include 相似, c:import 使用各种参数以便可在Web站点灵活移动内容。但与include指令不同,c:import 并不限制访问本地文件。

以下是<c:import标签实例c_import.jsp:

<%@ page language=”java” pageEncoding=”utf-8″%>
<%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<title>My JSP ‘c_import.jsp’ starting page</title>
</head>
<body>
<c:import var=”index” url=”http://localhost:8080/jsp_jstl/index.jsp” charEncoding=”utf-8″ scope=”request” />
<h1>index.jsp 的源代码为:</h1>
<br/><br/>
<c:out value=”${index}” escapeXml=”true”></c:out>
</body>
</html>

jsp:include与JSTL C:import用法比较:

jsp:include:

<jsp:include page=”header.jsp” flush=”true”>

<jsp:param name=”pageTitle” value=”newInstance.com”/>
<jsp:param name=”pageSlogan” value=” ” />
</jsp:include>

JSTL C:import


<c:import url=”header.jsp”>
<c:param name=”pageTitle” value=”newInstance.com”/>
<c:param name=”pageSlogan” value=” ” />
</c:import>

c:param 和 jsp:param 非常相似。

导入外部内容

使用 c:import 的真正优势在于,它可以引入外部Web站点的内容或Web应用程序。在前面学习jsp:includes时,您可能已经注意到,我们使用file(文件)属性来为include指定静态内容。file(文件)属性正如其名称所示:使您可以引入本地文件的内容。 c:import 的相应属性为 url ,它也正如其名称所示:使您能够引入任何URL。c:import 不仅可以使用本地文件的内容来填充您的站点网页,而且还允许您引入任何URL的内容,使其它站点的内容可以真正灵活地适应您自己站点的外观和风格。

<%@ page language=”java” contentType=”text/html” %>

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<html>
<head>
     <title>newInstance.com</title>
     <meta http-equiv="Content-Type" 
       content="text/html; charset=iso-8859-1" />
     <link href="/styles/default.css" rel="stylesheet" type="text/css" />
</head>
<body>
<c:import url="header.jsp">
     <c:param name="pageTitle" 
       value="newInstance.com :: True North Guitars"/>
     <c:param name="pageSlogan" value="...building it from scratch" />
</c:import>
<%@ include file="/navigation.jsp" %>
<c:import url="bookshelf.jsp" />
<c:import 
  url="http://www.truenorthguitars.com/Clients/Richman/index.htm" />
<%@ include file="/footer.jsp" %>
</body>
</html>

 

所有导入图像都不显示,并且相关链接全部出现故障。其实原因很很简单。外部资源(本例中是图像文件)被解释(interpreted),而您将解释结果直接导入您的输出流。外部图像文件链接如 /images/guitar-01-24.jpg 将显示不存在。解决该问题的方法是将原图像复制到您的站点,这是一项完全不同(并且消耗更多时间)的技术。因此,最好知道要导入的外部内容是否是纯文本。