|
发表于 2020-7-13 22:00:01
|
显示全部楼层
替你靠过来了
从数据库取出图像数据并通过servlet发布为图片
代码只能做为参考,最好不要用在实际,因为它严重违反了MVC模式。
servlet
以下内容为程序代码:
/**
*
*/
package servlet;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletConfig;
import javax.servlet.ServletOutputStream;
import javax.imageio.ImageIO;
import java.sql.*;
import java.awt.Image;
import java.awt.image.BufferedImage;
/**
* @author jaqcy
*
*/
public class ImageServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
// TODO 自动生成方法存根
resp.setContentType("image/png"[img]/images/wink.gif[/img];
BufferedImage image=null;
try
{
Class.forName("com.mysql.jdbc.Driver"[img]/images/wink.gif[/img];
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/sampledb","root","mysql"[img]/images/wink.gif[/img];
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("select image from customers"[img]/images/wink.gif[/img];
if(rs.next())
{
Blob blob=rs.getBlob(1);
InputStream is=blob.getBinaryStream();
image=ImageIO.read(is);
}
rs.close();
stmt.close();
conn.close();
ServletOutputStream sos=resp.getOutputStream();
ImageIO.write(image,"PNG",sos);
sos.close();
}
catch (Exception e)
{
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
// TODO 自动生成方法存根
doGet(req, resp);
}
@Override
public void init(ServletConfig config) throws ServletException
{
// TODO 自动生成方法存根
super.init(config);
}
}
以下内容为程序代码:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<servlet>
<servlet-name>image</servlet-name>
<servlet-class>servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>image</servlet-name>
<url-pattern>/image.png</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>image.png</welcome-file>
</welcome-file-list>
</web-app>
|
|