RequestDispatcher.forward to a media file?

最后都变了- 提交于 2019-12-10 21:17:56

问题


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();
}


来源:https://stackoverflow.com/questions/19529364/requestdispatcher-forward-to-a-media-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!