2012-05-24 18 views
2

使用此代碼,我可以呈現來自servlet的圖像,但我的企業說。我需要添加一個鏈接,如「www.google.com」。如果我點擊此image.Is有任何方式,我可以通過鏈接訪問圖像。我需要直接從servlet刷新它不應該使用jsp.Can任何人請幫助我。從servlet調用圖像和鏈接

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { 

     ServletContext sc = getServletContext(); 
     String filename = sc.getRealPath("image.JPG"); 

     resp.setContentType("image/jpeg"); 

     // Set content size 
     File file = new File(filename); 
     resp.setContentLength((int)file.length()); 

     // Open the file and output streams 
     FileInputStream in = new FileInputStream(file); 
     OutputStream out = resp.getOutputStream(); 

     // Copy the contents of the file to the output stream 
     byte[] buf = new byte[1024]; 
     int count = 0; 
     while ((count = in.read(buf)) >= 0) { 
      out.write(buf, 0, count); 

     } 
     in.close(); 
     out.close(); 
    } 

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     doPost(request , response); 
     // TODO Auto-generated method stub 
    } 

} 

回答

0

總之你要添加一個鏈接說google.com,並在其點擊顯示圖片。

首先你不需要發送圖像作爲迴應,相反你需要錨點鏈接並在該鏈接上添加javascript函數onclick。

out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + 
             "Transitional//EN\">\n" + 
       "<HTML>\n" + 
       "<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" + 
       "<BODY>\n" + 
       "<a href='www.google.com'><img src='imagePath' /></a>\n" + 
       "</BODY></HTML>"); 
1

你需要把一個<a>元素<img>元素周圍的標記。

<a href="http://www.google.com"> 
    <img src="imageServlet" /> 
</a> 

順便說一句,在sc.getRealPath()意味着你的圖像文件是已經公共WebContent文件夾。爲什麼不使用<img src="image.JPG">代替?或者servlet過度簡化了嗎?

+0

問題是 - 他們的servlet正在返回一個圖像,而不是標記。如果這保持原樣,那麼答案是「否」,您不能使用鏈接返回圖像。只是爲了確保@ user1046671能理解。 它可能是另一個servlet返回標記的工作,或者必須修改此servlet以返回文本/ html,如您的示例中所示。 – maksimov

+0

@balusc:maksimov說的是完全正確的,我們正在返回的圖像不是標記。所以沒有辦法扭轉,我們可以同時獲得圖像和鏈接。我的任務是呈現圖像,如果點擊它應該彈出提供的網站圖像。 – user1046671

+0

@maksimov:如果我將其更改爲文本或html,我的圖像將工作爲了獲得圖像,我們需要有圖像/ jpeg。 – user1046671

0

如果我undestood糾正你可以用鏈接的圖像返回HTML:

<a href="http://www.google.com"><img src="yourImageRenderingServletPath"></a> 

所以,你將有一個servlet,它呈現HTML和第二的是渲染圖像。爲了防止圖像緩存在瀏覽器,您可以添加隨機PARAM ID =(新的隨機())nextInt():

<a href="http://www.google.com"><img src="yourImageRenderingServletPath?id=124"></a>