gpt4 book ai didi

java - 引用HTML文件中的servlet以获取Tomcat中的.war文件

转载 作者:行者123 更新时间:2023-12-01 17:34:33 25 4
gpt4 key购买 nike

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

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

该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();
}
}

最佳答案

@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">

关于java - 引用HTML文件中的servlet以获取Tomcat中的.war文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61063101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com