参考HTML文件中的Tomcat中.war文件的servlet

问题描述 投票:0回答:1

我为部署在tomcat上的Java(.war)应用程序创建了index.html文件。

我已经有一个Java Servlet文件,该文件查询远程db服务器以获取我存储在其中的图片。

该Java Servlet文件称为ImageServlet.java。

我需要HTML页面来显示ImageServlet.java查询的图像。

我只是不知道在检索我的图片时如何引用servlet。

下面是ImageServlet文件:

package test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;

public class ImageServlet extends HttpServlet
{
  Connection con = null;

  public Connection getConnection()
  {
    try {
      Class.forName("com.mysql.jdbc.Driver");
      String url = System.getenv("FUJI_MYSQL_URL");
      return DriverManager.getConnection(url,             
System.getenv("FUJI_MYSQL_USER"), System.getenv("FUJI_MYSQL_PASS"));
    }
    catch (Exception ex)
    {
      System.out.println(ex.getMessage());
    }return null;
  }

  public static byte[] getImageById(Connection con)
  {
    String query = "select photo from photos where picid = 1";
    try
    {
      PreparedStatement stmt = con.prepareStatement(query);

      stmt.execute();
      ResultSet resultSet = stmt.getResultSet();
      resultSet.first();
      Blob blob = resultSet.getBlob(1);
      stmt.close();
      con.close();
      return blob.getBytes(1L, (int)blob.length());
    } catch (Exception ex) {
      System.out.println(ex.getMessage());
    }return null;
  }

  public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
  {
    PrintWriter out = res.getWriter();

    Connection con = null;
    con = getConnection();
    byte[] data = getImageById(con);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(data);

    out.println("<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title>PI_SQLogo.png</title></head><body><img src='data:image/png;base64," + DatatypeConverter.printBase64Binary(baos.toByteArray()) + "'></body></html>");
    out.close();
  }
}
java html jsp tomcat servlets
1个回答
0
投票
@WebServlet("/")
public class ImageServlet extends HttpServlet {
    //...
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //...
        byte[] data = getImageById(con);
        response.setContentType("image/jpeg"); // Assuming your image is .jpg
        response.setContentLength(data.length);
        response.getOutputStream().write(data);
    }
    //..
}

然后输入index.htmlindex.jsp

<img src="${pageContext.request.contextPath}/foo.jpg">
© www.soinside.com 2019 - 2024. All rights reserved.