package chap8;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
/**
* Allows any combination of English, Spanish, and Chinese XML
* and XSLT.
*/
public class LanguageDemo extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
ServletContext ctx = getServletContext();
// these are all required parameters from the HTML form
String xmlLang = req.getParameter("xmlLanguage");
String xsltLang = req.getParameter("xsltLanguage");
String charEnc = req.getParameter("charEnc");
// convert to system-dependent path names
String xmlFileName = ctx.getRealPath(
"/WEB-INF/xml/numbers_" + xmlLang + ".xml");
String xsltFileName = ctx.getRealPath(
"/WEB-INF/xslt/numbers_" + xsltLang + ".xslt");
// do this BEFORE calling HttpServletResponse.getWriter()
res.setContentType("text/html; charset=" + charEnc);
try {
Source xmlSource = new StreamSource(new File(xmlFileName));
Source xsltSource = new StreamSource(new File(xsltFileName));
TransformerFactory transFact = TransformerFactory.newInstance();
Transformer trans = transFact.newTransformer(xsltSource);
trans.setOutputProperty(OutputKeys.ENCODING, charEnc);
// note: res.getWriter() will use the encoding type that was
// specified earlier in the call to res.setContentType()
trans.transform(xmlSource, new StreamResult(res.getWriter()));
} catch (TransformerConfigurationException tce) {
throw new ServletException(tce);
} catch (TransformerException te) {
throw new ServletException(te);
}
}
}
|