import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.net.*;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = (String) request.getParameter("file");
if (fileName == null || fileName.equals(""))
throw new ServletException(
"Invalid or non-existent file parameter in UrlServlet servlet.");
if (fileName.indexOf(".pdf") == -1)
fileName = fileName + ".pdf";
URL pdfDir = null;
URLConnection urlConn = null;
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try{
pdfDir = new URL(getServletContext().getInitParameter("remote-pdf-dir") + fileName);
} catch (MalformedURLException mue){
throw new ServletException(mue.getMessage());
}
try{
stream = response.getOutputStream();
response.setContentType("application/pdf");
response.addHeader(
"Content-Disposition","attachment; filename="+fileName );
urlConn = pdfDir.openConnection();
response.setContentLength( (int) urlConn.getContentLength() );
buf = new BufferedInputStream(urlConn.getInputStream());
int readBytes = 0;
while((readBytes = buf.read()) != -1)
stream.write(readBytes);
} catch (IOException ioe){
throw new ServletException(ioe.getMessage());
} finally {
if(stream != null)
stream.close();
if(buf != null)
buf.close();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<servlet><servlet-name>MyServletName</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping><servlet-name>MyServletName</servlet-name>
<url-pattern>/index.html</url-pattern>
</servlet-mapping>
</web-app>
Download: ServletDisplayPdfBaseonRequestParameter.zip( 90 k)