(一)后台转换,不需要jsp页面(word模板,xml模板)
1.需要下载xalan.jar(在博客资源内,免分)
2.需要xslt文件(该文件对相应格式的xml,语法参考http://www.w3school.com.cn/xsl/)
例如
3.后台将word转换为xml(如果直接另存为word xml 有时格式不完整,还是需要后台处理)。
对xml进行解析生成org.dom4j.Document对象例如sourceXMLDocument。
4.Action中
xsltPageAddress为上述xstl文件全路径,sourceXMLDocument为上述后台生成Document
SAXReader reader=new SAXReader();
TransformerFactory factory=TransformerFactory.newInstance();
StreamSource xsl=new StreamSource(xsltPageAddress);
Transformer transformer=factory.newTransformer(xsl);
Properties properties=transformer.getOutputProperties();
properties.setProperty(OutputKeys.ENCODING,"GBK");
properties.setProperty(OutputKeys.METHOD, "html");
properties.setProperty(OutputKeys.VERSION, "4.0");
transformer.setOutputProperties(properties);
DocumentSource documentSource=new DocumentSource(sourceXMLDocument);
StringWriter strWriter=new StringWriter();
StreamResult streamResult=new StreamResult(strWriter);
transformer.transform(documentSource, streamResult);
System.out.println("strWriter:"+strWriter);
OutputStream outputStream=ServletActionContext.getResponse().getOutputStream();
outputStream.write(strWriter.toString().getBytes());
outputStream.close();
5.struts2配置
这样后台会报inputName错误,但是不影响生成Html
(二)前台页面转换
1,2,步骤如上
3.后台根据word生成一个新的xml(比较麻烦,因为需要删除)
4.struts2正常配置,并配置物理结果视图JSP
5.jsp页面代码
<%@page import="javax.xml.transform.*,javax.xml.transform.stream.*" %>
<%
String xmlAddress=(String)request.getAttribute("xmlAddress"); //需要转换的XML地址
String xsltAddress=(String)request.getAttribute("xsltAddress"); //xslt样式文件地址
TransformerFactory tFactory=TransformerFactory.newInstance();
System.out.println(xsltAddress);
Transformer transformer=tFactory.newTransformer(new StreamSource(application.getRealPath(“")+"\\"+xsltAddress));
System.out.println(xsltAddress);
transformer.transform(new StreamSource(application.getRealPath("")+"\\"+xmlAddress),new StreamResult(response.getOutputStream()));
out.println();
out.clear();
out=pageContext.pushBody();
%>
欢迎加入我的QQ交流群425783133