有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Javaservlet中打印XSLT转换的XML文档

我正在尝试使用Javaservlet(GlassFish服务器)打印转换后的XML文档。我从外部网站获取xml,用XSLT转换它,然后尝试打印转换后的文档。我相信XSL文件的格式是正确的,并且正在执行有效的转换

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.Result;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;

/**
 *
 * @author Kirie
 */
public class getArticles extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, TransformerConfigurationException, TransformerException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {


            // get the xsl stored in this project 
            ServletContext context = getServletContext();                       
            InputStream xsl = (InputStream)
                                (context.getResourceAsStream("/XSLTransformerCode.xsl"));

            // We need two source objects and one result
            // get an external xml document using a url in a 
            // string format
            String topic = request.getParameter("topic");
            String urlAsString = "";
            if(topic.equals("Business"))
                urlAsString = "http://rss.nytimes.com/services/xml/rss/nyt/Business.xml";
            else if(topic.equals("Technology"))
                urlAsString = "http://rss.nytimes.com/services/xml/rss/nyt/Technology.xml";
            else if(topic.equals("World"))
                urlAsString = "http://rss.nytimes.com/services/xml/rss/nyt/World.xml";

            Source xmlDoc =  new StreamSource(urlAsString);
            Source xslDoc =  new StreamSource(xsl);
            Result result =  new StreamResult(out);         

            // Prepare to transform 


            // The transformed document is returned to the browser.
           TransformerFactory factory = TransformerFactory.newInstance();
            Transformer trans = factory.newTransformer(xslDoc);
            trans.transform(xmlDoc,result);

            out.println(result.toString());

        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (TransformerException ex) {
            Logger.getLogger(getArticles.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (TransformerException ex) {
            Logger.getLogger(getArticles.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

这是执行转换的servlet。您可以从上面指定的URL访问XML文档。它们是RSS提要

 <?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>

  <xsl:output method="xml" 
        omit-xml-declaration="yes"
        doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
        doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"/>

    <xsl:template match="/">
    <html><head></head>
    <body>
    <h1>News Articles</h1>
    <ul>
        <xsl:for-each select = "rss/channel/item">
        <li>
            <xsl:value-of select = "title"/>
        </li>
        </xsl:for-each>
    </ul>
    </body>
    </html>
</xsl:template>
</xsl:stylesheet>

这是我用来转换文件的XSL文件。不幸的是,我不知道问题出在哪里。我试图把事情弄清楚,但我似乎做不到。任何意见都会很有帮助,我们将不胜感激。我将在线一段时间,以便能够回答问题

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>News Articles</h1>
<ul>
<li>Obama to Seek War Power Bill From Congress, to Fight ISIS</li>
<li>Kayla Mueller&rsquo;s Parents Are Said to Receive Photos of Her Corpse From ISIS</li>
<li>Towers of Secrecy: Mexican Political Family Has Close PRI Ties, and Homes in the U.S.</li>
<li>Jordan and Emirates Carry Out Airstrikes in Syria Against Islamic State</li>
<li>Australia Holds 2 in Terrorism Case</li>
<li>Bangkok Journal: In Thailand, the Ghost Business Thrives</li>
<li>Open Source: On YouTube, Vivid Evidence of War&rsquo;s Horror in Ukraine</li>
<li>Terrorist Claims Return Sept. 11 Suit to Spotlight</li>
<li>Obama to Recall Military Personnel From Ebola Zone, Officials Say</li>
<li>Agreement on Ukraine Cease-Fire Deal Is Reported</li>
<li>Venezuela Announces Plan to Relax Currency Controls</li>
<li>India&rsquo;s Aam Aadmi Party Sweeps Elections in Delhi</li>
<li>World Briefing: New DNA Tests Ordered in Argentine Prosecutor&rsquo;s Death</li>
<li>Robert Herzstein, 74, Dies; Historian Linked a U.N. Leader to War Crimes</li>
<li>Niger Adds Its Troops to the War on Boko Haram</li>
<li>Yemeni Militant Leader Pledges to Share Power</li>
<li>Dominique Strauss-Kahn&rsquo;s Defense: He Didn&rsquo;t Know Prostitutes Were at the Orgies</li>
<li>At War Blog: For Many Veterans, &lsquo;American Sniper,&rsquo; Right or Wrong, Starts an Important Conversation</li>
<li>Battered Ukrainian City of Mariupol Braces for Worst as Rebels Close In</li>
<li>Sinosphere Blog: University President Sees Echoes of Cultural Revolution in New Campaign</li>
</ul>
</body>
</html>

我在一个普通的java应用程序中运行XSLT,并将结果转储到一个文件中。上面的HTML代码就是给出的结果

提前谢谢! 基丽


共 (1) 个答案

  1. # 1 楼答案

    您需要设置正确的内容类型标题

    response.setContentType("text/xml");
    

    目前,浏览器试图将XML解释为HTML,因此不呈现任何内容


    尝试将最后一行从out.println(result.toString());更改为out.flush();。我认为这是不必要的,因为transform()也会通过StreamResult打印到out。此外,还可以将内容类型改回html