Set browser title in servlet which serves a PDF fi

2020-07-17 08:19发布

问题:

This question already has answers here:
Closed 7 years ago.

Possible Duplicate:
How to change the title of a browser page which a servlet streamed a PDF to?

I want to display a PDF file in browser, so I send the PDF to response output stream. I set headers:

response.setHeader("Content-Disposition", "inline; filename=\"" + getFileName() + "\"");

But I have problem with browser title. FireFox display servlet title.

回答1:

The request URL as appears in browser's address bar must contain the PDF filename in order to get it to work the way you want. This is easier if you map the PDF servlet on a prefix URL pattern something like as /pdf/* instead of a static path something like as /pdf so that it can also be invoked on /pdf/blahblah, /pdf/foo.ext and so on.

E.g.

<a href="pdf/filename.pdf">

in combination with

@WebServlet("/pdf/*")
public class PdfServlet extends HttpServlet {

    @Override
    public void doGet(...) {
        String filename = request.getPathInfo().substring(1); // filename.pdf
        // ...
    }

}

Additional advantage is that the Save As filename in IE browser will also be fixed. That browser namely extracts it from the last path of the request URL instead of from the content disposition header.



回答2:

If you need to set the title for generated HTML Page :-

Try This :

out.println("  <HEAD><TITLE>Your Title for browser</TITLE></HEAD>");

Use this in servlet. Then servlet will generate the dynamic page, the above code will add the title to page.