索引... 1關(guān)鍵詞... 1序... 2準(zhǔn)備工作... 2開發(fā)環(huán)境... 3流程和主要代碼... 3創(chuàng)建數(shù)據(jù)庫... 3整合SSH.. 4主要代碼(知識)... 5程序截圖... 12分享和下載... 14李順利,Struts,圖片,存取,存入,顯示,Mysql,數(shù)據(jù)庫,Blob,
實際上,寫完
多文件上傳和下載文章的時候,類似的想法就已經(jīng)有了,一直沒有實際把它整理好,今天也終于把這方面的一些經(jīng)驗分享給大家了。
本文涉及到的需求(功能點)大致有:
1. 如何上傳圖片,并把圖片存入數(shù)據(jù)庫(Mysql)中;
2. 從數(shù)據(jù)庫中讀取圖片并顯示在頁面中
注:本文使用的是單純的Struts2 + Spring + Hibernate,圖片操作并沒有使用Servlet。
本文全部使用Annotation來整合SSH,運用了文件上傳和表單驗證等知識,這些知識都可以在我以前寫的博文中獲取到,包括
1. Struts2下多文件的上傳與下載
http://www.blogjava.net/lishunli/archive/2010/01/07/308614.html2. 使用Annotation并對DAO層封裝具有分頁功能的S2SH整合實例
http://www.blogjava.net/lishunli/archive/2010/03/10/315055.htmlhttp://www.blogjava.net/lishunli/archive/2010/03/12/315231.html3. 如何自定義Struts2表單驗證后的錯誤信息顯示格式/樣式
http://www.blogjava.net/lishunli/archive/2010/10/17/335384.htmlhttp://www.blogjava.net/lishunli/archive/2010/01/07/308609.html如果大家對上面的知識有所欠缺的話和想學(xué)習(xí)的話,也請大家Google或者看我的blog。謝謝。
Struts 2.1.8.1 + Hibernate3 + Spring3+ Mysql5 + Tomcat 7.0.2+ Myeclipse 8.6
本文會使用User對象(包括username、password、picture等屬性),對應(yīng)Mysql數(shù)據(jù)庫的創(chuàng)建腳本如下:
/*
Source Server : Local
Source Server Version : 50140
Source Host : localhost:3306
Source Database : test
Target Server Type : MYSQL
Target Server Version : 50140
File Encoding : 65001
Date: 2010-11-13 23:23:37
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`username` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`picture` longblob,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=61 DEFAULT CHARSET=utf8;
(請注意pictrue的類型)
這個步驟請參考
使用Annotation并對DAO層封裝具有分頁功能的S2SH整合實例。
1、 User 類
實際上很簡單,寫出來,主要是讓大家知道這里面圖片是使用的是什么類型
@Entity
@Table(name = "user", catalog = "test")
public class User implements java.io.Serializable {
private static final long serialVersionUID = 4230186551226007292L;
private Integer id;
private String username;
private String password;
private Blob picture;
/**
* 省略構(gòu)造方法和set、get方法
*/
}
2、 AddUserAction類
在add user action,就是真正的把User對象(包括圖像)save到Mysql中。其中這里使用了Struts2的Annotation,請注意 InterceptorRefs 中 params 的寫法。
關(guān)鍵的代碼也就是使用hibernate的createBlob方法來把File類型轉(zhuǎn)換成Blob類型。
Blob blob = Hibernate.createBlob(..)
@Controller
@Scope("prototype")
@Results( { @Result(name = "success", location = "/index.jsp"), @Result(name = "input", location = "addUser.jsp") })
@InterceptorRefs(value = {
@InterceptorRef(value = "fileUpload", params = { "maximumSize", "1048576", "allowedTypes","image/bmp,image/x-png,image/png,image/gif,image/jpeg,image/jpg,image/pjpeg" }), @InterceptorRef(value = "defaultStack") })
public class AddUserAction extends ActionSupport {
private static final long serialVersionUID = -4829467290275994251L;
private User user;
private File image;
@Resource(name = "org.usc.services.userService")
private IUserService userService;
/**
* 省略 set、get方法和validate驗證
*/
@Override
public String execute() throws Exception {
if (image != null) {
FileInputStream fin = new FileInputStream(image);// File 轉(zhuǎn) InputStream
Blob blob = Hibernate.createBlob(fin);// InputStream 轉(zhuǎn) Blob
user.setPicture(blob);
}
userService.save(user);
return SUCCESS;
}
}
3、 addUser.jsp
這個就是一個普通的Input界面,很簡單。想說一下,這里使用了表單驗證后信息顯示的技術(shù),詳情請見
<s:form action="add-user" method="post" theme="simple" enctype="multipart/form-data">
UserName<s:textfield name="user.username"></s:textfield>
<font color="red"> *<s:property value="fieldErrors['user.username'][0]" /> </font>
<br>
PassWord<s:password name="user.password"></s:password>
<font color="red"> *<s:property value="fieldErrors['user.password'][0]" /> </font>
<br>
Image<s:file name="image"></s:file>
<font color="red"><s:property value="fieldErrors['image'][0]" /> </font>
<br>
<s:submit value="Submit" /><s:reset value="Reset"></s:reset>
</s:form>
4、 GetAllUserAction 類
很簡單,不想貼代碼了,主要是通過Dao查找所有的User,再放到List<User> userList,Struts在調(diào)用此Action的使用,通過Iterator List來顯示所有的User。
注意:我這里僅使用了List,并沒有使用把List放到request中,Struts會通過s:iterator來迭代List,只要我們提供Get List 方法即可。
<s:iterator value="userList" id="user" status="count">
5、 GetImageByIdAction 類
這個類應(yīng)該是本文的難點和重點,實際上,代碼很簡單的,請大家注意一下幾點
1) 使用Result type“Stream” :type = "stream" ;
2) Result params 中設(shè)置 contentType 和inputName參數(shù),其中
contentType = image/jpeg
inputName = image
inputName 是Action可以通過相關(guān)的method獲得InputStream。
注意:下載文件這里不使用contentType,而是使用contentDisposition參數(shù),詳情請見
Struts2下多文件的上傳與下載<param name="contentDisposition">attachment;filename="${fileName}"</param>
(Action可以通過Get,Set FileName()來設(shè)置和獲得文件名)
實際上這部分的代碼是參考以前某位朋友寫的使用Struts2 生成驗證碼的例子,參考下面的網(wǎng)站
struts2 實現(xiàn)圖片驗證碼不好意思,現(xiàn)在記不清作者和網(wǎng)站,所以貼上的網(wǎng)址不知道是否是原創(chuàng)或者就是原創(chuàng),如果有朋友知道,請聯(lián)系我,我會更新鏈接的,謝謝,也很感謝這位朋友的無私奉獻(xiàn)。
@Controller
@Scope("prototype")
@Results( { @Result(type = "stream", params = { "contentType", "image/jpeg", "inputName", "image" }) })
public class GetImageByIdAction extends ActionSupport {
private static final long serialVersionUID = 207987943720580274L;
private Integer id;
@Resource(name = "org.usc.services.userService")
private IUserService userService;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setUserService(IUserService userService) {
this.userService = userService;
}
/**
* 注意這里的方法名,和上面配置params中inputName是一致的,Struts會調(diào)用此方法(也可以使用Method配置其他方法)
* @return
* @throws Exception
*/
public InputStream getImage() throws Exception {
InputStream imageStream = userService.find(id).getPicture().getBinaryStream();
return imageStream;
}
}
6、 allUser.jsp
這個JSP也算知識點比較多,包括一下幾點
1) Action如何取得Image顯示在頁面上
通過調(diào)用get-image-by-id.action來獲取圖片
2) list如何Iterator
<s:iterator value="userList" id="user" status="count">
// 注意value
3) Table可以限制每行顯示多少條記錄
<s:if test="#count.index % 6 == 0">
<tr>
</s:if>
<s:if test="(#count.index + 1) % 6 == 0">
</tr>
</s:if>
// 每行顯示6 條記錄
(延伸,也可以控制只顯示多少條,給個鏈接,顯示所有的條數(shù))
4) 如果標(biāo)題長了,省略多余的字,避免表格撐大
<td width="800" height="120" style="width: 200px; word-break: break-all" align="center">
<div style="width: 200x; height: 20px; border: 1px; overflow: hidden; text-overflow: ellipsis">
(單元格固定寬帶,不是隨著內(nèi)容的變化而變化)
5) 如果沒找到圖片的話,選擇默認(rèn)圖片顯示
<img … onerror="javascript:this.src='images/default.png'" />
<s:form action="get-all-user" method="post" theme="simple">
<s:if test="userList.size">
<table width="75%" align="center">
<s:iterator value="userList" id="user" status="count">
<s:if test="#count.index % 6 == 0">
<tr>
</s:if>
<td width="800" height="120" style="width: 200px; word-break: break-all" align="center">
<a target="_blank">
<img src="<%=basePath + "get-image-by-id.action?id="%><s:property value="#user.id"/>" width="100" height="100" alt="照片"
title="<s:property value="#user.username" />" onerror="javascript:this.src='images/default.png'" />
</a>
<div style="width: 200x; height: 20px; border: 1px; overflow: hidden; text-overflow: ellipsis">
<s:property value="#user.username" />
</div>
</td>
<s:if test="(#count.index + 1) % 6 == 0">
</tr>
</s:if>
</s:iterator>
</table>
</s:if>
</s:form>
本文全部使用的是Annotation(包括Struts2的所有配置),如果需要使用xml但又覺得轉(zhuǎn)化成xml配置有困難的話,可以Google,或者聯(lián)系我。謝謝。
本篇文章還是可以延伸的,可以做成上傳文件,再判斷文件類型,例如是Image類型的,就顯示出來,如果是Txt等類型,可以提供下載。后續(xù)…或者Ending…
源碼在Google Code上
https://usc.googlecode.com/svn/ImageUseStruts2AndMysql源碼和相關(guān)參考提供下載
順利提供下載:(源碼和參考,所需Jar通過最下面的鏈接下載)
文 件 名:ImageUseStruts2AndMysql.zip
下載地址:http://usc.googlecode.com/files/ImageUseStruts2AndMysql.zip
其中 ImageUseStruts2AndMysql.zip 有下面的文件
順利提供下載:(源碼沒有相應(yīng)的Jar包,下載下面的整合Jar包添加進后才可以運行)
文 件 名:SSHWithAnnotationDemo.rar
下載地址:http://usc.googlecode.com/files/SSHWithAnnotationDemo.rar