也许用你的模型返回一个 DOMSource() ,如下所示:
@RequestMapping
public String overview(Model model) {
model.addAttribute("obj", new DOMSource());
return "list";
}
您在SpringSource 论坛上有一个示例。
不要忘记 SimpleFormController(来自我链接中的示例,在 Spring 3.0.x 中已弃用,但实现 XSL 视图的逻辑是相同的。
你可以在官方文档中找到一些非常有用的东西。
特别是以下部分:
17.5.1.3 将模型数据转换为 XML
17.5.1.4。定义视图属性
17.5.1.5。文档转换
你的控制器:
package xslt;
// 为简洁起见省略了导入
public class HomePage extends AbstractXsltView {
protected Source createXsltSource(Map model, String rootName, HttpServletRequest
request, HttpServletResponse response) throws Exception {
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element root = document.createElement(rootName);
List words = (List) model.get("wordList");
for (Iterator it = words.iterator(); it.hasNext();) {
String nextWord = (String) it.next();
Element wordNode = document.createElement("word");
Text textNode = document.createTextNode(nextWord);
wordNode.appendChild(textNode);
root.appendChild(wordNode);
}
return new DOMSource(root);
}
你的view.properties
文件:
home.(class)=xslt.HomePage
home.stylesheetLocation=/WEB-INF/xsl/home.xslt
home.root=words
您的 XSLT 样式表文件:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" omit-xml-declaration="yes"/>
<xsl:template match="/">
<html>
<head><title>Hello!</title></head>
<body>
<h1>My First Words</h1>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="word">
<xsl:value-of select="."/><br/>
</xsl:template>
</xsl:stylesheet>
祝你好运!
添加了关于Apache FOP 项目和使用 Servlets 进行 XSL 转换的信息:
private FopFactory fopFactory = FopFactory.newInstance();
private TransformerFactory tFactory = TransformerFactory.newInstance();
public void init() throws ServletException {
//Optionally customize the FopFactory and TransformerFactory here
}
[..]
//Setup a buffer to obtain the content length
ByteArrayOutputStream out = new ByteArrayOutputStream();
//Setup FOP
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
//Setup Transformer
Source xsltSrc = new StreamSource(new File("foo-xml2fo.xsl"));
Transformer transformer = tFactory.newTransformer(xsltSrc);
//Make sure the XSL transformation's result is piped through to FOP
Result res = new SAXResult(fop.getDefaultHandler());
//Setup input
Source src = new StreamSource(new File("foo.xml"));
//Start the transformation and rendering process
transformer.transform(src, res);
//Prepare response
response.setContentType("application/pdf");
response.setContentLength(out.size());
//Send content to Browser
response.getOutputStream().write(out.toByteArray());
response.getOutputStream().flush();