使用这段代码,我可以从 servlet 渲染图像,但我的业务说。我需要添加一个链接,比如“www.google.com”。如果我单击此图像。有什么办法可以访问带有链接的图像。我需要直接从 servlet 刷新它不应该使用 jsp。任何人都可以帮助我。
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
}
}
最佳答案
您需要输入 <a>
<img>
周围的元素标记中的元素。
<a href="http://www.google.com">
<img src="imageServlet" />
</a>
顺便说一句,sc.getRealPath()
建议您的图像文件已经在公共(public) webcontent 文件夹中。为什么不只使用 <img src="image.JPG">
反而?还是 servlet 过于简单化了?
关于java - 从 servlet 调用图像和链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10738831/