How to Open a Word Document From a Servlet Response

Written by jim campbell
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Open a Word Document From a Servlet Response
Open a Word document from Java. (Java hot and black image by Pix by Marti from

Java servlets are Web services run on host servers that provide an interface for developers to work with the internal business objects. Java servlets are written in typical Java code, and they can be used to open Word documents. This is beneficial for programmers who work with Word documents on the Web server for user interaction and Web content. The documents can be created, edited and deleted using the Java servlet code.

Skill level:

Other People Are Reading


  1. 1

    Create your Java output stream variable. This is used to send the Word document to the user and open it in the code. The following code creates the output stream variable:

    ServletOutputStream output = res.getOutputStream();

  2. 2

    Set the MIME type. The MIME type sets the type of file the output stream expects. In this case, the type is a Word document, but it can be set to any file type. The following code sets the output type:

    res.setContentType( "application /msword" );

  3. 3

    Set the document you want to open. The following code opens the Word file. It is still not displayed to the user, but it is opened.

    res.setHeader("Content-disposition", "attachment; filename=my_doc.doc" );

  4. 4

    Output the file to the user's window. The "URL" class is used to set the output to the Word document. This step is only needed if you want to display the document you opened. The following code displays the Word document:

    URL url = new URL ( res );


Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.