struts框架下,在jsp页面显示XSL格式化的XML。

2024-05-01 05:58

本文主要是介绍struts框架下,在jsp页面显示XSL格式化的XML。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

struts框架下,在jsp页面显示XSL格式化的XML。需要以下步骤:

1 页面显示前XMLDom对象和Xsl文件地址存入request

 

public class LoadDataAction extends Action {

            private Document mydata;

            private String xslPath;

 

            public ActionForward execute(ActionMapping mapping,

                                     ActionForm form,

                                     HttpServletRequest request,

                                     HttpServletResponse response)

            throws Exception{

                        mydata=loadData();

                        xslPath=”resources/example.xsl”;

                        //XMLDom对象

                        request.setAttribute("userXml",mydata);

                        //Xsl文件地址

                        request.setAttribute("bodyXsl",xslPath);

                        return mapping.findForward("success");

            }

            private Document loadData(){

                        Document result=null;

                        try{

                                    //创建XMLDom对象,XMLDTD下面给出

                        }catch(Exception e){

                                    e.printStackTrace();

                        }

                        return result;

            }

}

dtd文件内容

<?xml version="1.0" encoding="UTF-8"?>

<!--DTD generated by XMLSpy v2005 rel. 3 U (http://www.altova.com)-->

<!--the entity declarations may be overridden in the internal subset-->

<!--the declarations below should not be modified-->

<!--element name mappings-->

<!ENTITY % UsersBasicInfo "UsersBasicInfo">

<!ENTITY % UserBasicInfo "UserBasicInfo">

<!ENTITY % UserID "UserID">

<!ENTITY % Password "Password">

<!ENTITY % UserName "UserName">

<!ENTITY % Email "Email">

<!--element and attribute declarations-->

<!--Title: ubi.xsd

 

Subject: the user basic information.

                  Publisher: Nova Corporation, Colimas.

Format: text/xml

 

Creator: Zhao Lei

                 

Date.Created: 2005-04-26

                 

Language: en-US

                 

Description: User Basic Information Data Definition

                 

Change Log:

Version     Date                     Modifier   Description

 

01.00 2005/04/26       Zhao Lei     Initial release.                                                             

                  -->

<!ELEMENT %UsersBasicInfo; ((%UserBasicInfo;)*)>

<!--One User Basic Information-->

<!ELEMENT %UserBasicInfo; (%UserID;, (%Password;)?, %UserName;, %Email;)>

<!--The max Length of characters of it is 20-->

<!ELEMENT %UserID; (#PCDATA)>

<!--Show it only when user is administor. 12 fixed characters-->

<!ELEMENT %Password; (#PCDATA)>

<!ELEMENT %UserName; (#PCDATA)>

<!ELEMENT %Email; (#PCDATA)>

 

xsl文件内容

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<xsl:variable name="userinfo.comp" select="'Component Name'"/>

<xsl:variable name="userinfo.id" select="'Serial No'"/>

<xsl:variable name="userinfo.role" select="'Role Name'"/>

<xsl:variable name="userinfo.user" select="'User ID*'"/>

<xsl:variable name="userinfo.name" select="'User Name*'"/>

<xsl:variable name="userinfo.passord" select="'Password*'"/>

<xsl:variable name="userinfo.mail" select="'Email Address*'"/>

<xsl:variable name="userinfo.userp" select="'User Profile'"/>

<xsl:variable name="userinfo.required" select="'All items are required'"/>

<xsl:variable name="template.edit" select="'Edit!'"/>

<xsl:variable name="userinfo.access" select="'Access Role List'"/>

 

<xsl:template match="UserBasicInfo">

      <h1><xsl:value-of  select="$userinfo.userp"/></h1>

      <xsl:variable name="userid" select="UserID"/>

      <input type="button" name="edit" value="{$template.edit}"/>

      <p><font color="#003399" size="4"><xsl:value-of  select="$userinfo.required"/></font></p> 

      <table border="0" width="826" height="103" cellpadding="2" cellspacing="1">

     

                  <tr>

                              <td bgcolor="#E0F1FF"><xsl:value-of  select="$userinfo.user"/></td>

                              <td ><xsl:value-of select="$userid"/></td>

                  </tr>

                  <tr>

                              <td bgcolor="#E0F1FF"><xsl:value-of  select="$userinfo.passord"/></td>

                              <td><xsl:value-of select="Password"/></td>

                  </tr>

                  <tr>       

                              <td bgcolor="#E0F1FF"><xsl:value-of  select="$userinfo.name"/></td>

                              <td><xsl:value-of select="UserName"/></td>

                  </tr>

                  <tr>       

                              <td bgcolor="#E0F1FF"><xsl:value-of  select="$userinfo.mail"/></td>

                              <td><xsl:value-of select="Email"/></td>                                            

                  </tr>

      </table>

</xsl:template>

 

</xsl:stylesheet>

2 创建xsltag

tld文件内容如下:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>

      <tlibversion>1.0</tlibversion>

      <jspversion>1.1</jspversion>

      <shortname>colimas</shortname>

      <info>Contains xsl tag definitions used in colimas</info>

      <tag>

            <name>xsl</name>

            <tagclass>com.nova.colimas.common.tags.TagXSL</tagclass>

            <bodycontent>empty</bodycontent>

            <info>Gets XML DOM and XSL resource path from the HTTP request and uses these datas to generate and display HTML. The XSL resource path is localized according to the java.util.Locale that is found in the context. The different context are indicated by their scope : "application", "session", "request" or "page". The locale is optional ; if it is not supplied, the default Locale of the server is used.</info>

            <attribute>

                  <name>xslKey</name>

                  <required>true</required>

                  <rtexprvalue>false</rtexprvalue>

            </attribute>

            <attribute>

                  <name>xslScope</name>

                  <required>true</required>

                  <rtexprvalue>false</rtexprvalue>

            </attribute>

            <attribute>

                  <name>xmlKey</name>

                  <required>true</required>

                  <rtexprvalue>false</rtexprvalue>

            </attribute>

            <attribute>

                  <name>xmlScope</name>

                  <required>true</required>

                  <rtexprvalue>false</rtexprvalue>

            </attribute>

      </tag>

</taglib>

tagclass内容如下:

* Gets XML DOM and XSL resource path from the HTTP request and uses these

 * datas to generate and display HTML. The XSL resource path is localized

 * according to the java.util.Locale that is found in the context. The different

 * context are indicated by their scope : "application", "session", "request" or "page".

 * The locale is optional ; if it is not supplied, the default Locale of the server is used.

 * @author tyrone

 */

public class TagXSL extends TagSupport

{

            /**

                        * Key for the XMLObject in its context, xmlKey

                        */

            protected String xmlKey;

            /**

                        * Scope for the XMLObject, xmlScope

                        */

            protected int xmlScope;

            /**

                        * Key for the XSL resource path, xslKey

                        */

            protected String xslKey;

            /**

                        * Scope for the XSL resource path, xslScope

                        */

            protected int xslScope;

            /**

             * Executes the Tag. It gets XML and XSL information, then generates the HTML before write it.

             */

            public int doStartTag() throws JspException

            {

                        String xslPath = null;

                        long start = System.currentTimeMillis();

                        try

                        {

                                    // Gets the XML Object from the context

                                    Document xmlObject = (Document) pageContext.getRequest().getAttribute(xmlKey);

                                    if (xmlObject == null)

                                                throw new JspTagException("Cannot retrieve the XMLObject in scope " + xmlScope + " under the key " + xmlKey);

                                    // Gets the XSL resource path from the context

                                    xslPath = (String) pageContext.getRequest().getAttribute(xslKey);

                                    if (xslPath == null)

                                                throw new JspTagException("Cannot retrieve the XSL path in scope " + xslScope + " under the key " + xslKey);

                                    // Try to get the Locale from the context

                                    Locale locale = (Locale) pageContext.getAttribute(Globals.LOCALE_KEY, PageContext.SESSION_SCOPE);

 

                                    // Right. We have all needed elements.

                                    try

                                    {

                                                // Do the transformation

                                                XSLTransform.transform(xmlObject, xslPath, locale, pageContext.getOut());

                                                // All is done, continue to execute the JSP

                                                return EVAL_PAGE;

                                    }

                                    catch (Exception ex)

                                    {

                                                //Console.error (this, "Cannot transform XML", ex);

                                                throw new JspTagException(ex.getMessage());

                                    }

                        }

                        finally

                        {

                                    long end = System.currentTimeMillis();

                                    System.out.println("Time for TagXSL (" + xslPath + ") : " + (end - start) + " ms");

                                    //Console.verbose(this, "Time for TagXSL (" + xslPath + ") : " + (end - start) + " ms");

                        }

            }

}

3 XSLTransform的实现

/**

 * Transform XML with XSL file to show in web page

 * @author tyrone

 *

 */

public class XSLTransform {

            /**

             * Internal factory

             */

            private static TransformerFactory transformerFactory;

            static

            {

                        transformerFactory = TransformerFactory.newInstance();

            }

            /**

             * Method to transform an XMLObject into an XHTML string

             * by using an XSL stylesheet.

             *

             * The result of the transformation is given to the Writer given as a parameter.

             * @param xo The XMLObject to transform

             * @param xslResourcePath The absolute resource path to the XSL file, without any

             * country information.

             * @param locale The information about localization of the XSL file

             * @param output Output for the transformation.

             * @see XSLServer

             */

            public static void transform(Document xo, String xslResourcePath, Locale locale, Writer output) throws IOException, ParserConfigurationException, SAXException, TransformerException, TransformerConfigurationException, CLMSException

            {

                        // Get the XMLObject DOM

                        Document xmlDom = xo

                        // Get the XSL DOM,本文忽略如何得到XSLDocument

                        Document xslDom = XSLServer.getXSL(xslResourcePath, locale);

                        transformAsString(xmlDom, xslDom, output);

            }

 

            /**

             * Transforms the <code>xml</code> in a XML string

             * to the <code>xsl</code> XSLT stylesheet.

             *

             * The output of the transformation is put into the given Writer.

             * @param xml The XML DOM

             * @param xsl The XSL DOM

             * @param output Output for the transformation.

             */

            public static void transformAsString(Document xml, Document xsl, Writer output) throws IOException, SAXException, TransformerException, TransformerConfigurationException

            {

                        // XSL source

                        DOMSource xslSource = new DOMSource(xsl);

                        // Transformer

                        Transformer transformer = transformerFactory.newTransformer(xslSource);

                        // Prepare the result

                        StreamResult result = new StreamResult(output);

                        // Process

                        transformer.transform(new DOMSource(xml), result);

                       

            }         

}

结果如下:

这篇关于struts框架下,在jsp页面显示XSL格式化的XML。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/950866

相关文章

Java进行日期解析与格式化的实现代码

《Java进行日期解析与格式化的实现代码》使用Java搭配ApacheCommonsLang3和Natty库,可以实现灵活高效的日期解析与格式化,本文将通过相关示例为大家讲讲具体的实践操作,需要的可以... 目录一、背景二、依赖介绍1. Apache Commons Lang32. Natty三、核心实现代

Python Selenium动态渲染页面和抓取的使用指南

《PythonSelenium动态渲染页面和抓取的使用指南》在Web数据采集领域,动态渲染页面已成为现代网站的主流形式,本文将从技术原理,环境配置,核心功能系统讲解Selenium在Python动态... 目录一、Selenium技术架构解析二、环境搭建与基础配置1. 组件安装2. 驱动配置3. 基础操作模

C#实现查找并删除PDF中的空白页面

《C#实现查找并删除PDF中的空白页面》PDF文件中的空白页并不少见,因为它们有可能是作者有意留下的,也有可能是在处理文档时不小心添加的,下面我们来看看如何使用Spire.PDFfor.NET通过C#... 目录安装 Spire.PDF for .NETC# 查找并删除 PDF 文档中的空白页C# 添加与删

exfat和ntfs哪个好? U盘格式化选择NTFS与exFAT的详细区别对比

《exfat和ntfs哪个好?U盘格式化选择NTFS与exFAT的详细区别对比》exFAT和NTFS是两种常见的文件系统,它们各自具有独特的优势和适用场景,以下是关于exFAT和NTFS的详细对比... 无论你是刚入手了内置 SSD 还是便携式移动硬盘或 U 盘,都需要先将它格式化成电脑或设备能够识别的「文

Spring框架中@Lazy延迟加载原理和使用详解

《Spring框架中@Lazy延迟加载原理和使用详解》:本文主要介绍Spring框架中@Lazy延迟加载原理和使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录一、@Lazy延迟加载原理1.延迟加载原理1.1 @Lazy三种配置方法1.2 @Component

浅析如何使用xstream实现javaBean与xml互转

《浅析如何使用xstream实现javaBean与xml互转》XStream是一个用于将Java对象与XML之间进行转换的库,它非常简单易用,下面将详细介绍如何使用XStream实现JavaBean与... 目录1. 引入依赖2. 定义 JavaBean3. JavaBean 转 XML4. XML 转 J

电脑显示mfc100u.dll丢失怎么办?系统报错mfc90u.dll丢失5种修复方案

《电脑显示mfc100u.dll丢失怎么办?系统报错mfc90u.dll丢失5种修复方案》最近有不少兄弟反映,电脑突然弹出“mfc100u.dll已加载,但找不到入口点”的错误提示,导致一些程序无法正... 在计算机使用过程中,我们经常会遇到一些错误提示,其中最常见的就是“找不到指定的模块”或“缺少某个DL

Python利用ElementTree实现快速解析XML文件

《Python利用ElementTree实现快速解析XML文件》ElementTree是Python标准库的一部分,而且是Python标准库中用于解析和操作XML数据的模块,下面小编就来和大家详细讲讲... 目录一、XML文件解析到底有多重要二、ElementTree快速入门1. 加载XML的两种方式2.

Spring 基于XML配置 bean管理 Bean-IOC的方法

《Spring基于XML配置bean管理Bean-IOC的方法》:本文主要介绍Spring基于XML配置bean管理Bean-IOC的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一... 目录一. spring学习的核心内容二. 基于 XML 配置 bean1. 通过类型来获取 bean2. 通过

使用Python将JSON,XML和YAML数据写入Excel文件

《使用Python将JSON,XML和YAML数据写入Excel文件》JSON、XML和YAML作为主流结构化数据格式,因其层次化表达能力和跨平台兼容性,已成为系统间数据交换的通用载体,本文将介绍如何... 目录如何使用python写入数据到Excel工作表用Python导入jsON数据到Excel工作表用