开个网站做代理,公司介绍简介,陕西省建设工程造价管理协会网站,WordPress 陈星概述#xff1a; 在本研讨会中#xff0c;我们将开发一个Web应用程序#xff0c;可用于创建漂亮的照片库。 您可以将其托管在Web服务器中#xff0c;也可以在自己的PC中使用以维护和管理照片集。 使用本教程#xff0c;您将能够了解与Struts2和Hibernate相关的以下重要内容… 概述 在本研讨会中我们将开发一个Web应用程序可用于创建漂亮的照片库。 您可以将其托管在Web服务器中也可以在自己的PC中使用以维护和管理照片集。 使用本教程您将能够了解与Struts2和Hibernate相关的以下重要内容 如何将Struts2框架与Hibernate集成 如何在Struts2中上传照片或文件 如何在MySQL BLOB字段之间动态上传/下载照片 如何在Struts2中将参数从一个动作动态传递给另一个动作 在本教程的第1部分中我们将开发管理面板。 管理面板将用于创建相册并将照片上传到相册。 在第2部分中我们将创建前端主Web应用程序该应用程序将按管理面板中添加的相册显示照片。 使用的工具 面向Web开发人员的Eclipse Indigo Java EE IDE Struts2 休眠3 Hibernate Tools Eclipse插件版本3.5.1 mysql JDBC jarmysql-connector-java-5.1.23 雄猫7 步骤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)
) ENGINEInnoDB DEFAULT CHARSETlatin1;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)
) ENGINEInnoDB DEFAULT CHARSETlatin1;步骤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 version1.0 encodingUTF-8?
web-app idWebApp_ID version2.4 xmlnshttp://java.sun.com/xml/ns/j2ee xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocationhttp://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd
display-namePersonalPhotoAlbumApp/display-namewelcome-file-listwelcome-fileindex.jsp/welcome-file/welcome-file-listfilterfilter-namestruts2/filter-namefilter-classorg.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter/filter-class
/filter
filter-mappingfilter-namestruts2/filter-nameurl-pattern*.action/url-pattern
/filter-mapping
/web-app Struts.xml ?xml version1.0 encodingUTF-8?
!DOCTYPE struts PUBLIC-//Apache Software Foundation//DTD Struts Configuration 2.0//ENhttp://struts.apache.org/dtds/struts-2.0.dtdstrutsconstant namestruts.enable.DynamicMethodInvocation valuefalse /constant namestruts.devMode valuefalse /package namedefault extendsstruts-default namespace/result-typesresult-type nameimageResult classcom.tctalk.apps.album.web.actions.CustomPhotoResult //result-typesdefault-action-ref nameindex /action nameindexresultindex.jsp/result/actionaction nameadminresult namesuccess typeredirectActionlistAlbumAdmn/result/actionaction namelistAlbumAdmn classcom.tctalk.apps.album.web.actions.PhotoAlbumAdminAction methodgetAllAlbumList result namesuccess/WEB-INF/admin/jsp/showalbums.jsp/result/actionaction nameaddAlbumAdmn class com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction methodaddAlbumToCollection result nameinputlistAlbumAdmn/resultresult namesuccess typeredirectActionlistAlbumAdmn/result/actionaction namedelAlbumAdmn class com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction methoddelAlbumFromCollection result namesuccess typeredirectActionlistAlbumAdmn/result/actionaction namelistPhotosByAlbumAdmn classcom.tctalk.apps.album.web.actions.PhotoAlbumAdminAction methodlistAllPhotos result namesuccess/WEB-INF/admin/jsp/showphotos.jsp/result/actionaction nameaddPhotoAcion class com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction methoduploadPhotoToAlbum interceptor-ref nameexception/interceptor-ref namei18n/interceptor-ref namefileUploadparam nameallowedTypesimage/x-png,image/png,image/gif,image/jpeg,image/pjpeg/param/interceptor-ref interceptor-ref nameparamsparam nameexcludeParamsdojo\..*,^struts\..*/param/interceptor-refinterceptor-ref namevalidationparam nameexcludeMethodsinput,back,cancel,browse/param/interceptor-refinterceptor-ref nameworkflowparam nameexcludeMethodsinput,back,cancel,browse/param/interceptor-refresult namesuccess typeredirectActionparam nameactionNamelistPhotosByAlbumAdmn/paramparam namealbumid${albumid}/param/resultresult nameinput/WEB-INF/admin/jsp/showphotos.jsp/result/actionaction namedelPhotoFrmAlbumAdmn class com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction methoddelPhoto result namesuccess typeredirectActionparam nameactionNamelistPhotosByAlbumAdmn/paramparam namealbumid${albumid}/param/result/actionaction nameshowPhotoAction classcom.tctalk.apps.album.web.actions.PhotoAlbumAdminAction methodshowPhotoresult namesuccess typeimageResult//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以连接到数据库 使用插件创建POJO类并将其保存在与表相对应的包中。 在我们的应用程序中我们将使用两个表相册和phototbl因此我们有两个POJO类。 然后添加与上述步骤中创建的两个POJO类相对应的hbm文件 接下来我们将添加HibernateUtils.java以便在我们的应用程序中轻松处理休眠会话。 同样在同一个包中我们保留一个常量文件以保留我们项目中的所有常量。 现在我们将添加DAO类该类将具有与数据库交互的所有方法。 ListgetAllPhotoAlbums–从数据库返回所有相册的列表 boolean addAlbumAlbumBO album–这会将一个专辑添加到数据库 boolean delAlbumint albumId–删除相册以及该相册下的所有照片 ListgetAllPhotosFromAlbumint albumid–根据相册ID返回相册中的所有照片 boolean addPhotoToAlbumPhototblBO photo–将照片对象添加到相册 boolean delPhotoFromAlbumint photoid–从相册中删除照片 ListgetPhotoint photoid–返回要显示在页面中的照片对象 hibernate.cfg.xml ?xml version1.0 encodingUTF-8?
!DOCTYPE hibernate-configuration PUBLIC-//Hibernate/Hibernate Configuration DTD 3.0//ENhttp://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd
hibernate-configurationsession-factoryproperty namehibernate.connection.driver_classcom.mysql.jdbc.Driver/propertyproperty namehibernate.connection.urljdbc:mysql://localhost:3306/tctalk_apps_photoalbum/propertyproperty namehibernate.connection.usernameroot/propertyproperty namehibernate.connection.password/propertyproperty namehibernate.dialectorg.hibernate.dialect.MySQLDialect/propertyproperty nameshow_sqltrue/propertymapping resourcecom/tctalk/apps/album/db/hbm/Album.hbm.xml /mapping resourcecom/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 version1.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-mappingclass namecom.tctalk.apps.album.db.businessobjects.AlbumBO tablealbum catalogtctalk_apps_photoalbumid namealbumid typejava.lang.Integercolumn namealbumid /generator classidentity //idproperty namealbumname typestringcolumn namealbumname length55 not-nulltrue //propertyproperty namealbumdesc typestringcolumn namealbumdesc length65535 not-nulltrue //propertyproperty namealbumcreatedate typedatecolumn namealbumcreatedate length10 not-nulltrue //property/class
/hibernate-mapping Phototbl.hbm.xml ?xml version1.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-mappingclass namecom.tctalk.apps.album.db.businessobjects.PhototblBO tablephototbl catalogtctalk_apps_photoalbumid namephotoid typeintcolumn namephotoid /generator classassigned //idproperty namealbumid typeintcolumn namealbumid not-nulltrue //propertyproperty namephototitle typestringcolumn namephototitle not-nulltrue //propertyproperty namephotoname typestringcolumn namephotoname not-nulltrue //propertyproperty nameimgcontenttype typestringcolumn nameimgcontenttype not-nulltrue //propertyproperty namephotocreatedate typetimestampcolumn namephotocreatedate length19 not-nulltrue //propertyproperty namephotodata typebinarycolumn namephotodata not-nulltrue //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 ListAlbumBO getAllPhotoAlbums(); public boolean addAlbum(AlbumBO album);public boolean delAlbum(int albumId);//Photo related operationspublic ListPhototblBO getAllPhotosFromAlbum(int albumid);public boolean addPhotoToAlbum(PhototblBO photo);public boolean delPhotoFromAlbum(int photoid);public ListPhototblBO 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 ListAlbumBO getAllPhotoAlbums() {ListAlbumBO 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 todays 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 ListPhototblBO getAllPhotosFromAlbum(int albumid) {ListPhototblBO 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 ListPhototblBO getPhoto(int photoid) {ListPhototblBO 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 languagejava contentTypetext/html; charsetISO-8859-1pageEncodingISO-8859-1%
% taglib prefixs 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-equivContent-Type contenttext/html; charsetISO-8859-1
titleTechcubeTalk.com - Lets build apps from scratch series - Personal Photo Album App/title
/head
body
h2:: TechcubeTalk.com - Personal Photo Album Admin Panel ::/h2
div stylemargin-bottom: 25px;
s:form actionaddAlbumAdmn methodPOSTs:textfield labelPhoto Album Name/Title namealbum.albumname/s:textfield labelOptional Brief Description namealbum.albumdesc/br/ s:submit valueCreate Photo Album aligncenter/
/s:form
hr/
/div
divtable styleborder: 1px dotted black;trth stylebackground-color:#ABDCFF; aligncenter Album Id /thth stylebackground-color:#ABDCFF; aligncenter Photo Album Title /thth stylebackground-color:#ABDCFF; aligncenter Brief Description /thth stylebackground-color:#ABDCFF; aligncenter Created On /thth stylebackground-color:#ABDCFF; aligncenter Delete? /thth stylebackground-color:#ABDCFF; aligncenter View Photos in Album /th/trs:iterator valuealbumList varalbumtrtd aligncenters:property valuealbumid//tdtd aligncenters:property valuealbumname//tdtd aligncenters:property valuealbumdesc//tdtd aligncenters:property valuealbumcreatedate//tdtd aligncenter a hrefdelAlbumAdmn.action?albumids:property valuealbumid/Delete/a /tdtd aligncenter a hreflistPhotosByAlbumAdmn.action?albumids:property valuealbumid/Click to View/a /td/tr/s:iterator/table
/div
/body
/html showphotos.jsp –此jsp将显示用户单击的相册下的所有照片。 它还会显示要在该目录下上传照片的字段。 % page languagejava contentTypetext/html; charsetISO-8859-1pageEncodingISO-8859-1%
% taglib prefixs 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-equivContent-Type contenttext/html; charsetISO-8859-1
titleTechcubeTalk.com - Lets build apps from scratch series - Personal Music Manager Application/title
/head
body
h2:: TechcubeTalk.com - Personal Photo Album Admin Panel ::/h2
div stylemargin-bottom: 25px;
s:form actionaddPhotoAcion namespace/ methodPOST enctypemultipart/form-data
s:textfield labelPhoto Title namephotoTitle/
s:file namefileUpload labelSelect a File to upload size40 /
s:hidden namealbumid value%{albumid} /s:submit valueUpload Photo to Album namesubmit /
/s:form/div
div a hreflistAlbumAdmn.action Back to Albums/a/div
divtable styleborder: 1px dotted black;trth stylebackground-color:#ABDCFF;Photo Id/thth stylebackground-color:#ABDCFF;Photo Title/thth stylebackground-color:#ABDCFF;Upload Date/thth stylebackground-color:#ABDCFF;View Photo/thth stylebackground-color:#ABDCFF;Delete Photo/th/trs:iterator valuephotoList varphototrtds:property valuephotoid//tdtds:property valuephototitle//tdtds:property valuephotocreatedate//tdtda hrefshowPhotoAction.action?photoids:property valuephotoid/ target_blankView/a/tdtda hrefdelPhotoFrmAlbumAdmn.action?albumids:property valuealbumid/photoids:property valuephotoid/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() {ListAlbumBO 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() {ListPhototblBO 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;ListPhototblBO 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 ListAlbumBO albumList null;private ListPhototblBO 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 ListAlbumBO getAlbumList() {return albumList;}public void setAlbumList(ListAlbumBO albumList) {this.albumList albumList;}public ListPhototblBO getPhotoList() {return photoList;}public void setPhotoList(ListPhototblBO 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 ListAlbumBO 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 ListPhototblBO 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 ListPhototblBO getPhoto(int photoid) {return admindao.getPhoto(photoid);}
}步骤9最终整合 整个项目结构将类似于以下内容 在struts.xml文件中当我们从一个动作重定向到另一个动作时我们需要传递相册ID。 例如将照片上传到数据库后您需要重定向回到该相册下的所有照片列表。 因此添加照片后我们还需要发回相册。 为此我们在struts.xml中使用$ {albumid}来传递POJO表单中的相册。 项目完成后从eclipse生成WAR文件。 为此请右键单击项目然后选择导出- WAR文件以创建WAR文件并在Tomcat中进行部署。 如果您的部署成功并且Tomcat控制台中没有错误消息忽略任何警告例如LOG4J等则启动浏览器并输入URL – http// localhost8080 / PersonalPhotoAlbumApp / admin.action 这将调用管理面板并且将显示类别列表第一次将不会显示结果因此继续添加一个相册。 选择“单击以查看”进入“照片”页面您可以在该页面中上传照片或查看上传的照片。 今天就这些。 在第二部分中我将开发前端面板该面板将使用jQueryStruts2和Hibernate显示相册以及该相册中的照片。 下载源文件 我已经在上述步骤中提供了所有源代码。 eclipse项目带有jar和WAR文件上传到GitHub存储库中。 参考 使用Struts2Hibernate和MySQL BLOB开发个人迷你照片库应用程序–来自我们JCG合作伙伴 Suvoraj Biswas的第1部分 在TechCubeTalk博客上。 翻译自: https://www.javacodegeeks.com/2013/10/developing-a-personal-mini-photo-gallery-application-using-struts2-hibernate-and-mysql-blob-part-1.html