我正在處理用戶信息被添加和修改(更新)的應用程序。使用servlet在jsp中顯示圖像
在添加模塊,管理員輸入用戶詳細信息並在「添加」按鈕生成unique-id(abc001)。並且管理員還將用戶的圖像/圖片(名稱:abc001)保存在服務器位置(// some-location-ip address/D drive/images)中。
「更新」模塊,admin可以修改用戶的詳細信息,但不能修改id。
我需要一些方向在幾個場景。
如果某個管理員「更新」了某個特定用戶,則當該管理員點擊更新按鈕時,該服務器中該用戶的圖像應該會顯示在該頁面上。在JSP
圖片代碼:
<img height="100px;" width="100px;" src="........." alt="Candidate Image"></img>
我已經寫了一個servlet,但不知道如何調用對應於不同用戶的不同圖像和個人資料頁上顯示的圖像。
用戶A簡檔將顯示用戶A的圖像 用戶B簡檔將顯示用戶B圖像 等
的Servlet代碼段
public class UpDatePhoto extends HttpServlet {
public UpDatePhoto() {
super();
// TODO Auto-generated constructor stub
}
private static final long serialVersionUID = -8071854868821235857L;
private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
private String imagePath;
*public void init() throws ServletException {
this.imagePath = "D:\\photo_not_available_large.png";
}*
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String requestedImage = request.getPathInfo();
if (requestedImage == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
File image = new File(imagePath, URLDecoder.decode(requestedImage, "UTF-8"));
String contentType = getServletContext().getMimeType(image.getName());
if (contentType == null || !contentType.startsWith("image")) {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(image.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(image), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
close(output);
close(input);
}
}
private static void close(Closeable resource) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
圖像沒有HTTP訪問但是隻能作爲訪問一個文件,servlet將不得不打開圖像文件,讀入內容並將它們放在響應緩衝區中「....不知道我是否正確。並幫助我如何從服務器目錄位置獲取圖像併爲用戶顯示正確的圖像。
道歉如果問題很模糊,很多謝謝你的建議:),會試試看 –