当前位置:编程学习 > JSP >>

利用JDK1.4中的Templates实现xslt转换的缓存

答案:javax.xml.transform.Templates是一个编译过的xsl, 线程安全, 可以从其中得到transformer. 在server端做xslt转换的BS架构中可以明显提高效率.

    //模板缓存
    static private Hashtable templates = new Hashtable();

    public static Transformer getTransformer(Source xslSource)
    throws Exception
    {
        Transformer transformer = null;
        String id = xslSource.getSystemId();
        if (null != id){
            synchronized(templates){
                Templates temp = (Templates)templates.get(id);
                if (null != temp){
//                    System.out.println("use cache: "+id);
                    return temp.newTransformer();
                }
            }
        }
        TransformerFactory factory = TransformerFactory.newInstance();
        Templates temp = factory.newTemplates(xslSource);
        if (null != id)
            synchronized(templates){
                templates.put(id,temp);
            }
        transformer = factory.newTransformer(xslSource);
        return transformer;
    }

    public static void transform(Source xmlSource, Source xslSource, Writer result, String encoding)
    throws Exception
    {
        if (xmlSource == null || xslSource == null || result == null)
            throw new NullPointerException("Null XSLT input");

        Transformer transformer = this.getTransformer(xslSource);
        transformer.setOutputProperty("encoding", encoding);

//        System.out.println("xfmr: "+transformer);

        StreamResult transformResult = new StreamResult(result);
        transformer.transform(xmlSource, transformResult);
    }

上一个:内置加密软件的嵌入用途Java软件今秋问世
下一个:Tomcat4的数据库连接池配置

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,