Ссылка на сервлет в файле HTML для файла .war в Tomcat - PullRequest
0 голосов
/ 06 апреля 2020

Я создал файл index. html для приложения Java (.war), которое я развернул на tomcat.

У меня уже есть файл сервлета Java, который запрашивает удаленный сервер БД для изображения, которое я там сохранил.

Файл сервлета java называется ImageServlet. java.

Мне нужна страница HTML, чтобы отобразить это изображение, что ImageServlet. java запросы.

Я просто не знаю, как я могу ссылаться на сервлет, когда он получает мою картинку.

Ниже приведен файл 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();
  }
}

1 Ответ

0 голосов
/ 06 апреля 2020
@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.html или index.jsp:

<img src="${pageContext.request.contextPath}/foo.jpg">
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...