java - 从 servlet 调用图像和链接

标签 java servlets

使用这段代码,我可以从 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/

相关文章:

java - 3.1 中缺少 SPRING_SECURITY_LAST_LOGIN

java - 您建议使用哪种压缩(GZIP 是最流行的)servlet 过滤器?

java - 识别类本身后使用类函数

java - 在 Java 中读取缓冲区

java - hashMap 的意外输出

java - Jetty Servlet 不运行——而是获取目录列表

java - 是否有用于应用程序级(而非数据库)事务(例如回滚)的框架

c# - 如何从c# windows 窗体连接java servlet?

java - 为什么这个简单的jsp程序没有运行?

java - 使用局部变量还是全局变量更好