使用Struts2,Hibernate和MySQL BLOB开发个人迷你相册应用程序–第1部分
概述:
在本研討會中,我們將開發一個Web應用程序,可用于創建漂亮的照片庫。 您可以將其托管在Web服務器中,也可以在自己的PC中使用以維護和管理照片集。 使用本教程,您將能夠了解與Struts2和Hibernate相關的以下重要內容:
- 如何將Struts2框架與Hibernate集成
- 如何在Struts2中上傳照片或文件
- 如何在MySQL BLOB字段之間動態上傳/下載照片
- 如何在Struts2中將參數從一個動作動態傳遞給另一個動作
在本教程的第1部分中,我們將開發管理面板。 管理面板將用于創建相冊并將照片上傳到相冊。 在第2部分中,我們將創建前端主Web應用程序,該應用程序將按管理面板中添加的相冊顯示照片。
使用的工具:
步驟1:為照片庫應用程序準備數據庫MySQL
我們將使用MySQL數據庫。 Belw是用于您創建數據庫表的腳本。 使用的數據庫名稱是'tctalk_apps_photoalbum'。 但是,您可以創建任何數據庫名稱。 只要記住您需要在Hibernate配置文件中更改數據庫名稱即可。 以下是兩個表Album和phototbl的SQL。
CREATE TABLE IF NOT EXISTS `album` (`albumid` INT(4) NOT NULL AUTO_INCREMENT,`albumname` VARCHAR(55) NOT NULL,`albumdesc` text NOT NULL,`albumcreatedate` DATE NOT NULL,PRIMARY KEY (`albumid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;CREATE TABLE IF NOT EXISTS `phototbl` (`photoid` INT(4) NOT NULL AUTO_INCREMENT,`albumid` INT(4) NOT NULL,`phototitle` VARCHAR(255) NOT NULL,`photoname` VARCHAR(255) NOT NULL,`imgcontenttype` VARCHAR(255) NOT NULL,`photocreatedate` datetime NOT NULL,`photodata` longblob NOT NULL,PRIMARY KEY (`photoid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;步驟2:在Java源代碼中創建包
在Eclipse中創建動態Web項目之后,在java src端創建軟件包。 請記住,包com.tctalk.apps.album.db.xxx包含所有Java和其他文件,可在數據庫/休眠端使用,而com.tctalk.apps.album.web.xxx將具有所有使用struts2的表示層的Java文件。框架。
Businessobject將使所有BO類都與表映射。 Dao將具有DAO類以使用Hibernate調用數據庫。 Hbm將具有* .hbm.xml文件,該文件具有表字段和表Java的映射。 實用程序將具有各種實用程序類。 動作將具有Struts2框架的所有動作類。 委托將把委托類作為UI層和DB層之間的橋梁。 表單將具有與UI字段相對應的POJO(普通Java對象)。 Hibernate.cfg.xml具有hibernate配置文件,以具有數據庫連接信息以連接到數據庫。 Struts.xml具有Struts配置數據。
步驟3:將jar文件復制到lib文件夾中
您將需要從Tomcat安裝目錄中獲取的servlet-api.jar文件。 我的Tomcat位于C:\ Java \ Tomcat \ tomcat7文件夾中。
步驟4:將Struts 2支持添加到我們的應用中
我們的應用程序中已經具有支持Struts2所需的jar文件。 現在是時候包括Struts2.xml并將引用放在web.xml中,以便讓Tomcat知道這一點。
Web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>PersonalPhotoAlbumApp</display-name><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping><filter-name>struts2</filter-name><url-pattern>*.action</url-pattern> </filter-mapping> </web-app>Struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""http://struts.apache.org/dtds/struts-2.0.dtd"><struts><constant name="struts.enable.DynamicMethodInvocation" value="false" /><constant name="struts.devMode" value="false" /><package name="default" extends="struts-default" namespace="/"><result-types><result-type name="imageResult" class="com.tctalk.apps.album.web.actions.CustomPhotoResult" /></result-types><default-action-ref name="index" /><action name="index"><result>index.jsp</result></action><action name="admin"><result name="success" type="redirectAction">listAlbumAdmn</result></action><action name="listAlbumAdmn" class="com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction" method="getAllAlbumList" ><result name="success">/WEB-INF/admin/jsp/showalbums.jsp</result></action><action name="addAlbumAdmn" class ="com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction" method="addAlbumToCollection" ><result name="input">listAlbumAdmn</result><result name="success" type="redirectAction">listAlbumAdmn</result></action><action name="delAlbumAdmn" class ="com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction" method="delAlbumFromCollection" ><result name="success" type="redirectAction">listAlbumAdmn</result></action><action name="listPhotosByAlbumAdmn" class="com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction" method="listAllPhotos" ><result name="success">/WEB-INF/admin/jsp/showphotos.jsp</result></action><action name="addPhotoAcion" class ="com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction" method="uploadPhotoToAlbum" ><interceptor-ref name="exception"/><interceptor-ref name="i18n"/><interceptor-ref name="fileUpload"><param name="allowedTypes">image/x-png,image/png,image/gif,image/jpeg,image/pjpeg</param></interceptor-ref> <interceptor-ref name="params"><param name="excludeParams">dojo\..*,^struts\..*</param></interceptor-ref><interceptor-ref name="validation"><param name="excludeMethods">input,back,cancel,browse</param></interceptor-ref><interceptor-ref name="workflow"><param name="excludeMethods">input,back,cancel,browse</param></interceptor-ref><result name="success" type="redirectAction"><param name="actionName">listPhotosByAlbumAdmn</param><param name="albumid">${albumid}</param></result><result name="input">/WEB-INF/admin/jsp/showphotos.jsp</result></action><action name="delPhotoFrmAlbumAdmn" class ="com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction" method="delPhoto" ><result name="success" type="redirectAction"><param name="actionName">listPhotosByAlbumAdmn</param><param name="albumid">${albumid}</param></result></action><action name="showPhotoAction" class="com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction" method="showPhoto"><result name="success" type="imageResult"/></action></package></struts>步驟5:將Hibernate支持添加到我們的相冊應用程序
要使用hibernate,我們已經有一個不錯的分步教程,它顯示了如何在Eclipse中使用Hibernate插件自動生成與數據庫表相對應的hbm和java文件。 查看教程– http://www.techcubetalk.com/2013/04/step-by-step-auto-code-generation-for-pojo-domain-java-classes-and-hbm-files-using-elipse-休眠插件/
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration><session-factory><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tctalk_apps_photoalbum</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password"></property><property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property><property name="show_sql">true</property><mapping resource="com/tctalk/apps/album/db/hbm/Album.hbm.xml" /><mapping resource="com/tctalk/apps/album/db/hbm/Phototbl.hbm.xml" /></session-factory> </hibernate-configuration>相冊BO.java
package com.tctalk.apps.album.db.businessobjects; // Generated Apr 22, 2013 1:26:39 PM by Hibernate Tools 3.4.0.CR1import java.util.Date;/*** Album generated by hbm2java*/ public class AlbumBO implements java.io.Serializable {private Integer albumid;private String albumname;private String albumdesc;private Date albumcreatedate;public AlbumBO() {}public AlbumBO(String albumname, String albumdesc, Date albumcreatedate) {this.albumname = albumname;this.albumdesc = albumdesc;this.albumcreatedate = albumcreatedate;}public Integer getAlbumid() {return this.albumid;}public void setAlbumid(Integer albumid) {this.albumid = albumid;}public String getAlbumname() {return this.albumname;}public void setAlbumname(String albumname) {this.albumname = albumname;}public String getAlbumdesc() {return this.albumdesc;}public void setAlbumdesc(String albumdesc) {this.albumdesc = albumdesc;}public Date getAlbumcreatedate() {return this.albumcreatedate;}public void setAlbumcreatedate(Date albumcreatedate) {this.albumcreatedate = albumcreatedate;}}PhototblBO.java
package com.tctalk.apps.album.db.businessobjects; // Generated Apr 22, 2013 1:26:39 PM by Hibernate Tools 3.4.0.CR1import java.util.Date;/*** Phototbl generated by hbm2java*/ public class PhototblBO implements java.io.Serializable {private int photoid;private int albumid;private String phototitle;private String photoname;private String imgcontenttype;private Date photocreatedate;private byte[] photodata;public PhototblBO() {}public PhototblBO(int photoid, int albumid, String phototitle,String photoname, String imgcontenttype, Date photocreatedate,byte[] photodata) {this.photoid = photoid;this.albumid = albumid;this.phototitle = phototitle;this.photoname = photoname;this.imgcontenttype = imgcontenttype;this.photocreatedate = photocreatedate;this.photodata = photodata;}public int getPhotoid() {return this.photoid;}public void setPhotoid(int photoid) {this.photoid = photoid;}public int getAlbumid() {return this.albumid;}public void setAlbumid(int albumid) {this.albumid = albumid;}public String getPhototitle() {return this.phototitle;}public void setPhototitle(String phototitle) {this.phototitle = phototitle;}public String getPhotoname() {return this.photoname;}public void setPhotoname(String photoname) {this.photoname = photoname;}public String getImgcontenttype() {return this.imgcontenttype;}public void setImgcontenttype(String imgcontenttype) {this.imgcontenttype = imgcontenttype;}public Date getPhotocreatedate() {return this.photocreatedate;}public void setPhotocreatedate(Date photocreatedate) {this.photocreatedate = photocreatedate;}public byte[] getPhotodata() {return this.photodata;}public void setPhotodata(byte[] photodata) {this.photodata = photodata;}}Album.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated Apr 22, 2013 1:26:40 PM by Hibernate Tools 3.4.0.CR1 --> <hibernate-mapping><class name="com.tctalk.apps.album.db.businessobjects.AlbumBO" table="album" catalog="tctalk_apps_photoalbum"><id name="albumid" type="java.lang.Integer"><column name="albumid" /><generator class="identity" /></id><property name="albumname" type="string"><column name="albumname" length="55" not-null="true" /></property><property name="albumdesc" type="string"><column name="albumdesc" length="65535" not-null="true" /></property><property name="albumcreatedate" type="date"><column name="albumcreatedate" length="10" not-null="true" /></property></class> </hibernate-mapping>Phototbl.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated Apr 22, 2013 1:26:40 PM by Hibernate Tools 3.4.0.CR1 --> <hibernate-mapping><class name="com.tctalk.apps.album.db.businessobjects.PhototblBO" table="phototbl" catalog="tctalk_apps_photoalbum"><id name="photoid" type="int"><column name="photoid" /><generator class="assigned" /></id><property name="albumid" type="int"><column name="albumid" not-null="true" /></property><property name="phototitle" type="string"><column name="phototitle" not-null="true" /></property><property name="photoname" type="string"><column name="photoname" not-null="true" /></property><property name="imgcontenttype" type="string"><column name="imgcontenttype" not-null="true" /></property><property name="photocreatedate" type="timestamp"><column name="photocreatedate" length="19" not-null="true" /></property><property name="photodata" type="binary"><column name="photodata" not-null="true" /></property></class> </hibernate-mapping>HibernateUtils.java
package com.tctalk.apps.album.utils;import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration;public class HibernateUtils {private static SessionFactory hbmSessionFactory;static {try {Configuration cfg = new Configuration().configure(PhotoAlbumConstant._HIBERNATE_CONFIG_LOCATION);hbmSessionFactory = cfg.buildSessionFactory();} catch (RuntimeException ex) {System.out.println("********* Error occurred while reading config file *********");ex.printStackTrace();}}/*** getSession creates hibernate Session & returns it*/public static Session getSession() {return hbmSessionFactory.openSession();}/*** closeSession closes the session, if it exists*/public static void closeSession(Session inSession) {if (inSession != null) {inSession.close();}} }PhotoAlbumConstant.java
package com.tctalk.apps.album.utils;public interface PhotoAlbumConstant {String _HIBERNATE_CONFIG_LOCATION = "hibernate.cfg.xml";String _HQL_DEL_PHOTOS_ALBUM = "DELETE FROM PhototblBO WHERE albumid= :albumid"; }PhotoAlbumAdminDao.java
package com.tctalk.apps.album.db.dao;import java.util.List;import com.tctalk.apps.album.db.businessobjects.AlbumBO; import com.tctalk.apps.album.db.businessobjects.PhototblBO;public interface PhotoAlbumAdminDao {// Photo Album related operationspublic List<AlbumBO> getAllPhotoAlbums(); public boolean addAlbum(AlbumBO album);public boolean delAlbum(int albumId);//Photo related operationspublic List<PhototblBO> getAllPhotosFromAlbum(int albumid);public boolean addPhotoToAlbum(PhototblBO photo);public boolean delPhotoFromAlbum(int photoid);public List<PhototblBO> getPhoto(int photoid); }PhotoAlbumAdminDaoImpl.java
package com.tctalk.apps.album.db.dao;import java.util.Date; import java.util.List;import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Restrictions;import com.tctalk.apps.album.db.businessobjects.AlbumBO; import com.tctalk.apps.album.db.businessobjects.PhototblBO; import com.tctalk.apps.album.utils.HibernateUtils; import com.tctalk.apps.album.utils.PhotoAlbumConstant;public class PhotoAlbumAdminDaoImpl implements PhotoAlbumAdminDao, PhotoAlbumConstant {/*** The below methods will be used for handling the Photo album related* operations* *//*** This function retrieves all the photo albums and send the list to the* front end*/public List<AlbumBO> getAllPhotoAlbums() {List<AlbumBO> albumList = null;Session hbmSession = null;try {hbmSession = HibernateUtils.getSession();Criteria criteria = hbmSession.createCriteria(AlbumBO.class);albumList = criteria.list();} catch (Exception ex) {ex.printStackTrace();} finally {HibernateUtils.closeSession(hbmSession);}return albumList;}/*** This function adds one photo album to the database*/public boolean addAlbum(AlbumBO album) {Session hbmSession = null;boolean STATUS_FLAG = true;try {hbmSession = HibernateUtils.getSession();hbmSession.beginTransaction();// change the creation date to today's date in the album objectalbum.setAlbumcreatedate(new Date());// add the album to the hibernate session to savehbmSession.save(album);hbmSession.getTransaction().commit();} catch (Exception ex) {hbmSession.getTransaction().rollback();ex.printStackTrace();STATUS_FLAG = false;} finally {HibernateUtils.closeSession(hbmSession);}return STATUS_FLAG;}/*** This function deletes the photoalbum based on the album id. It first* check if the album has any photos or not. If the album is not emptry then* it deletes the photos first and then delete the album itself*/public boolean delAlbum(int albumId) {Session hbmSession = null;boolean STATUS_FLAG = true;try {// get the hibernate session to perform delete operationhbmSession = HibernateUtils.getSession();hbmSession.beginTransaction();//delete all photos from the Photo table correspond to the album idQuery query = hbmSession.createQuery(_HQL_DEL_PHOTOS_ALBUM);query.setInteger("albumid", new Integer(albumId));int rowCount = query.executeUpdate();System.out.println("Rows affected: " + rowCount);//now load the album object from Album table and delete it correspond to the album idAlbumBO albumObj = (AlbumBO) hbmSession.load(AlbumBO.class, albumId);hbmSession.delete(albumObj);hbmSession.getTransaction().commit();} catch (Exception ex) {hbmSession.getTransaction().rollback();ex.printStackTrace();STATUS_FLAG = false;} finally {HibernateUtils.closeSession(hbmSession);}return STATUS_FLAG;}/*** The below functions will be helpful to work on the Photos in the photo* album*//*** This function retrieves all the photos and send the list to the front end*/public List<PhototblBO> getAllPhotosFromAlbum(int albumid) {List<PhototblBO> photoList = null;Session hbmSession = null;Criteria criteria = null;try {hbmSession = HibernateUtils.getSession();hbmSession.beginTransaction();// retrieve all photos from photo table correspond to the album Idcriteria = hbmSession.createCriteria(PhototblBO.class).add(Restrictions.eq("albumid", albumid));photoList = criteria.list();} catch (Exception ex) {ex.printStackTrace();} finally {HibernateUtils.closeSession(hbmSession);}return photoList;}/*** This function adds photo to the album*/public boolean addPhotoToAlbum(PhototblBO photoobj) {Session hbmSession = null;boolean STATUS_FLAG = true;try {hbmSession = HibernateUtils.getSession();hbmSession.beginTransaction();hbmSession.save(photoobj);hbmSession.getTransaction().commit();} catch (Exception ex) {hbmSession.getTransaction().rollback();ex.printStackTrace();STATUS_FLAG = false;} finally {HibernateUtils.closeSession(hbmSession);}return STATUS_FLAG;}/*** This function deletes the photo from the album itself*/public boolean delPhotoFromAlbum(int photoid) {Session hbmSession = null;boolean STATUS_FLAG = true;try {// get the hibernate session to perform delete operationhbmSession = HibernateUtils.getSession();hbmSession.beginTransaction();PhototblBO photoobj = (PhototblBO) hbmSession.load(PhototblBO.class, photoid);hbmSession.delete(photoobj);hbmSession.getTransaction().commit();} catch (Exception ex) {hbmSession.getTransaction().rollback();ex.printStackTrace();STATUS_FLAG = false;} finally {HibernateUtils.closeSession(hbmSession);}return STATUS_FLAG;}/*** This function returns the photo object itself*/public List<PhototblBO> getPhoto(int photoid) {List<PhototblBO> photoList = null;Session hbmSession = null;Criteria criteria = null;try {hbmSession = HibernateUtils.getSession();hbmSession.beginTransaction();// retrieve all photos from photo table correspond to the album Idcriteria = hbmSession.createCriteria(PhototblBO.class).add(Restrictions.eq("photoid", photoid));photoList = criteria.list();} catch (Exception ex) {ex.printStackTrace();} finally {HibernateUtils.closeSession(hbmSession);}return photoList;}}步驟6:開發UI部分
創建“ admin”文件夾,以保留所有與管理員相關的UI文件。 盡管我們的應用程序中沒有CSS或JavaScript文件,但我們仍將創建文件夾作為占位符。 我們將添加兩個jsp文件– showalbums.jsp –該文件將用于顯示現有相冊以及用于向數據庫中添加一個相冊的字段
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>TechcubeTalk.com - Let's build apps from scratch series - Personal Photo Album App</title> </head> <body> <h2>:: TechcubeTalk.com - Personal Photo Album Admin Panel ::</h2> <div style="margin-bottom: 25px;"> <s:form action="addAlbumAdmn" method="POST"><s:textfield label="Photo Album Name/Title" name="album.albumname"/><s:textfield label="Optional Brief Description" name="album.albumdesc"/><br/> <s:submit value="Create Photo Album" align="center"/> </s:form> <hr/> </div> <div><table style="border: 1px dotted black;"><tr><th style="background-color:#ABDCFF;" align="center"> Album Id </th><th style="background-color:#ABDCFF;" align="center"> Photo Album Title </th><th style="background-color:#ABDCFF;" align="center"> Brief Description </th><th style="background-color:#ABDCFF;" align="center"> Created On </th><th style="background-color:#ABDCFF;" align="center"> Delete? </th><th style="background-color:#ABDCFF;" align="center"> View Photos in Album </th></tr><s:iterator value="albumList" var="album"><tr><td align="center"><s:property value="albumid"/></td><td align="center"><s:property value="albumname"/></td><td align="center"><s:property value="albumdesc"/></td><td align="center"><s:property value="albumcreatedate"/></td><td align="center"> <a href="delAlbumAdmn.action?albumid=<s:property value="albumid"/>">Delete</a> </td><td align="center"> <a href="listPhotosByAlbumAdmn.action?albumid=<s:property value="albumid"/>">Click to View</a> </td></tr></s:iterator></table> </div> </body> </html>showphotos.jsp –此jsp將顯示用戶單擊的相冊下的所有照片。 它還會顯示要在該目錄下上傳照片的字段。
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>TechcubeTalk.com - Let's build apps from scratch series - Personal Music Manager Application</title> </head> <body> <h2>:: TechcubeTalk.com - Personal Photo Album Admin Panel ::</h2> <div style="margin-bottom: 25px;"> <s:form action="addPhotoAcion" namespace="/" method="POST" enctype="multipart/form-data"> <s:textfield label="Photo Title" name="photoTitle"/> <s:file name="fileUpload" label="Select a File to upload" size="40" /> <s:hidden name="albumid" value="%{albumid}" /><s:submit value="Upload Photo to Album" name="submit" /> </s:form></div> <div> <a href="listAlbumAdmn.action"><< Back to Albums</a></div> <div><table style="border: 1px dotted black;"><tr><th style="background-color:#ABDCFF;">Photo Id</th><th style="background-color:#ABDCFF;">Photo Title</th><th style="background-color:#ABDCFF;">Upload Date</th><th style="background-color:#ABDCFF;">View Photo</th><th style="background-color:#ABDCFF;">Delete Photo</th></tr><s:iterator value="photoList" var="photo"><tr><td><s:property value="photoid"/></td><td><s:property value="phototitle"/></td><td><s:property value="photocreatedate"/></td><td><a href="showPhotoAction.action?photoid=<s:property value="photoid"/>" target="_blank">View</a></td><td><a href="delPhotoFrmAlbumAdmn.action?albumid=<s:property value="albumid"/>&photoid=<s:property value="photoid"/>">Delete</a></td></tr></s:iterator></table> </div> </body> </html>步驟7:添加動作類和自定義結果類
PhotoAlbumAdminAction擴展了POJO PhotoAlbumForm.java,以保存UI頁面的提交表單字段和其他值。 我們使用一種自定義結果來顯示照片,方法是從BLOB字段數據庫中將其作為二進制文件獲取。
PhotoAlbumAdminAction.java
package com.tctalk.apps.album.web.actions;import java.io.IOException; import java.util.Date; import java.util.List;import org.apache.commons.io.FileUtils;import com.tctalk.apps.album.db.businessobjects.AlbumBO; import com.tctalk.apps.album.db.businessobjects.PhototblBO; import com.tctalk.apps.album.web.delegates.PhotoAlbumAdminDelegate; import com.tctalk.apps.album.web.forms.PhotoAlbumForm;public class PhotoAlbumAdminAction extends PhotoAlbumForm {private static final long serialVersionUID = 9168149105719285096L;private PhotoAlbumAdminDelegate delegate = new PhotoAlbumAdminDelegate();public String getAllAlbumList() {List<AlbumBO> albumList = delegate.getAllPhotoAlbums();String returnString = ERROR;if (albumList != null) {setAlbumList(albumList);returnString = SUCCESS;}return returnString;}public String addAlbumToCollection() {String returnString = ERROR;AlbumBO album = getAlbum();if (delegate.addAlbumToCollection(album)) {returnString = SUCCESS;}return returnString;}public String delAlbumFromCollection() {String returnString = ERROR;int albumId = getAlbumid();if (delegate.delAlbumFromCollection(albumId)) {returnString = SUCCESS;}return returnString;}public String listAllPhotos() {List<PhototblBO> photoList = delegate.getAllPhotos(this.getAlbumid());String returnString = ERROR;if (photoList != null) {this.setPhotoList(photoList);returnString = SUCCESS;}return returnString;}public String uploadPhotoToAlbum() {String returnString = ERROR;PhototblBO photoBO = new PhototblBO();// set the uploaded file meta data to the PhototblBO object before// saving to databasephotoBO.setAlbumid(getAlbumid());photoBO.setPhotocreatedate(new Date());photoBO.setImgcontenttype(getFileUploadContentType());photoBO.setPhotoname(getFileUploadFileName());photoBO.setPhototitle(getPhotoTitle());try {// the uploaded file is in File format so we need to convert to// byte[] array for storing in our database. For this apache //common file utility class is used below.photoBO.setPhotodata(FileUtils.readFileToByteArray(getFileUpload()));} catch (IOException e) {e.printStackTrace();}setPhotobo(photoBO);setAlbumid(photoBO.getAlbumid());if (delegate.addAPhoto(getPhotobo())) {returnString = SUCCESS;}return returnString;}public String delPhoto() {String returnString = ERROR;int photoId = getPhotoid();if (delegate.delPhoto(photoId)) {returnString = SUCCESS;}return returnString;}public String showPhoto() {String returnString = ERROR;List<PhototblBO> photoList = delegate.getPhoto(this.getPhotoid());if (photoList != null) {PhototblBO photoBO = (PhototblBO)photoList.get(0);if(photoBO != null){setPhotobo(photoBO);returnString = SUCCESS;}}return returnString;}}PhotoAlbumForm.java
package com.tctalk.apps.album.web.forms;import java.io.File; import java.util.List;import com.opensymphony.xwork2.ActionSupport; import com.tctalk.apps.album.db.businessobjects.AlbumBO; import com.tctalk.apps.album.db.businessobjects.PhototblBO;public class PhotoAlbumForm extends ActionSupport{private static final long serialVersionUID = 706337856877546963L;private List<AlbumBO> albumList = null;private List<PhototblBO> photoList = null;private AlbumBO album = null;private PhototblBO photobo = null;private File fileUpload;private String fileUploadContentType;private String fileUploadFileName;private String photoTitle;private int photoid;private int albumid;public String getFileUploadContentType() {return fileUploadContentType;}public void setFileUploadContentType(String fileUploadContentType) {this.fileUploadContentType = fileUploadContentType;}public String getFileUploadFileName() {return fileUploadFileName;}public void setFileUploadFileName(String fileUploadFileName) {this.fileUploadFileName = fileUploadFileName;}public File getFileUpload() {return fileUpload;}public void setFileUpload(File fileUpload) {this.fileUpload = fileUpload;}public String getPhotoTitle() {return photoTitle;}public void setPhotoTitle(String photoTitle) {this.photoTitle = photoTitle;}public List<AlbumBO> getAlbumList() {return albumList;}public void setAlbumList(List<AlbumBO> albumList) {this.albumList = albumList;}public List<PhototblBO> getPhotoList() {return photoList;}public void setPhotoList(List<PhototblBO> photoList) {this.photoList = photoList;}public AlbumBO getAlbum() {return album;}public void setAlbum(AlbumBO album) {this.album = album;}public PhototblBO getPhotobo() {return photobo;}public void setPhotobo(PhototblBO photobo) {this.photobo = photobo;}public int getPhotoid() {return photoid;}public void setPhotoid(int photoid) {this.photoid = photoid;}public int getAlbumid() {return albumid;}public void setAlbumid(int albumid) {this.albumid = albumid;} }CustomPhotoResult.java
package com.tctalk.apps.album.web.actions;import javax.servlet.http.HttpServletResponse;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.Result;public class CustomPhotoResult implements Result {private static final long serialVersionUID = 1L;public void execute(ActionInvocation invocation) throws Exception {PhotoAlbumAdminAction action = (PhotoAlbumAdminAction) invocation.getAction();HttpServletResponse response = ServletActionContext.getResponse();response.setContentType(action.getPhotobo().getImgcontenttype());response.setHeader("Content-Disposition", "inline; filename=\"" + action.getPhotobo().getPhotoname() + "\"");response.setHeader("cache-control", "no-cache");response.getOutputStream().write(action.getPhotobo().getPhotodata());response.getOutputStream().flush();response.getOutputStream().close();} }步驟8:添加委托類
委托類充當Struts2表示層和使用Hibernate開發的業務層之間的橋梁。
PhotoAlbumAdminDelegate.java
package com.tctalk.apps.album.web.delegates;import java.util.List;import com.tctalk.apps.album.db.businessobjects.AlbumBO; import com.tctalk.apps.album.db.businessobjects.PhototblBO; import com.tctalk.apps.album.db.dao.PhotoAlbumAdminDao; import com.tctalk.apps.album.db.dao.PhotoAlbumAdminDaoImpl;public class PhotoAlbumAdminDelegate {PhotoAlbumAdminDao admindao = (PhotoAlbumAdminDao) new PhotoAlbumAdminDaoImpl();// Photo Album related functionspublic List<AlbumBO> getAllPhotoAlbums() {return admindao.getAllPhotoAlbums();}public boolean addAlbumToCollection(AlbumBO album) {return admindao.addAlbum(album);}public boolean delAlbumFromCollection(int albumId) {return admindao.delAlbum(albumId);}//Only Photo related functionspublic List<PhototblBO> getAllPhotos(int albumId) {return admindao.getAllPhotosFromAlbum(albumId);}public boolean addAPhoto(PhototblBO photo) {return admindao.addPhotoToAlbum(photo);}public boolean delPhoto(int photoid) {return admindao.delPhotoFromAlbum(photoid);}public List<PhototblBO> getPhoto(int photoid) {return admindao.getPhoto(photoid);} }步驟9:最終整合
整個項目結構將類似于以下內容:
在struts.xml文件中,當我們從一個動作重定向到另一個動作時,我們需要傳遞相冊ID。 例如,將照片上傳到數據庫后,您需要重定向回到該相冊下的所有照片列表。 因此,添加照片后,我們還需要發回相冊。 為此,我們在struts.xml中使用$ {albumid}來傳遞POJO表單中的相冊。
項目完成后,從eclipse生成WAR文件。 為此,請右鍵單擊項目,然后選擇導出-> WAR文件以創建WAR文件并在Tomcat中進行部署。
如果您的部署成功,并且Tomcat控制臺中沒有錯誤消息(忽略任何警告,例如LOG4J等),則啟動瀏覽器并輸入URL – http:// localhost:8080 / PersonalPhotoAlbumApp / admin.action
這將調用管理面板,并且將顯示類別列表(第一次將不會顯示結果,因此繼續添加一個相冊)。
選擇“單擊以查看”進入“照片”頁面,您可以在該頁面中上傳照片或查看上傳的照片。
今天就這些。 在第二部分中,我將開發前端面板,該面板將使用jQuery,Struts2和Hibernate顯示相冊以及該相冊中的照片。
下載源文件:
我已經在上述步驟中提供了所有源代碼。 eclipse項目(帶有jar)和WAR文件上傳到GitHub存儲庫中。
翻譯自: https://www.javacodegeeks.com/2013/10/developing-a-personal-mini-photo-gallery-application-using-struts2-hibernate-and-mysql-blob-part-1.html
總結
以上是生活随笔為你收集整理的使用Struts2,Hibernate和MySQL BLOB开发个人迷你相册应用程序–第1部分的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 存款利率百分之四是啥意思?
- 下一篇: 存款保险制度50万包括利息吗?