Chanky Mallick
Chanky Mallick

Reputation: 587

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. I am doing this from a simple main method inside a java class by providing the path.

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.

How can I achieve that?

Upvotes: 3

Views: 1699

Answers (1)

Brian Agnew
Brian Agnew

Reputation: 272387

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)
  2. set the returned type to be XML e.g. 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 e.g.

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

Upvotes: 5

Related Questions