RequestDispatcher.forward to a media file?

2019-07-03 16:04发布

问题:

I recently had an issue to resolve and found a solution, but that solution could potentially be greatly simplified if I could somehow use RequestDispatcher.forward to forward a request to a media URL.

From the docs, it says that it only supports servlet, JSP file, or HTML file. I tried with a media URL anyway and it did not complain, however it's not returning the correct headers (e.g. mime type) and perhaps there or other faulty things but anyway it did not worked as expected.

Is there a way I could use RequestDispatcher.forward with a media URL so that the response is served exactly as if the media URL was requested to the web server directly?

EDIT:

I can attest that at least the Content-Type is correct, since it's returning Content-Type text/html; charset=iso-8859-1 for any media file. Also, I have tried opening the url directly in Window Media Player and it seems to be downloading the entire video before starting to play, which is unacceptable. Therefore I can safely assume that forward doesn't just hand back the control to IIS or at least does it incorrectly for media files.

回答1:

The solution you found points to the right direction, but I have no knowledge of coldfusion, but with servlets the same thing can be done very easily.

If you want to use RequestDispatcher.forward method then you can specify a servlet url in the forward method. And in that servlet all you need to do is read the media and send it using OutputStream as the response.

For example:

In your servlets doGet or doPost method you just need to set the content type according to your media, read it and send it.

Below is a simple example you can use to send the media as response from the servlet:

public void doGet(HttpServletRequest request, HttpServletResponse response)  {
    response.setContentType("video/x-ms-wmx");
    ServletContext ctx = getServletContext();

    InputStream is = ctx.getResourceAsStream("/path/to/media/file");

    int read = 0;
    byte bytes[] = new byte[1024];

    OutputStream os = response.getOutputStream();
    while((read = is.read(bytes)) != -1) {
        os.write(bytes, 0, read);
    }
    os.flush();
    os.close();
}