【问题标题】:how to display image and text from mysql database on jsp page如何在jsp页面上显示来自mysql数据库的图像和文本
【发布时间】:2014-05-06 05:06:33
【问题描述】:

我正在做一个 Java Web 应用程序,我需要同时显示 MySQL 数据库中的图像和文本。请帮助我在数据库的同一“JSP”页面上显示图像和文本。我的图像在 MySQL 中存储为 blob .

【问题讨论】:

标签: java jsp


【解决方案1】:

您可以定义可以将图像发送给用户的 servlet http://www.javatpoint.com/example-to-display-image-using-servlet

然后定义从 blob 中检索的图像 http://codeglobe.blogspot.com/2009/03/readwrite-blob-fromto-mysql-in-java_21.html

在你的jsp页面中添加图片链接

<img src="http://example.com/getImage?imageId=1234">

因此,当用户单击链接时,您的 servlet 将被调用。 servlet 从 BLOB 中读取图像并将其发送到响应中。

更新:

你也可以试试http://www.roseindia.net/tutorial/java/jsp/jspdisplayblob.html

【讨论】:

  • 实际上我只获取文本或图像,但我希望同时从同一个数据库中获取两者..
【解决方案2】:

这不是 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>

【讨论】:

    猜你喜欢
    • 2013-03-27
    • 2012-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多