Tag Cloud

Showing posts with label servlet. Show all posts
Showing posts with label servlet. Show all posts

Saturday, December 15, 2012

Create servlet to serving Download


This tutorial shows how to create a link button on web for "Download". You will need have a servlet on the server side to provide this feature. In the end of this tutorial you will have a download link to download a text file.

Create a servlet

public class DownloadServlet extends HttpServlet {

 

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

    PrintWriter out = response.getWriter();

    // Set the response content type

    response.setContentType("text/plain"); // for text file

 

    response.addHeader("Content-disposition","attachment; filename=yourfilename.txt");

 

    out.print("HELLO");

    out.close();

 

 }

 

}

Register servlet in web.xml

<web-app>

 

   <servlet>

      <servlet-name>DownloadServlet</servlet-name>

      <servlet-class>com.mycompany.DownloadServlet</servlet-class>

   </servlet>

 

<servlet-mapping>

      <servlet-name>DownloadServlet</servlet-name>

      <url-pattern>/download</url-pattern>

   </servlet-mapping>

</web-app>

Create HTML page

<a href="download">Go to download</a>