小编典典

如何使用Servlet在响应中显示图像的JSP页面?

jsp

Servlet doGet()代码用于从数据库获取图像并将图像存储在Response中

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException {

// Get userid from session

try {

    // Get photos from database in (image)

    // Init servlet response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(image.getContenttype());
    response.setHeader("Content-Length", String.valueOf(image.getLength()));
    response.setHeader("Content-Disposition", "inline; filename=\"" + image.getTitle()
    + "\"");

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(image.getPhoto(), DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(),
                 DEFAULT_BUFFER_SIZE);

        // Write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    } finally {
        // Gently close streams.
        output.close();
        input.close();
    }

    //Redirect it to photo page
    RequestDispatcher rd = request.getRequestDispatcher
        ("/webplugin/jsp/profile/photos.jsp");
    rd.forward(request, response);

} catch (Exception e) {
    e.printStackTrace();
}

}

但是,当此servlet显示JSP页面时,它显示的only image不是JSP页面。

JSP代码:

... JSP code

<img src="Servlet url">

... JSP code cont...

我得到什么输出:

  1. 我只得到图像而不是JSP中的图像
  2. 当我使用RequestDispatcher / sendRedirect()时,出现以下异常 java.lang.IllegalStateException: Cannot forward after response has been committed

题:

  1. 如何在JSP中获取图像而不只是在浏览器中获取图像
  2. 如何避免上述异常?

编辑:我的Web.xml看起来像这样

<servlet>
    <servlet-name>Photo Module</servlet-name>
    <servlet-class>app.controllers.PhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Photo Module</servlet-name>
    <url-pattern>/Photos</url-pattern>
</servlet-mapping>

阅读 331

收藏
2020-06-08

共1个答案

小编典典

如何在JSP中获取图像而不只是在浏览器中获取图像

<img>在浏览器地址栏中输入包含该元素的JSP文件的URL 。

http:// localhost:8080 / contextname / webplugin / jsp / profile /
photos.jsp


如何避免上述异常?

*从servlet代码中 *删除 以下几行。

//Redirect it to profile page
RequestDispatcher rd = request.getRequestDispatcher
    ("/webplugin/jsp/profile/photos.jsp");
rd.forward(request, response);

servlet应该只返回图像。而已。应该由网络浏览器本身下载并显示图像,而不是由网络服务器。

2020-06-08