使ç¨Struts2ï¼HibernateåMySQL BLOBå¼åä¸ªäººè¿·ä½ ç¸ååºç¨ç¨åºâ第1é¨å
æ¦è¿°ï¼
å¨æ¬ç 讨ä¼ä¸ï¼æ们å°å¼åä¸ä¸ª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 jarï¼mysql-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`) ) 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以è¿æ¥å°æ°æ®åº
- 使ç¨æ件å建POJOç±»ï¼å¹¶å°å ¶ä¿åå¨ä¸è¡¨ç¸å¯¹åºçå ä¸ã å¨æ们çåºç¨ç¨åºä¸ï¼æ们å°ä½¿ç¨ä¸¤ä¸ªè¡¨ç¸ååphototblï¼å æ¤æ们æ两个POJOç±»ã
- ç¶åæ·»å ä¸ä¸è¿°æ¥éª¤ä¸å建ç两个POJOç±»ç¸å¯¹åºçhbmæ件
- æ¥ä¸æ¥ï¼æ们å°æ·»å HibernateUtils.javaï¼ä»¥ä¾¿å¨æ们çåºç¨ç¨åºä¸è½»æ¾å¤çä¼ç ä¼è¯ã åæ ·å¨åä¸ä¸ªå ä¸ï¼æ们ä¿çä¸ä¸ªå¸¸éæ件ï¼ä»¥ä¿çæ们项ç®ä¸çææ常éã
- ç°å¨ï¼æ们å°æ·»å DAOç±»ï¼è¯¥ç±»å°å
·æä¸æ°æ®åºäº¤äºçæææ¹æ³ã
- ListgetAllPhotoAlbumsï¼ï¼âä»æ°æ®åºè¿åææç¸åçå表
- boolean addAlbumï¼AlbumBO albumï¼âè¿ä¼å°ä¸ä¸ªä¸è¾æ·»å å°æ°æ®åº
- boolean delAlbumï¼int albumIdï¼âå é¤ç¸å以å该ç¸åä¸çææç §ç
- ListgetAllPhotosFromAlbumï¼int albumidï¼âæ ¹æ®ç¸åIDè¿åç¸åä¸çææç §ç
- boolean addPhotoToAlbumï¼PhototblBO photoï¼âå°ç §ç对象添å å°ç¸å
- boolean delPhotoFromAlbumï¼int photoidï¼âä»ç¸åä¸å é¤ç §ç
- ListgetPhotoï¼int photoidï¼âè¿åè¦æ¾ç¤ºå¨é¡µé¢ä¸çç §ç对象
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.CR1 import 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.CR1 import 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 operations public List<AlbumBO> getAllPhotoAlbums(); public boolean addAlbum(AlbumBO album); public boolean delAlbum(int albumId); //Photo related operations public 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 object album.setAlbumcreatedate(new Date()); // add the album to the hibernate session to save hbmSession.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 operation hbmSession = HibernateUtils.getSession(); hbmSession.beginTransaction(); //delete all photos from the Photo table correspond to the album id Query 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 id AlbumBO 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 Id criteria = 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 operation hbmSession = 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 Id criteria = 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 database photoBO.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 functions public 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 functions public 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åå¨åºä¸ã