Serving xsl in addition to xml for web browser
I have the following controller method
one that successfully sends text xml
to a web browser in an application spring mvc
. The problem is that it just sends text to the browser, not the format, so the output in the browser is just a bunch of unformatted text mixed together. How can I configure the following controller method
so that it also xsl
sends the stylesheet style.xsl
to the user's web browser and so that the content in the user's web browser is successfully formatted to style.xsl
?
Here's what I have so far:
@RequestMapping(value = "actionName.xml", method = RequestMethod.GET)
public HttpEntity<byte[]> getXml(ModelMap map, HttpServletResponse response) {
String xml = "";
String inputpath = "path\\to\\";
String filename = "somefile.xml";
String filepluspath = inputpath+filename;
StreamSource source = new StreamSource(filepluspath);
try {
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.transform(source,result);
xml = writer.toString();
} catch (Exception e) {e.printStackTrace();}
byte[] documentBody = xml.getBytes();
HttpHeaders header = new HttpHeaders();
header.setContentType(new MediaType("application", "xml"));
header.setContentLength(documentBody.length);
return new HttpEntity<byte[]>(documentBody, header);
}
source to share
The direct answer to your question is "you can't" - there is no way to send two resources in one HTTP response.
You can include a link to the XSLT file in the header of the returned XML file:
<?xml-stylesheet href="style.xsl" type="text/xsl"?>
This will force the user's browser to try to load and apply ./style.xsl
to the data, so your server will have to expose it.
UPDATE: The URI in the stylesheet can be arbitrary; if you only want to apply the style when viewed on your page, you can make it relative to the URI that serves your document. If yours @RequestMapping
allows something like http://your-server.com/app/actionName.xml
, you can add a static resource to your application http://your-server.com/app/static/style.xsl
and access it via
<?xml-stylesheet href="static/style.xsl" type="text/xsl"?>
Alternatively, you can embed XSLT directly into XML data and not worry about URL mapping, but that's a topic for another question (already answered by the way) .
source to share