简体   繁体   English

如何使用JAXB从Servlet创建XML文件?

[英]How can I create XML files from Servlets using JAXB?

I just started JAX-B for writing XML files, I am able to create XML files from a java object and saving that file into a local path. 我刚刚启动了JAX-B来编写XML文件,我能够从java对象创建XML文件并将该文件保存到本地路径中。 I am doing this from a simple main method inside a java class by providing the path. 我是通过提供路径从java类中的一个简单的main方法做到这一点的。

public static void main(String ...s){
    JAXBContext jaxbcntxtobject = JAXBContext.newInstance(Student.class);
    Marshaller marshallerObject = jaxbcntxtobject.createMarshaller();
    marshallerObject.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);

    Student s1 = new Student(1, "Chanky Mallick","MCA");
    marshallerObject.marshal(s1, new FileOutputStream("e://StudentList.xml"));
}

But my main purpose is to do it from servlet or jsp so it can be saved into client machine as download. 但我的主要目的是从servlet或jsp中执行它,以便它可以作为下载保存到客户端计算机中。

How can I achieve that? 我怎样才能做到这一点?

You need to: 你需要:

  1. write to the ServletOutputStream in your response rather than your FileOutputStream (JAXB will let you specify any subclass of an OutputStream ) 写入响应中的ServletOutputStream而不是FileOutputStream (JAXB将允许您指定OutputStream任何子类)
  2. set the returned type to be XML eg response.setContentType("text/xml") 将返回的类型设置为XML,例如response.setContentType("text/xml")

You should probably set the content disposition such that the browser knows to download the content as a file and present the user with an option to save it under a given name eg 您应该设置内容处置,以便浏览器知道将内容下载为文件并向用户显示将其保存在给定名称下的选项,例如

response.setHeader( "Content-Disposition", "filename=" + filename );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM