Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to download document files from webserver using Servlet

In this tutorial, we will learn the types of responses that can be produced using a servlet. Also we learn the processing of a multimedia response using a servlet to download a document file.

When a request comes to a web server using a url, a web server generates a response to the client against the request. A response could be of any type. It could be a textual or html response, a multimedia response like video or audio response or document file response. These all type of responses are made available by Servlet technology in java. The textual and html responses are normally processed by the web server, whereas multimedia responses are made available to download or to open or play directly using the client application.

Servlet Multimedia Response in Detail:

When a user submits a request to pull a document file from the web server, user is asked to open a file or to download a file from server. Servlet make available data files to client application and rest of the functionality is made by client application. A client application may prompt the user to open a document or download the document else it may downloaded directly or open directly.

A developer has to specify a response type by the servlet, whenever a servlet is being created. A HttpServletResponse interface takes care of generating response.

Listing 1: WordServlet Servlet Class to download a ms – word document

Import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/WordServlet")
public class WordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public WordServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/msword");
		PrintWriter out = response.getWriter();
		out.println("THis doc is generated by servlet");
		out.close();
	}

}

Above table code creates a MS-Word document file that prints a simple text statement “This doc is generated by servet.”

Listing 2: ExcelServlet Servlet Class to download a ms – excel docoument

Import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ExcelServlet")
public class ExcelServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ExcelServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/vnd.ms-excel");
		PrintWriter out = response.getWriter();
		out.println("Name\tJob\tSalary");
		out.println("Raj\tAccountant\t20000");
		out.println("Vinay\tAccountant\t20000");
		out.println("Rajesh\tAccountant\t20000");
		out.println("\tTotal:\t=sum(c2:c3)");
		out.close();
	}

}

The above table code creates a Ms-Excel document file that calculate the salary of all employees and produces the sum of these employee’s salary.

In the above listing 1 and 2, The first seven lines of the code imports seven java classes and interfaces that are required to run this servlet. @WebServlet is the next line of code that is servlet annotation to define a url pattern for this web servlet. This url pattern will help to call the servlet using html form action url. The url pattern for these servlets are:

@WebServlet(“WordServlet”) and @WebServlet(“ExcelServlet”)

In the next line a WordServlet class is created that extends HttpServlet class that was defined into the javax.servlet.http package.

The next line defines a serialVersionUID variable that is used by Eclipse IDE, if it is not defined into the class, Eclipse will raise a warning. In the next line a default constructor is defined that calls the super() the parent constructor of the servlet itself.

The next linex define a method doGet() and doPost() methods. The doGet() method acceps two parameters of type HttpServletRequest and HttpServletResposne interface, which are defined in the javax.servlet.http package and this method calls doPost() methods.

The doPost() method also accepts two parameter of type HttpServletRequest and HttpServletResponse and defines the response type in the first line of the method. To define a response type of servlet, a method of HttpServletResponse interface setContentType() is used.

The above servlet will create a Ms-Word document file as a response as follows:

response.setContentType(“application/msword”);

Next we call a method getWriter() of HttpServletResponse interface that returns PrintWriter class refrence.

PrintWriter out = response.getWriter();

The next lines calls a method println() or print() of PrintWriter class to write into the web page. WordServlet class calls print() method to write:

out.println("THis doc is generated by servlet");

And ExcelServlet class calls println() method to write a excel sheet, where /t is used to separate data into next column. Sum(c3:c3) will add data of 3 rows of third column in the excel sheet. In the end of the servlet, a method close() of PrintWriter class is called to close the write stream.

Listing 3: index.jsp file to visit Ms-Word and Ms-Excel Servlet

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Download Data</title>
</head>
<body>
View data in following format:<br>
<a href = "WordServlet">MS-Word</a><br>
<a href = "ExcelServlet">MS-Excel</a>
</body>
</html>

The above table code creates a html web page to create an user interface to visit Ms-Word and Ms-Excel sheets. Two anchor tags were used to create anchor tag url, that can visit the above defined servlets (WordServlet & ExcelServlet) respectively.

Shows an interface to visit Ms-Word and Ms-Excel servlet

Figure 1: Shows an interface to visit Ms-Word and Ms-Excel servlet

The above figure shows html interface that gives url to visit Ms-Word servlet and Ms-Excel servlet. Once we click on MS-Word, It loads WordServlet and prompts the user to download or open Ms-Word document. This document will contain the String “THis doc is generated by servlet” that was passed into the servlet using writer stream.

The next url MS-Excel that loads ExcelServlet and prompts the user to download or open Ms-Excel document using the appropriate application. This document will create three colums “Name”, “JobType” and “Salary”. This document save three records and the fourth row produces the total salary distributing to these three employees.

Visit ExcelServlet that prompt the user to download or open the excel sheet.

Figure 2: Visit ExcelServlet that prompt the user to download or open the excel sheet.

The above figure shows that a requesting url calls ExcelServlet servlet and downloads an excel file, while a client application receives response from the server, it ask the user to choose an action to be performed against the downloading excel file.

Shows the contents of downloaded excel sheet using ExcelServlet.

Figure 3: Shows the contents of downloaded excel sheet using ExcelServlet.

The above figure shows an excel sheet screen shot that was produced by the ExcelServlet.

Visit WordServlet that download the Ms-Word document file

Figure 4: Visit WordServlet that download the Ms-Word document file

The above figure shows a small window prompting the user to choose an action to open or save a Ms-Word file, while a url request is submitted to initialize WordServlet on the web server.

Shows the contents of downloaded Ms-Word document file using the WordServlet

Figure 5: Shows the contents of downloaded Ms-Word document file using the WordServlet

This is screen shot of the Ms-Word file downloaded from web server.

Required Jar Files:

Required Jar Files

Figure 6: Required Jar Files

Directory Structure:

Required Directory Structure to run a java web application

Figure 7: Required Directory Structure to run a java web application

Require Tools:

To create and run this web application, we need following listed applications:

  • JDK (Java Development Kit) should be installed on the system for java application development.
  • Eclipse IDE (Integrated Development Environment) can be used for this web application development.
  • Web Server or Application Server: To run java web applications, we are required to have an application server (Web Logic 12C) or a web server (Tomcat Apache).

I used an application server (Web Logic 12C) that uses 7001 as default port number to run java web applications.

Server Configured into Eclipse IDE for Application Server and Web Server

Figure 8: Server Configured into Eclipse IDE for Application Server and Web Server

Conclusion:

In this article, we learn:

  • How many types of responses can be produced using a servlet?
  • How do we process a multimedia response using a servlet to download a document file?


I am a software developer from India with hands on experience on java, html for over 5 years.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login