blob_使用Struts2,Hibernate和MySQL BLOB开发个人迷你相册应用程序–第1部分

blob

blob

概述:

在本研讨会中,我们将开发一个Web应用程序,可用于创建漂亮的照片库。 您可以将其托管在Web服务器中,也可以在自己的PC中使用以维护和管理照片集。 使用本教程,您将能够了解与Struts2和Hibernate相关的以下重要知识:

  • 如何将Struts2框架与Hibernate集成
  • 如何在Struts2中上传照片或文件
  • 如何在MySQL BLOB字段之间动态上传/下载照片
  • 如何在Struts2中将参数从一个动作动态传递到另一个动作

在本教程的第1部分中,我们将开发管理面板。 管理面板将用于创建相册并将照片上传到相册。 在第2部分中,我们将创建前端主Web应用程序,该应用程序将按管理面板中添加的相册显示照片。

使用的工具:

  1. 面向Web开发人员的Eclipse Indigo Java EE IDE
  2. Struts2
  3. Hibernate3
  4. Hibernate Tools Eclipse插件版本3.5.1
  5. mysql JDBC jar(mysql-connector-java-5.1.23)
  6. Tomcat7

步骤1:为照片库应用程序准备数据库MySQL

我们将使用MySQL数据库。 Belw是用于您创建数据库表的脚本。 使用的数据库名称是'tctalk_apps_photoalbum'。 但是,您可以创建任何数据库名称。 只要记住您需要在Hibernate配置文件中更改数据库名称即可。 以下是两个表Album和phototblSQL。

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包含用于在数据库/Hibernate端工作的所有Java和其他文件,而com.tctalk.apps.album.web.xxx将具有使用struts2的表示层的所有Java文件。框架。

image001

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文件夹中

image003

您需要从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插件/

  1. 使用数据库连接信息创建hibernate.cfg.xml以连接到数据库
  2. 使用插件创建POJO类,并将其保存在与表相对应的包中。 在我们的应用程序中,我们将使用两个表格相册和phototbl,因此我们有两个POJO类。
  3. 然后添加与上述步骤中创建的两个POJO类相对应的hbm文件
  4. 接下来,我们将添加HibernateUtils.java,以在我​​们的应用程序中轻松处理Hibernate会话。 同样,在同一包中,我们保留一个常量文件,以保留我们项目中的所有常量。
  5. 现在,我们将添加DAO类,该类将具有与数据库交互的所有方法。
    1. ListgetAllPhotoAlbums()–从数据库返回所有相册的列表
    2. boolean addAlbum(AlbumBO album)–这会将一个相册添加到数据库
    3. boolean delAlbum(int albumId)–删除相册以及该相册下的所有照片
    4. ListgetAllPhotosFromAlbum(int albumid)–根据相册ID返回相册中的所有照片
    5. boolean addPhotoToAlbum(PhototblBO photo)–将照片对象添加到相册
    6. boolean delPhotoFromAlbum(int photoid)–从相册中删除照片
    7. 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:最终整合

整个项目结构将类似于以下内容:

image005

在struts.xml文件中,当我们从一个动作重定向到另一个动作时,我们需要传递相册ID。 例如,将照片上传到数据库后,您需要重定向回到该相册下的所有照片列表。 因此,添加照片后,我们还需要发回相册。 为此,我们在struts.xml中使用$ {albumid}来传递POJO表单中的相册。

项目完成后,从eclipse生成WAR文件。 为此,请右键单击项目,然后选择“导出”->“ WAR文件”以创建WAR文件并在Tomcat中进行部署。

如果您的部署成功,并且Tomcat控制台中没有错误消息(忽略任何警告,例如LOG4J等),则启动浏览器并输入URL – http:// localhost:8080 / PersonalPhotoAlbumApp / admin.action

这将调用管理面板并显示类别列表(第一次将不会显示任何结果,因此继续添加一个相册)。

image007

选择“单击以查看”进入“照片”页面,您可以在该页面中上传照片或查看上传的照片。

image009

今天就这些。 在第二部分中,我将开发前端面板,该面板将使用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

blob

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值