I want to display a pdf file in a new tab of the browser of client side.
I have created a servlet class in order to display the pdf File, I'm new in Java and i don't know how to use the class I've crerated, and if the class is right.
I work with Java on windows with Tomcat.
The servlet code:
public class DisplayPdf extends HttpServlet implements Servlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,
IOException {
processRequest(request, response);
}
private void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException,
IOException {
File file = new File("test.pdf");
InputStream inputStream = getServletContext().getResourceAsStream("/WEB-INF/resources/test.pdf");
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
}
}
How can I call this servlet and use it from the Java Webapp?
This has actually nothing (or just very little) to do with servlets nor any other server-side technology, opening new window/tab or save dialog is fully in browser's competence. All you can do server-side is to set proper HTTP headers to your response, eg
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename=\"My.pdf\"");
The inline
part of the Content-Disposition
header tells browser, that it can display the file inline, if it is able to, attachment
would force download.
You can force opening new tab/window from the HTML, where the file is linked, using eg
<a href="#" onclick="window.open('My.pdf', '_blank', 'fullscreen=yes'); return false;">My PDF</a>
See window.open() documentation for more details.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.