我有以下controller method
它成功發送xml
文本到spring mvc
應用程序的Web瀏覽器。問題在於它只是將文本發送到瀏覽器而不是格式化,因此瀏覽器中的輸出只是一堆混雜在一起的未格式化文本。 如何調整以下controller method
,以便它還將xsl
樣式表style.xsl
發送到用戶的網絡瀏覽器,並使用戶網絡瀏覽器中的內容成功格式化爲style.xsl
?服務xsl除了XML到網絡瀏覽器
這是我到目前爲止有:
@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);
}
請注意['application/xml'在MediaType中預先定義](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/MediaType.html#APPLICATION_XML ) 已經。另外,如果「somefile.xml」是靜態的,配置Spring將其作爲靜態資源而不是讀寫控制器內的響應會更容易和更高效。 – kryger 2014-11-07 00:55:13
@kryger你是說如果我要刪除一行'header.setContentType(new MediaType(「application」,「xml」));'? – CodeMed 2014-11-07 01:19:53
你可以用'header.setContentType(MediaType.APPLICATION_XML)'替換它; – kryger 2014-11-07 10:12:40