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

相关文章

在MyBatis的XML映射文件中<trim>元素所有场景下的完整使用示例代码

《在MyBatis的XML映射文件中<trim>元素所有场景下的完整使用示例代码》在MyBatis的XML映射文件中,trim元素用于动态添加SQL语句的一部分,处理前缀、后缀及多余的逗号或连接符,示... 在MyBATis的XML映射文件中,<trim>元素用于动态地添加SQL语句的一部分,例如SET或W

Python xmltodict实现简化XML数据处理

《Pythonxmltodict实现简化XML数据处理》Python社区为提供了xmltodict库,它专为简化XML与Python数据结构的转换而设计,本文主要来为大家介绍一下如何使用xmltod... 目录一、引言二、XMLtodict介绍设计理念适用场景三、功能参数与属性1、parse函数2、unpa

关于Maven中pom.xml文件配置详解

《关于Maven中pom.xml文件配置详解》pom.xml是Maven项目的核心配置文件,它描述了项目的结构、依赖关系、构建配置等信息,通过合理配置pom.xml,可以提高项目的可维护性和构建效率... 目录1. POM文件的基本结构1.1 项目基本信息2. 项目属性2.1 引用属性3. 项目依赖4. 构

使用Python实现批量访问URL并解析XML响应功能

《使用Python实现批量访问URL并解析XML响应功能》在现代Web开发和数据抓取中,批量访问URL并解析响应内容是一个常见的需求,本文将详细介绍如何使用Python实现批量访问URL并解析XML响... 目录引言1. 背景与需求2. 工具方法实现2.1 单URL访问与解析代码实现代码说明2.2 示例调用

Linux磁盘分区、格式化和挂载方式

《Linux磁盘分区、格式化和挂载方式》本文详细介绍了Linux系统中磁盘分区、格式化和挂载的基本操作步骤和命令,包括MBR和GPT分区表的区别、fdisk和gdisk命令的使用、常见的文件系统格式以... 目录一、磁盘分区表分类二、fdisk命令创建分区1、交互式的命令2、分区主分区3、创建扩展分区,然后

使用JavaScript将PDF页面中的标注扁平化的操作指南

《使用JavaScript将PDF页面中的标注扁平化的操作指南》扁平化(flatten)操作可以将标注作为矢量图形包含在PDF页面的内容中,使其不可编辑,DynamsoftDocumentViewer... 目录使用Dynamsoft Document Viewer打开一个PDF文件并启用标注添加功能扁平化

SpringBoot如何访问jsp页面

《SpringBoot如何访问jsp页面》本文介绍了如何在SpringBoot项目中进行Web开发,包括创建项目、配置文件、添加依赖、控制层修改、测试效果以及在IDEA中进行配置的详细步骤... 目录SpringBoot如何访问JSP页python面简介实现步骤1. 首先创建的项目一定要是web项目2. 在

电脑显示hdmi无信号怎么办? 电脑显示器无信号的终极解决指南

《电脑显示hdmi无信号怎么办?电脑显示器无信号的终极解决指南》HDMI无信号的问题却让人头疼不已,遇到这种情况该怎么办?针对这种情况,我们可以采取一系列步骤来逐一排查并解决问题,以下是详细的方法... 无论你是试图为笔记本电脑设置多个显示器还是使用外部显示器,都可能会弹出“无HDMI信号”错误。此消息可能

MyBatis框架实现一个简单的数据查询操作

《MyBatis框架实现一个简单的数据查询操作》本文介绍了MyBatis框架下进行数据查询操作的详细步骤,括创建实体类、编写SQL标签、配置Mapper、开启驼峰命名映射以及执行SQL语句等,感兴趣的... 基于在前面几章我们已经学习了对MyBATis进行环境配置,并利用SqlSessionFactory核

第10章 中断和动态时钟显示

第10章 中断和动态时钟显示 从本章开始,按照书籍的划分,第10章开始就进入保护模式(Protected Mode)部分了,感觉从这里开始难度突然就增加了。 书中介绍了为什么有中断(Interrupt)的设计,中断的几种方式:外部硬件中断、内部中断和软中断。通过中断做了一个会走的时钟和屏幕上输入字符的程序。 我自己理解中断的一些作用: 为了更好的利用处理器的性能。协同快速和慢速设备一起工作