Pin It

How to write a Servlet code to download a Jar or file from the Server at a specified location ?.

A simple application demonstrating how to write a Servlet code to download a Jar or file from the Server at a specified location.

1. A simple html file for sending a get request to server for the Jar/file.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Download Jar</title>

 <h2>Download Page !!!!</h2>

 <a href="DownloadJarServlet">Download Jar</a>


2. Servlet code for downloading a Jar/file to a specified location on client's machine.

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

public class DownloadJar extends HttpServlet {

 private static final long serialVersionUID = 1L;

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

  // 1. Helping the browser to understand that it is 
  // a jar file not an html content.
  // Inorder to pass this information in response
  // we set the content type as "application/jar" 
  // by calling setContentType() method in response object 

  // 2. Getting the ServletContext object by calling
  // getServletContext() method from the current servlet object  
  ServletContext ctx = getServletContext();

  // 3. From ServletContext object we are calling getResourceAsStream()
  // which returns the resource located at the named path as an InputStream object. 
  // The data in the InputStream can be of any type or length. 
  // This method returns null if no resource exists at the specified path.
  // here we are passing the jar name present in the server at the relative path 
  InputStream is =  ctx.getResourceAsStream("/mail.jar");

  int read = 0;

  byte[] noOfBytes = new byte[1024];

  // 4. Getting the outputstream from the response object to write 
  // contents of jar to browser
  OutputStream os = response.getOutputStream();

  // 5. Reading the contents of jar in bytes using the inputstream created above
  // and writing it to the browser through outputstream created above.
  while((read = != -1 ){
   os.write(noOfBytes, 0 , read);




(Output) Running Download.html :

(Output) On clicking the "Download Jar" link we get the download file pop-up (Save as to specified location)

Please Give Us Your 1 Minute In Sharing This Post!
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
© 2012 Learn Java by Examples Template by Hubber Spot