我是Spring新手,我需要从spring控制器传递一个XML文件到我的JavaScript文件。任何人都可以详细说明我应该怎么做吗? 我在我的控制器上尝试了这个,但响应主体不是内容。
@Api(value = "XML", description = "")
@RequestMapping("/XML/v1/setting")
public class XMLController{
@RequestMapping(method = RequestMethod.GET,
value = "/createFOO",
produces = "application/xml")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public Document createFOO(){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document doc1 = null;
try {
builder = factory.newDocumentBuilder();
doc1 = builder.parse(new FileInputStream("largeXmlGraph.xml"));
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
return doc1;
}
}
答案 0 :(得分:2)
你正在走向复杂的道路。
@RequestMapping(method = RequestMethod.GET,value = "/createFOO",produces = "application/xml")
public void createFOO(OutputStream out){
try (InputStream is = new FileInputStream("largeXmlGraph.xml")) {
StreamUtils.copy(is, out);
} catch (IOException e) {
e.printStackTrace();
}
}
这样的东西应该有用,你可能想要添加更好的异常处理(例如向客户端发送错误)。
答案 1 :(得分:0)
为了使用application/xml
,请添加此依赖项
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
到Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity的参考链接