Servlet doGet()代码,用于从数据库获取图像并在响应中存储图像
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...
我得到了什么输出:
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>
答案 0 :(得分:4)
如何在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应该只返回图像。而已。 Web浏览器本身应该下载并显示图像,而不是网络服务器。
答案 1 :(得分:2)
1 你正在修改响应然后转发,这是没用的。不要这样做。