|
Leaned over for you
Take the image data from the database and publish it as a picture through servlet
The code can only be used as a reference, it is best not to use it in practice, because it seriously violates the MVC pattern.
servlet
The following is the program code:
/**
*
*/
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 automatically generates method stubs
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 automatically generates catch blocks
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
// TODO automatically generates method stubs
doGet(req, resp);
}
@Override
public void init(ServletConfig config) throws ServletException
{
// TODO automatically generates method stubs
super.init(config);
}
}
The following is the program code:
<?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> |
|