Download servlet

Hi!
I'm building a servet to download files from a database. It works fine when you choose save in the IE dialog, but of you choose open you get an error message: File not found...
Here is my code (at least part of it):
OutputStream os = response.getOutputStream();
response.setContentType(file.getMimeType() + "; name=\"" + file.getName() + "\"");
response.setContentLength((int)file.getSize());
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
os.write(file.getContent());
os.close();Does anyone know how to fix this?
Thanks,
// Magnus

First of all, don't close the output stream. If you close the stream, how is IE supposed to read from it? Secondly, I wouldn't use os.write(file.getContent()). I recently wrote a downloadservlet for my organization. It downloads excel spreadsheets and works very well with the browser. It takes BLOBS from an oracle database. This is where the spreadsheets are saved.
package com.wellsfargo.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
* Servlet Class
* @web.servlet name="XLDownload" display-name="Name for XLDownload"
*              description="Description for XLDownload"
* @web.servlet-mapping url-pattern="/XLDownload"
* @web.servlet-init-param name="A parameter" value="A value"
public class XLDownloadServlet extends HttpServlet {
     protected void doGet(HttpServletRequest req, HttpServletResponse resp)
               throws ServletException, IOException {
          // TODO Auto-generated method stub
          doPost(req, resp);
     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
               throws ServletException, IOException {
          ServletOutputStream os = null;
          Connection conn = null;
          PreparedStatement pstmt = null;
          String forwardPage = req.getParameter("forwardPage");
          try {
               String selectedDeal = req.getParameter("selectedDeal");
               // Set the content header information
               String contentDisposition = "attachment; filename=";
               // Connection to database
               conn = DBHelper.getConnection();
               // Query to get the data content
               String sql = "select * from redd.t_clpr_attachment where attachmentname = ?";
               pstmt = conn.prepareStatement(sql);
               pstmt.setString(1, selectedDeal);
               ResultSet rs = pstmt.executeQuery();
               if (rs.next()) {
                    Blob blob = rs.getBlob("attachmentdata");
                    String mimetype = rs.getString("mimetype");
                    System.out.println("found " + selectedDeal + " type "
                              + mimetype);
                    String filename = selectedDeal + ".xls";
                    int length = contentDisposition.length() + filename.length();
                    StringBuffer sb = new StringBuffer(length);
                    sb.append(contentDisposition).append(filename);
                    resp.setContentType(mimetype);
                    resp.setHeader("Content-Disposition", sb.toString());
                    InputStream in = blob.getBinaryStream();
                    os = resp.getOutputStream();
                    byte by[] = new byte[32768];
                    int index = in.read(by, 0, 32768);
                    while (index != -1) {
                         os.write(by, 0, index);
                         index = in.read(by, 0, 32768);
                    os.flush();
               } else {
                    System.out.println(selectedDeal + " does not exist");
          } catch (Exception e) {
               System.out.println(e.toString());
          } finally {
               if (os != null)
                    os.close();
               if (pstmt != null)
                    try {
                         pstmt.close();
                    } catch (Exception e) {
               if (conn != null)
                    try {
                         conn.close();
                    } catch (Exception e) {
               RequestDispatcher dispatcher = getServletContext()
                         .getRequestDispatcher(forwardPage);
               dispatcher.forward(req, resp);
}

Similar Messages

  • Getting  save as dialog while downloading using download servlet

    Hi Folks,
    I am developing a web based video download application.In this i intend to download the video file by calling a download servlet.
    Though the application works ,that is it downloads the file, the video file is straight away being played by the media player.My objective is to save it in the client machine at the desired location of the hard disk and then play the same later at cient's convenience. This is not happenening with my application.
    Pl suggest me as how to get the save as dialog box to save the video file at will.
    The site is to be lauched in a weeks time.Pl help!!!
    thanks and regards
    sathiyam K G

    Hi rupak,
    Thanks for the tip.I actually did all the things u said.But the difference is that i rely on http download.
    I mean i do not use the servlet output stream to download the video file.If i do so it takes about 20 mins for a 10 MB sample file,to be downloaded via a broad band T1 link.
    So i just use href to depend on http by which the download speed is accelerated and my one clip of video of 100MB average size can be downloaded in about 15 min. duration.
    If this is not the correct way of working for the video download will u pl suggest me any other way through servlet, i can download with the above specified speed.
    i am clear if i use the servlet output stream the download process is deadly slow.
    so pl suggest!!
    thanks again
    regards
    sathiyam K G

  • Need urgent help on file download servlet problem in Internet Explore

    I have trouble to make my download servlet work in Internet Explore. I have gone through all the previous postings and done some research on the internet, but still can't figure out the solution. <br>
    I have a jsp page called "download.jsp" which contains a URL to download a file from the server, and I wrote a servlet (called DownloadServlet) to look up the corresponding file from the database based on the URL and write the file to the HTTP output to send it back to the browser. <br>
    the URL in download.jsp is coded like <a href="/download/<%= currentDoc.doc_id %>/<%= currentDoc.name %>">on the browser, it will be sth like , the number 87 is my internal unique number for a file, and "myfile.doc" is the real document name. <br>
    in my web.xml, "/download/" is mapped to DownloadServlet <br>
    the downloadServlet.java looks like
    tem_name = ... //read DB for file name
    // set content type
    if ( tmp_name.endsWith(".doc")) {
    response.setContentType("application/msword");
    else if ( tmp_name.endsWith(".pdf")){
    response.setContentType("application/pdf");
    else if ( tmp_name.endsWith(".ppt")){
    response.setContentType("application/vnd.ms-powerpoint");
    else if ( tmp_name.endsWith(".xls")){
    response.setContentType("application/vnd.ms-excel");
    else {
    response.setContentType("application/download");
    // set HTTP header
    response.setHeader("Content-Disposition",
    "attachment; filename=\""+tmp_name+"\"");
    OutputStream os = response.getOutputStream();
    //read local file and write back to browser
    int i;
    while ((i = is.read()) != -1) {
    os.write (i);
    os.flush();
    Everything works fine in Netscape 7.0, when I click on the link, Netscape prompts me to choose "open using Word" or "save this file to disk". That's exactly the behavior I want. <br>
    However in IE 5.50, the behavior is VERY STRANGE.
    First, when I click on the URL, the popup window asks me to "open the file from its current location" or "save the file to disk". It also says "You have chosen to download a file from this location, ...(some url).. from localhost"
    (1) If I choose "save the file to disk", it will save the rendered "download.jsp" (ie, the currect page with URL I just clicked, which isn't what I want).
    (2)But if I choose "open the file from its current location", the 2nd popup window replaces the 1st, which also has the "Open ..." and "Save.." options, but it says "You have chosen to download a file from this location, MYFILE.doc from localhost". (notice it shows the correct file name now)
    (3) If I choose "Save..." on the 2nd window, IE will save the correct file which is "myfile.doc"; if I choose "Open ...", a 3rd replaces the 2nd window, and they look the same, and when I choose "Open..." on the 3rd window, IE will use Word to open it.
    any ideas?
    </a>

    Did you find a solution to this problem? I've been wrestling with the same issues for the past six months. Nothing I try seems to work. I've tried setting the contentLength(), inline vs. attachments, different write algorythms, etc. I don't get the suggestion to rename the servlet to a pdf file.

  • Problem in Download Servlet (Urgent)

    Hai
    i am using an servlet to download files.
    i am facing an problem with that servlet.While downloading, at times it strucks at 290k or 330k.
    Note : Acually i am calling this servlet from a popup window.The popup window closes automatically after one minute irrescpective of the download progress.At times i noticed that the download strucks while the popup closes, whether is causes the problem of strucking.
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Download extends HttpServlet {
    HttpSession session =null;
    File F;
    BufferedInputStream fif;
    ServletOutputStream stream;
    public void init(){
    F=null;
    fif=null;
    stream =null;
    public void doGet(HttpServletRequest request ,HttpServletResponse response) {
    try{
         // Setting Buffer size
    response.setBufferSize(50000);
                   // Setting Content Type
    response.setContentType("application/x-filler");
    int buffersize;
    String cfile="";
    boolean flag=false;
    session = request.getSession(true);
                   //Receiving variables
    String fileName= request.getParameter("filename");
    String filePath = request.getParameter("filepath");
    String downloadFile = filePath + fileName;
    F=new File(downloadFile);
    String download_date = "sysdate";
    String file=F.getName();
    buffersize=(int)F.length();
    byte b[]=new byte[buffersize];
         //Servet output stream to download file
    stream = response.getOutputStream();
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file + "\";");
    int data;
    fif = new BufferedInputStream(new FileInputStream(F));
    //writing data to output stream
    while((data = fif.read()) != -1) {
    stream.write(data);
                   //closing objects
    fif.close();
    stream.close();
    F.delete();
    }catch(java.net.SocketException se){
    System.out.println("SocketException " +se);
    catch(IOException io){
    System.out.println("IOException " + io);
    catch(Exception e){
    System.out.println("Exception " +e);      
    }

    I guess your closing of the window is your problem. Your servlet looks just fine to me.
    Try calling this servlet from a browser and see if it still stops..

  • Working Sample Code: File Download Servlet

    Pardon the cross-posting (Java Servlet Technology), but when I was researching this problem I found alot of people asking this question in here as well as in the servlet forum. So I thought this code would be helpful here too.
    Here is a complete working servlet for downloading virtually any type of file to a browser.
    It uses a file called application.properties to specify the location of the folder where the files to be downloaded reside. Of course you could modify this to allow the users to select the location as well.
    A sample URL to call the Servlet would look like this:
    http://localhost/website/servlet/DownloadAssistant?YourFileName.ext
    I tested this with varying filenames. It did have some issues if the file contained special characters like # symbol. This should be manageable however.
    Hope someone finds this useful.
    import java.io.*;
    import java.util.*;
    import java.net.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.zip.GZIPOutputStream;
    public class DownloadAssistant extends HttpServlet
    private static final String DIR = "dir";
    private String separator;
    private String root;
    public DownloadAssistant()
    Properties propFile = null;
    FileInputStream in = null;
    String JAVA_HOME = "C:\\jrun\\servers\\default\\filetest\\application.properties";
    // Get a handle on the peoperties file
    try{
    in = new FileInputStream(JAVA_HOME);
    propFile = new Properties();
    propFile.load(in);
    catch (IOException ignore){}
    separator = "/";
    // Get the directory from the application.properties file
    // e.g. C:\\Temp\\Files\\
    root = propFile.getProperty("app.directory");
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    processRequest(request, response);
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    processRequest(request, response);
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    PrintWriter out = null;
    ServletOutputStream stream = null;
    GZIPOutputStream zipstream = null;
    Object obj = null;
    String s = "";
    //determine if there is a filename appended to the url
    // If so, then decode it
    s = HttpUtils.getRequestURL(request).toString();
    int i;
    if((i = s.indexOf("?")) > 0)
    s = s.substring(0, i);
    String s1;
    if((s1 = request.getQueryString()) == null)
    s1 = "";
    else
    //s1 = decode(s1);
    s1 = URLDecoder.decode(s1);
    // No filename, so set contentType and generate error message
    if(s1.length() == 0)
    response.setContentType("text/html");
    out = response.getWriter();
    out.println("<html>");
    out.println("<p>Could not get file name ");
    out.println("</html>");
    out.flush();
    out.close();
    return;
    // Restriction while gaining access to the file
    if(s1.indexOf(".." + separator) > 0)
    response.setContentType("text/html");
    out = response.getWriter();
    out.println("<html>");
    out.println("<br><br><br>Restrictions on filename");
    out.println("</html>");
    out.flush();
    out.close();
    return;
    // Try to get a handle on the file
    File file = new File(root + s1);
    // Couldn't get the file, return an error message
    if(file == null)
    response.setContentType("text/html");
    out = response.getWriter();
    out.println("<html>");
    out.println("<p>Could not read file: " + s1);
    out.println("</html>");
    out.flush();
    out.close();
    return;
    // Either the file doesn't exist or it can't be read, return an error message
    if(!file.exists() || !file.canRead())
    response.setContentType("text/html");
    out = response.getWriter();
    out.println("<html><font face=\"Arial\" size=\"+1\">");
    out.println("<p>Could not read file " + s1);
    out.print("<br>Reasons are: ");
    if(!file.exists())
    out.println("file does not exist");
    else
    out.println("file is not readable at this moment");
    out.println("</font></html>");
    out.flush();
    out.close();
    return;
    // Looks like we can read/access the file, determine its type
    String s2 = request.getHeader("Accept-Encoding");
    // Is this a zip file?
    boolean flag = false;
    if(s2 != null && s2.indexOf("gzip") >= 0)
    flag = true;
    flag = false;
    if(flag)
    response.setHeader("Content-Encoding", "gzip");
    response.setHeader("Content-disposition", "attachment;filename=" + s1);
    stream = response.getOutputStream();
    zipstream = new GZIPOutputStream(stream);
    downloadFile(root + s1, zipstream);
    zipstream.close();
    stream.close();
    // It's not a zip file so treat it as any other file
    else
    response.setContentType("application/force-download");
    response.setHeader("Content-disposition", "attachment;filename=" + s1);
    stream = response.getOutputStream();
    downloadFile(root + s1, stream);
    stream.flush();
    stream.close();
    }// end processRequest()
    // This method downloads the file to the browser
    private void downloadFile(String s, OutputStream outstream)
    String s1 = s;
    byte abyte0[] = new byte[4096];
    try
    BufferedInputStream instream = new BufferedInputStream(new FileInputStream(s1));
    int i;
    while((i = instream.read(abyte0, 0, 4096)) != -1)
    outstream.write(abyte0, 0, i);
    instream.close();
    catch(Exception _ex) { }
    }//end downloadFile()
    public void init(ServletConfig servletconfig)
    throws ServletException
    super.init(servletconfig);
    String s;
    if((s = getInitParameter("dir")) == null)
    s = root;
    separator = System.getProperty("file.separator");
    if(!s.endsWith(separator))
    s = s + separator;
    root = s;
    }//end init()
    }//end servlet()

    Yes - it is useful

  • Performance issues in file download servlet

            FileInputStream in = null;
            ServletOutputStream sos = res.getOutputStream();
              File f = new File(path);
              if(f.exists())  {
                in = new FileInputStream(f);
                int length = (int)f.length();
                byte[] input = new byte[length];
                res.setContentType ("application/octet-stream");
                res.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");
                res.setContentLength(length);
                if(length != 0) {
                  while ((in != null) && ((length = in.read(input)) != -1))  {   // read
                    sos.write(input,0, input.length);   // write
              }Hi experts, the above is a block of code that sends a file to a client machine through servlet. One problem I am having now is that it frequently cause the server to run out of memory. Is it because of the way I read the FileInputStream is not efficient?
                byte[] input = new byte[length];
                if(length != 0) {
                  while ((in != null) && ((length = in.read(input)) != -1))  {   // read
                    sos.write(input,0, input.length);   // write
                  }It seems that my code reads an entire file into memory before it writes anything to the client, so when there are many people downloading files, the server will run out of memory. Is it true?
    I am not very familiar with the read() and write() methods in the inputstream and output stream classes. So I hope someone here can tell me whether the above code is indeed the cause of the problem. If not, then I can troubleshoot my other servlets and JSPs.
    Thanks!

    try not to create a byte[] with the file size
    try to make it a fix one
    e.g.new byte[1024]
    treat it as a package to sendThanks. But is 1024 too small a size for sending files throught the internet? What is the best size to used?

  • Download servlet from external server

    I write a download file servlet. It should download files from external ftp and make the save as dialog window save it with proper extension.
    It gets 3 parametes:
    http://10.60.1.1:8080/sd-sp45/DownloadServlet?fileName=55555.doc&filePath=000/000/000/000/000/000/010/002/8c8/f07/57/00000000-0000-0000-0001-00028c8f076e&fileType=doc
    fileName - original file name;
    filePath - path and file name on ftp server;
    fileType - file type;
    I get an error IOException : java.oi.FileNotFoundException :
    ftp:\sdattach:[email protected]\sdftp\Servicecall\000\000\000/000\000/000/010\002\8c8\f07\57\00000000-0000-0000-0001-00028c8f076e (The file name, diroctory name, or volume label syntax is incorrect)
    I'm not sure if I can use here File class (maybe some network stuff)
    Besides, what shoud I change here :
    response.setContentType("application/octet-stream");
    response.setContentLength((int)F.length());
    response.setHeader("Content-Disposition","attachment;filename="+file);
    to save file with the extension i need?
    Thank you for help
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.net.*;
    public class DownloadServlet extends HttpServlet {
        File F;
        BufferedInputStream fif;
        ServletOutputStream stream;
        public void init(){
            F=null;
            fif=null;
            stream =null;
        public void doGet(HttpServletRequest request ,HttpServletResponse response) {
            try{
                try{
                // Setting Buffer size
                response.setBufferSize(50000);
                int buffersize;
                String filePath="";
                String fileName="";
                String fileType="";
                //Receiving variables
                fileName=request.getParameter("fileName");
                filePath = request.getParameter("filePath");
                fileType = request.getParameter("fileType");
                System.out.println("========New compile==");
                System.out.println(fileName);
                System.out.println(filePath);
                System.out.println(fileType);
                String downloadFile = "ftp://sdattach:[email protected]/sdftp/Servicecall/" + filePath;
                F=new File(downloadFile);
                String file=F.getName();
                buffersize= 10248;
                byte b[]=new byte[buffersize];
                // Setting Content Type
                response.setContentType("application/octet-stream");
                response.setContentLength((int)F.length());
                response.setHeader("Content-Disposition","attachment;filename="+file);
                stream = response.getOutputStream();
                fif = new BufferedInputStream(new FileInputStream(F));
                //writing data to output stream
                int count=fif.read(b,0,buffersize);
                while(count!=-1){
                stream.write(b,0,count);
                count=fif.read(b,0,buffersize);
                //closing objects
                fif.close();
                stream.flush();
                stream.close();
                F.delete();
                }catch(SocketException se){
                System.out.println("SocketException " +se);
                catch(IOException io){
                System.out.println("IOException " + io);
                catch(Exception e){
                System.out.println("Exception " +e);
            }catch(Exception e){ System.out.println("Exception " +e); }
    }

    assuming the filepath is absolutely correct, try doing this:
    String downloadFile = "ftp://sdattach:[email protected]/sdftp/Servicecall/" + filePath;
    response.setHeader("Content-Disposition","attachment;filename=\""+downloadFile+ "\"");

  • Download Servlet OutOfMemory

    Hi all
    I have a servlet which generates a PDF (via jasper reports) for the user to download. After a couple of hours this servlet starts generating outofmemory errors. The pdfs that are generated are relatively small , average 3 pages. The server is started with sufficient memory (-Xms512m -Xmx1024m)
    Server : tomcat 5.5.9
    jdk : 1.5.0
    The code that writes the bytes to the response is :
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
    response.setContentType("application/octet-stream");
    response.setContentLength(bytes.length);
    ServletOutputStream ouputStream = response.getOutputStream();
    ouputStream.write(bytes, 0, bytes.length);
    ouputStream.flush();
    ouputStream.close();The error is :
    - Servlet.service() for servlet PDFServlet threw exception
    java.lang.OutOfMemoryError: PermGen space
    Has anyone seen this error and now what could be causing it ??
    Thanks

    There are memory profilers out there that could help you JProbe for instance, altho i'm not sure what free ones are available. If you are wild guessing, you could try loading jasper reports using a custom class loader and tossing the loader each time so that all of jasper is tossed as well.

  • A Download servlet: non-ASCII characters not working

    This is my servlet used for file download:
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
      String filepath = request.getParameter("filepath");
      String filename = request.getParameter("filename");
      response.setContentType("application/zip");
      response.setHeader("Content-Disposition", "attachment;filename=\""+filename+"\";");
      ServletOutputStream sos = null;
      BufferedInputStream bis = null;
      try {
        sos = response.getOutputStream();
        bis = new BufferedInputStream(new FileInputStream(source));
        byte buffer[] = new byte[2048];
        int c;
        while((c = bis.read(buffer)) != -1)
          sos.write(buffer, 0, c);
      } catch(Exception e) {
      } finally {
        bis.close();
        sos.close();
    }It does not work when the filename contains non-ASCII characters (e.g., extended ASCII, CJK ...)
    What do I fix this? Thanks!

    One possiblitiy that occurs to me is you have too many encoding things going on and you are sorta "over-encoding" things, as it were....
    All I can think to do is give you this sample JSP page that I created when I was trying to figure all this web encoding stuff with forms back in the day. So perhaps you can use this as a basis for your own page.
    // _lang.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>
    <head>
         <title></title>
         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body bgcolor="#ffffff" background="" text="#000000" link="#ff0000" vlink="#800000" alink="#ff00ff">
    <%
    request.setCharacterEncoding("UTF-8");
    String str = "\u7528\u6237\u540d";
    String name = request.getParameter("name");
    %>
    req enc: <%= request.getCharacterEncoding() %><br />
    rsp enc: <%= response.getCharacterEncoding() %><br />
    str: <%= str %><br />
    name: <%= name %><br />
    <br />
    <a href="_lang.jsp?name=<%= java.net.URLEncoder.encode(str, "UTF-8") %>">as link</a>
    <br />
    <br />
    <form method="GET" action="_lang.jsp" encoding="UTF-8">
    Name: <input type="text" name="name" value="" >
    <input type="submit" name="submit" value="GET Submit" />
    </form>
    <form method="POST" action="_lang.jsp" encoding="UTF-8">
    Name: <input type="text" name="name" value="" >
    <input type="submit" name="submit" value="POST Submit" />
    </form>
    </body>
    </html>

  • Download Servlet throwing Out Of Memory Exception

    I am trying to download file of more than 500 mb through servlet but getting out of memory exception .
    Before downloading i am zipping that huge file .
    try {
         String zipFileName = doZip(file);
          file =null;
          System.gc();
          File inputFile = new File(zipFileName);
          InputStream fileToDownload = new FileInputStream(
                                            inputFile);
           response.setContentType("application/zip");
         response.setHeader("Content-Disposition","attachment; filename=\""
                                                      + fileName.replaceAll("tmx", "zip")
                                                                .concat("\""));
         response.setContentLength(fileToDownload.available());
         byte buf[] = new byte[BUF_SIZE];
         int read;
         while ((read = fileToDownload.read(buf)) != -1) {
                   outs.write(buf, 0, read);
              fileToDownload.close();
                   outs.flush();
                                  outs.close();
    }catch(Exception e ) {
      //Getting out of memory.
    }Please suggest solution for this .

    cotton.m wrote:
    My zip suggestion was as follows.
    Take the file. Do not set the Content length header. Do set the Content encoding header to gzip. Create a GZIP output stream using the servlet output stream. Read the unzipped file in and output it through the gzip output stream.
    This cuts out one full cycle of file reading and writing from what you are doing currently.Thanks for u r reply
    InputStream fileToDownload = new FileInputStream(
                                            file);
    response.setContentType("application/gzip");
    response.setHeader("Transfer-Encoding", "chunked");
    response.setContentLength((int) file.length());
    GZIPOutputStream gzipoutputstream = new GZIPOutputStream(outs);
    byte buf[] = new byte[BUF_SIZE];
    int read;
    while ((read = fileToDownload.read(buf)) != -1) {
         gzipoutputstream.write(buf, 0, read);
    fileToDownload.close();
    outs.flush();
    outs.close();I made changes accordingly . Please provide u r view on this .

  • Where from can i download "servlet.jar"

    Hi Friends,
    I've JDk1.5 and Tomcat installed on my system,I am going through some servlet tutorials and i need to run them.So,i guess i need to have servlet.jar file in my classpath.Can someone tell me where from can i install that?I have this link
    www.java.sun.com/products/servlet/index.html
    But,I dont want the whole J2EE download,i just need a customized installation or just this file.Please help.

    hey kefgolfs,
    Thanks ...that helped me too...That was written over two years ago. Thanks for resurrecting it.

  • From Where should i download Servlets and how to set Environment variables?

    Hi,
    I want to download the Servlets Kit for my development of application,but couldnt find it.I found a zip file containing all class files.If that is the correct one,then how should i set my environment variables?
    thanks
    rao

    Your files should come in a folder with the name "Javax" and subfolders right?
    What you can do is to paste the file "Javax" in your folder of your JDK installation.
    For example, I have installed my JDK in C:\Java\jdk1.3
    I added one new folder in C:\Java\jdk1.3 called classes.
    Then I would put the Javax folder in classes.
    PS : We add one new folder called classes so that in future when you want to add new classes you can just into this folder.
    Then in your enviroment settings, simple point to C:\Java\jdk1.3\classes;.;
    This works for me. Hopefully you will no problems!
    jing
    170902

  • How to download servlet package source code

    In servlet interface package.there is some implement class,Iwant to see the source code.
    Thanks for answer!

    You are not suppose to see the source code without prior permission from the vendor.
    If your question is about decompiling the java class, you can use jad (or ant other java decompilers). You can give a search in Google for java decompilers.
    By the way, why do you want to see the implementation class?
    Sudha

  • Call HTTPServlet in Struts Application (Or Download Servlet)

    I have a struts application. I need to call an application that will create a file and then allow the client to open or save it (by writing the file into the response).
    Can this be done with a struts action servlet or do I need to use a standard http servlet? If I need to use a standard http servlet how do I create a standard html link to that servlet in my html?
    I have placed a servlet tag in the web.xml giving the standard http servlet a servlet-name of downloaddocument.
    Any help is appreciated,
    Thanks,
    DeltaCoder

    Yes. And don't cross-post.
    http://forum.java.sun.com/thread.jspa?threadID=628983&tstart=0
    - Saish

  • PDF Download From Servlet

    Hi guys,
    I'm having issues creating a file download servlet to download pdf files. I can successfully download text files using this code. For some reason however I cannot download a pdf using the same code. On execution, the browser will present me with a dialogue box asking me to open, save or cancel. If i open or save and open later I get an error message saying that the pdf file is corrupt or damaged and won't open properly. I have tried opening the original pdf on the server and there are no problems there. I have absolutely no idea why this is happening. Can someone point me in the right direction please.
         request.setAttribute("message", "This is a warning");
              String urlString = "test.jsp";
              DataInputStream dataInputStream=null;
              ServletOutputStream out = response.getOutputStream();
              String filePath = "/files";
              String originalFilename="test.pdf";
              File f = new File(originalFilename);
              response.setContentType("application/pdf");
              response.setContentLength((int) f.length());
              response.setHeader( "Content-Disposition", "attachment; filename=" +originalFilename );
              try{
                   dataInputStream = new DataInputStream(new FileInputStream(filePath+originalFilename));
                   byte[] bbuf = new byte[1024];
                   dataInputStream.read() method
                   while (dataInputStream.read(bbuf) != -1){
                        out.write(bbuf);
              } catch(IOException e){
                   e.printStackTrace();
              } finally{
                   dataInputStream.close();
                   out.flush();
                   out.close();
         }                   Thank You

    Try this
    in this scenario i'm reading file from databsae (Object type in SQLServer) as bytes
    String path=getServletContext().getRealPath("/");
                   byte[] buf = new byte[3 * 1024 * 1024];
                   HashMap fileInfo=new HashMap();
              System.out.println("servlet called----> "+path);
              //String fileName=(String)arg0.getSession().getAttribute("fileName");
              int id=Integer.parseInt(arg0.getParameter("id"));
              String pageName=(String)arg0.getParameter("pageName");
              TrainingDBImpl dbImpl= new TrainingDBImpl();
              if(pageName.equals("Employee")){
                   fileInfo=dbImpl.getEmpFile(id);     
              }else if(pageName.equals("Courses")){
                   fileInfo=dbImpl.getFile(id);
              //fileInfo=dbImpl.getFile(id);
              //fileInfo=dbImpl.getEmpFile(id);
              String fileName=fileInfo.get("FileName").toString();
              buf=(byte[])fileInfo.get("EmployeeFile");
    response.setHeader("Content-Disposition","attachment;filename=\""+fileName+"\"");
    OutputStream out = response.getOutputStream();
              ByteArrayInputStream bain=new ByteArrayInputStream(buf);
         BufferedInputStream bIn = new BufferedInputStream(bain);
         int bytesRead;
         while ((bytesRead = bIn.read(buf)) != -1) {
         out.write(buf, 0, bytesRead);
         out.flush();
         bIn.close();
         out.close();

Maybe you are looking for

  • Delete only itemno from sales order

    Dear all,    By using this bapi BAPI_SALESORDER_CREATEFROMDAT2 i created the sales order.And i  updated the sales order.When i am deleting the item the whole sales order is deleting.How should i delete only item no in sales order.                    

  • Tween class question

    I'm learning 3.0 and have a movieclip that I want to fade in on the stage. once the clip finishes the fade tween I want to move the clip to the top of the stage using the x y. I know hwo to do this with a button but need to know how to add the code t

  • Traffic/Service configuration for ISG

    Need help in configuration so that the following requirements should be met: A set of target IP Addresses to be excluded in the traffic defined for a service (access to those IPs should be allowed, only that the traffic should not be qualified under

  • Deletion of Data From PSA in BI 7.0

    Hi All, my req is tht we are using Full Load info package from DBconnect ..now i want to delete the data from the PSA of the datasource whenever we schedule the info package so that there is only one request in the PSA. i want to achive this using pr

  • Photoshop Plugin Support - PLEASE

    I find myself exporting images to TIFF and then loading them into Photoshop to use 3rd party Noise reduction and then Photoshops Smart Sharpen tool, the Noise reduction and sharpening tools in Lightroom are USELESS, and I am sorry to say this as I lo