This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Calling servlet from JSP

 
Deepak Chawla
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a JSP Page whcih display files, i want that when i click on the files, it should dispaly in its format, for example if it is word doc, it should open in word document.
I don't know if i am passing servlet in JSP correctly.
for(int i =0;i<filesdisplay;i++)
{
out.write( "<a href='docs/servlet/viewAttachment" + filenames[i] + "'>" + filenames[i] + "</a>" );
}
This is my viewAttachment servlet
package servlet;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class viewAttachment extends HttpServlet
{

public void doGet (HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
{
ResourceBundle rb = ResourceBundle.getBundle("Project");
String rootdir = rb.getString("projectDocRootDirectory");
String uri = request.getRequestURI();
int slash = uri.lastIndexOf("/docs/") + 6;
int dot = uri.lastIndexOf('.') + 1;
String fpath = uri.substring(slash);
String ftype = uri.substring(dot);
String fullpath = rootdir + fpath;
String ctype = "text/plain";

if ( ftype.equals("html") )
{
ctype = "text/html";
}
else if ( ftype.equals("xml") )
{
ctype = "text/xml";
}
else if ( ftype.equals("ppt") )
{
ctype = "application/ppt";
}
else if ( ftype.equals("xls") )
{
ctype = "application/xls";
}
else if ( ftype.equals("doc") )
{
ctype = "application/doc";
}
else if ( ftype.equals("pdf") )
{
ctype = "application/pdf";
}

response.setContentType( ctype );
FileInputStream fis = new FileInputStream(fullpath);
ServletOutputStream out = response.getOutputStream();
for( int c=fis.read(); c > -1; c=fis.read() )
{
out.write(c);
}

}

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

}
 
Tim Baker
Ranch Hand
Posts: 541
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why not do:
out.write( "<a href='docs/servlet/viewAttachment?file=" + filenames[i] + "'>" + filenames[i] + "</a>" );
.....
String fpath = request.getParameter("file");
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic