这不是 HTML 的工作方式。
浏览器首先请求服务器给它所有的文本内容。然后浏览器单独向服务器请求图像内容、js 内容、css 内容等。所以你不能使用 jsp 在页面上“写”你的图像,只是你如何写你的文本、表格等。图像需要有一个 src ”网址”。
如果您的图像内容来自 DB,则 URL 需要是一个 servlet。它基本上从数据库中获取图像,将其转换为流并发送回浏览器。
如果您绝对希望文本和图像来自同一个 servlet,那么也许您可以使用请求参数...
这里是一个示例 servlet 和 html。看看你是否可以在你的项目中使用类似的风格
Servlet(从磁盘加载图像。更改代码以从数据库加载)
@WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
if(id!=null && "1".equalsIgnoreCase(id)){
response.setContentType("image/jpeg");
response.getOutputStream().write( Files.readAllBytes(new File(getServletContext().getRealPath("****.jpg")).toPath()));
response.getOutputStream().close();
}else {
response.getWriter().println("Sample text");
response.getWriter().close();
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
}
}
HTML(文本通过 AJAX 加载。如果需要,您可以使用 AJAX 加载文本和图像)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
function load()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("textDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","Servlet2?id=2",true);
xmlhttp.send();
}
</script>
</head>
<body onload="load()">
<div id="textDiv"></div>
<br/>
<input type="image" src="http://localhost:8080/ImageCanvas/Servlet2?id=1"/>
</body>
</html>