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页面。
only image
JSP代码:
... JSP code <img src="Servlet url"> ... JSP code cont...
我得到什么输出:
java.lang.IllegalStateException: Cannot forward after response has been committed
题:
编辑:我的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>
如何在JSP中获取图像而不只是在浏览器中获取图像
<img>在浏览器地址栏中输入包含该元素的JSP文件的URL 。
<img>
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应该只返回图像。而已。应该由网络浏览器本身下载并显示图像,而不是由网络服务器。