动态显示数据库图片,本程序为小样,代码过于简单,只是实现其功能之作用。在代码方面没有考虑。
1. 创建数据库表
if exists (select * from dbo.sysobjects
where id = object_id(N'[dbo].
') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[picturenews]
GO
CREATE TABLE [dbo].[picturenews] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[image] [image] NULL ,
[content] [varchar] (500) COLLATE Chinese_PRC_CI_AS NULL ,
[detail] [varchar] (5000) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
2. 向数据库中存储图片
a. InputImage.jsp
<%@ page contentType="text/html;charset=gb2312"%>
<HTML>
<HEAD>
<TITLE>存储图片</TITLE>
</HEAD>
<body>
<!-- 下面的窗体将以Post方法,将数据传递给testimage.jsp文件 -->
<FORM METHOD=POST ACTION=<%request.getContextPath();%>"image.do?method=inputImage">
新 闻 标 题:<INPUT TYPE="text" NAME="content"><BR>
新 闻 图 片:<INPUT TYPE="file" NAME="image"><BR>
新闻内容:
<TEXTAREA name="txtmail" rows="15" cols="90"
style="BORDER-BOTTOM: #000000 1px solid; BORDER-LEFT: #000000 1px solid;
BORDER-RIGHT: #000000 1px solid; BORDER-TOP: #000000 1px solid; FONT-SIZE: 9pt;
HEIGHT: 200px; WIDTH: 100%" wrap="physical" ></TEXTAREA><br>
<INPUT TYPE="submit"></form>
</body>
</HTML>
b. ImageAction(ImageAction为DispatchAction,本Action在SRC下)
public class ImageAction extends DispatchAction {
public ActionForward inputImage(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException, SQLException, IllegalAccessException, InstantiationException, ClassNotFoundException, FileNotFoundException {
//保存
GetConnection getCon = new GetConnection();
Connection conn = getCon.getConnection();
Statement stmt = conn.createStatement();
//建立Statement对象
String content = request.getParameter("content");
content = new String(content.getBytes("8859_1"), "gb2312");
String filename = request.getParameter("image");
filename = new String(filename.getBytes("8859_1"), "gb2312");
String detail = request.getParameter("txtmail");
detail = new String(detail.getBytes("8859_1"), "gb2312");
//获得所要显示图片的标题、存储路径、内容,并进行中文编码
FileInputStream str = new FileInputStream(filename);
String sql = "insert into picturenews(content,image,detail) values(?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, content);
pstmt.setBinaryStream(2, str, str.available());
pstmt.setString(3, detail);
pstmt.execute();
pstmt.close();
conn.close();
System.out.println("~~~~~~~~~~~~~关");
return null;
}
public ActionForward showImage(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException, SQLException, IllegalAccessException, InstantiationException, ClassNotFoundException, FileNotFoundException {
// 显示图片
GetConnection getCon = new GetConnection();
Connection conn = getCon.getConnection();
Statement stmt = conn.createStatement();
String sql = new String();
sql = "select * from picturenews";
ResultSet rs = stmt.executeQuery(sql);
List list = new ArrayList();
while (rs.next()) {
ImageVO imagevo=new ImageVO();
int id=rs.getInt("id") ;
imagevo.setId(id);
imagevo.setTitle(rs.getString("content"));
imagevo.setNews(rs.getString("detail"));
list.add(imagevo);
}
stmt.close();
conn.close();
System.out.println("~~~~~~~~~~~~~关1");
request.setAttribute("list", list);
return mapping.findForward("show");
}
public ActionForward queryRs(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException, SQLException, IllegalAccessException, InstantiationException, ClassNotFoundException, FileNotFoundException {
// 查询图片
GetConnection getCon = new GetConnection();
Connection conn = getCon.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = null;
//建立ResultSet(结果集)对象
int id = (new Integer(request.getParameter("id"))).intValue();
//获得所要显示图片的编号id,并转换为整型
String sql = "select image from picturenews WHERE id=" + id + "";
System.out.println(sql);
//要执行查询的SQL语句
rs = stmt.executeQuery(sql);
while (rs.next()) {
ServletOutputStream sout = response.getOutputStream();
//图片输出的输出流
InputStream in = rs.getBinaryStream("image");
byte b[] = new byte[0x7a120];
while (in.read(b) != -1) {
//将缓冲区的输入输出到页面
sout.write(b);
}
sout.flush();
//输入完毕,清除缓冲
sout.close();
}
System.out.println("close");
stmt.close();
conn.close();
return null;
}
}
c.做一个连接页面,link.jsp
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>显示图片</title>
</head>
<body>
<a href=<%request.getContextPath();%>"image.do?method=showImage">显示图片 </a>
</body>
</html>
d.图片显示页面。showImage.jsp
<%@ page import="java.util.List,
java.util.ArrayList,
domain.ImageVO"%>
<%@ page contentType="text/html;charset=gb2312"%>
<html>
<head>
<title>动态显示数据库图片</title>
</head>
<body>
<%List list=(ArrayList) request.getAttribute("list");%>
<table border="1">
<%for(int i=0;i<list.size();i++){%>
<%ImageVO imagevo=(ImageVO) list.get(i);%>
<tr>
<td>取出第<%=imagevo.getId()%>个图片</td>
<td><%=imagevo.getTitle()%></td>
<td><IMG height=99 src=<%request.getContextPath();%>"image.do?method=queryRs&id=<%=imagevo.getId()%>" width=136></td>
<td><%=imagevo.getNews()%></td>
</tr>
<%}%>
</table>
</body>
</html>
e.在SRC下创建domain夹子,在domain下创建ImageVO
public class ImageVO {
private int id=0;//id
private String title = "";//标题
private String news = "";//新闻内容
public ImageVO() {
id=0;
title = "";
news = "";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getNews() {
return news;
}
public void setNews(String news) {
this.news = news;
}
}
f. struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<action-mappings>
<action path="/image" type="ImageAction" parameter="method" scope="request">
<forward name="show" path="/showImage.jsp"/>
</action>
</action-mappings>
</struts-config>
g.web.xml
<?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>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
</web-app>
h.在SRC下创建接接类
public class GetConnection {
private Connection conn = null;
public Connection getConnection() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb ";
String user = "sa";
String password = "";
conn = DriverManager.getConnection(url, user, password);
return conn;
}
}