首页 > 开发 > JSP > 正文

JSP结合XML+XSLT将输出转换HTML

2020-02-05 13:52:25
字体:
来源:转载
供稿:网友
  我们知道 xml+xslt就可以直接输出到支持xml的浏览器上,如ie 5.0以上,但是,我们还要考虑到有不少浏览器不直接支持xml,在这种情况下,我们需要在服务器上进行转换成html输出到浏览器,这种临时过渡办法恐怕要在一段时间内一直要使用.

  使用jsp 加上tablib标识库,我们可以完成这种转换。

  著名open source项目组jakarta.apache.org推出的系列标识库中,就有这个功能的tanglib:http://jakarta.apache.org/taglibs/doc/xsl-doc/intro.html

  按照jakarta配置方法,有点繁琐,需要修改或定义web.xml,本人经过摸索,使用下列相当简单的办法,就可以使jsp能成功运行xsl这个标识库了。

  xsl标识库有三个关键包:

  •   xerces.jar 可以在http://xml.apache.org/中得到
  •   xalan.jar 可以在http://xml.apache.org/中得到
  •   xsl.jar 从http://jakarta.apache.org/taglibs/doc/xsl-doc/intro.html得到

  1.将这三个包放置到tomcat的common/lib目录下,或者直接放入classpath环境中。

  2.在jsp中调用标识库:

  原来jakarta推荐方法是:

<%@taglib uri="http://jakarta.apache.org/taglibs/xsl-1.0" prefix="xsl" %>

  这就需要在/web-inf/web.xml下定义一下http://jakarta.apache.org/taglibs/xsl-1.0指向。如:

<taglib>
<taglib-uri>http://jakarta.apache.org/taglibs/xsl-1.0</taglib-uri>
<taglib-location>/web-inf/xsl.tld</taglib-location>
</taglib>

  这种做法虽然很标准,但是,如果你的容器一直使用tomcat,就完全不必了。

  我们的做法是:

<%@taglib uri="xsl.jar" prefix="xsl" %>

  我们以jakarta的xsl taglib附带的apply.jsp为例,正好了解一下jsp xml xslt三者之间的关系:

  apply.jsp

<%@taglib uri="xsl.jar" prefix="xsl" %>
<html>
<head>
<title>employee list</title>
</head>
<body bgcolor="white">

<p>下面展示了jsp的四种组合xml xslt的方法:
<p>下面使用apply方法,将已经存在的employees.xml和employeelist.xsl结合在一起

<xsl:apply xml="/xml/employees.xml" xsl="/xml/employeelist.xsl"/>
<hr>


<p>下面是使用已经存在employeelist.xsl 然后在jsp中自己直接写入xml数据.


<xsl:apply xsl="/xml/employeelist.xsl">
<?xml version="1.0" encoding="iso-8859-1"?>
<employees>
<employee id="123">
<first-name>john</first-name>
<last-name>doe</last-name>
<telephone>800-555-1212</telephone>
</employee>
<employee id="456">
<first-name>jane</first-name>
<last-name>smith</last-name>
<telephone>888-555-1212</telephone>
</employee>
<employee id="789">
<first-name>george</first-name>
<last-name>taylor</last-name>
<telephone>555-555-1212</telephone>
</employee>
</employees>
</xsl:apply>
<hr>

<p>下面使使用include调用的办法,这样一个xslt样式可以适应不同的xml文件。

<xsl:apply xsl="/xml/employeelist.xsl">
<xsl:include page="/xml/employees.xml"/>
</xsl:apply>
<hr>

<p>下面是使用import方法,在page-scope(类似scope="page")中导入xml文件</p>

<xsl:import id="data" page="/xml/employees.xml"/>
<xsl:apply namexml="data" xsl="/xml/employeelist.xsl"/>

</body>

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表