I have to implement a download module wherein I have to give only registered users the requested files.

James Johnson



Kishore, try this servlet:

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;

* Serves a file from the disk.
public class FileServerServlet extends HttpServlet
* Receives and responds to requests.
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
String error = null;
HttpSession ses = null;
String company = DoAuthorizaton(req);

if (company != null)
InputStream fis = null;
OutputStream out = res.getOutputStream();
String filename = req.getParameter("filename");
res.setHeader("Content-Disposition", "attachment; filename=" + filename);

String filepath = "c:webfiles";
filename = filepath + filename;
fis = new BufferedInputStream(
new FileInputStream(filename));

byte[] buffer = new byte[1024];
int bytes = -1;
while ((bytes = fis.read(buffer, 0, buffer.length)) != -1)
out.write(buffer, 0, bytes);

if(error != null)
PrintWriter out = res.getWriter();

out.println("File cannot be served at the moment:");
" + error);


private String DoAuthorizaton(HttpServletRequest req)
HttpSession session = req.getSession(false);
if(session != null)
String company = (String) session.getAttribute("company");
return company;
return null;

Name this file some servlet name like: "fileServer"

you can link to a jsp page (with the link text as the file name) that checks for a session like: checkSession.jsp?filename=file.txt

then if the session is there, forward the request onto the servlet with the file name like: fileServer?filename=file.txt&session=ok

modify the "c:webfiles" directory in the code to reflect your file storage directory on your hard drive.

Hope this helps...