程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA編程入門知識 >> 基於spring+hibernate+JQuery開發之電子相冊(附源碼下載)

基於spring+hibernate+JQuery開發之電子相冊(附源碼下載)

編輯:JAVA編程入門知識

項目結構:

項目首頁:

注冊頁面:

上傳圖片:

效果圖一:

效果圖二:

效果圖三:

=============================================================

下面是代碼部分

=============================================================

需要用到的數據庫SQL:
代碼如下:

drop database if exists db_ajax;

 create database db_ajax;

 use db_ajax;

 create table user_table
 (
  user_id int auto_increment primary key,
  name varchar(255) unique,
  pass varchar(255)
 );

 create table photo_table
 (
  photo_id int auto_increment primary key,
  title varchar(255),
  fileName varchar(255),
  owner_id int,
  foreign key(owner_id) references user_table(user_id)
 );

/ajax_0500_jQuery_album/WebRoot/album.html
代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
     <title> 電子相冊系統 </title>
     <meta http-equiv="Content-Type" content="text/html; charset=GBK" />
     <link rel="stylesheet" href="css/flora.dialog.css" type="text/css" />
     <link rel="stylesheet" href="css/flora.resizable.css" type="text/css" />
     <link rel="stylesheet" href="css/flora.draggable.css" type="text/css" />
     <link rel="stylesheet" href="css/flora.css" type="text/css" />
     <link rel="stylesheet" href="css/album.css" type="text/css" />
     <script type="text/javascript" src="js/jquery-1.2.6.min.js"></script>
     <script type="text/javascript" src="js/ui.core.js"></script>
     <script type="text/javascript" src="js/ui.dialog.js"></script>
     <script type="text/javascript" src="js/ui.resizable.js"></script>
     <script type="text/javascript" src="js/ui.draggable.js"></script>
     <script type="text/javascript" src="js/album.js"></script>
 </head>
 <body class="flora">
 <table width="780" cellspacing="1" >
 <caption><h3>電子相冊系統</h3></caption>
 <tr>
 <td height="60" colspan="2">
 <!-- 沒有登錄顯示下面div元素 -->
 <div id="noLogin">
 <!-- 這裡是注冊/登錄的表格 -->
 <table width="100%" cellspacing="0">
 <tr>
     <td width="38%">用戶名:
         <input id="user" type="text" name="user" /></td>
     <td width="38%">密  碼:
         <input id="pass" type="text" name="pass" /></td>
     <td width="24%">我還沒有注冊,請讓我<a href="javascript:void(0);"
         onclick="changeRegist();">注冊</a></td>
 </tr>
 <tr>
     <td colspan="5">
     <div id="loginDiv" >
     <input id="login" type="button" onclick="proLogin();" value="登錄" />
     <input id="resetLogin" type="button" onclick="reset();" value="重設" />
     </div>
     <div id="registDiv" >
     <a href="javascript:void(0)" onclick="validateName();">驗證用戶名是否可用</a>
     <input id="regist" type="button" onclick="regist();" value="注冊" />
     <input id="resetRegist" type="button" onclick="reset();" value="重設" />
     </div>
     </td>
 </tr>
 </table>
 </div>
 <!-- 已經登錄顯示下面div元素 -->
 <div id="hasLogin" >
     您已經登錄成功,下面是您的相冊,您也可以<a href="javascript:void(0);"
         onclick="openUpload();">增加相片</a>
 </div>
 </td>
 </tr>
 <tr>
     <!-- 顯示相片列表的元素 -->
     <td width="120" height="440" valign="top">
     <div ><h3>相片列表</h3></div>
     <div id="list"></div><hr />
     <div ><a href="javascript:void(0);" onclick="turnPage(-1);">上一頁</a>
          <a href="javascript:void(0);" onclick="turnPage(1);">下一頁</a></div>
     </td>
     <!-- 顯示相片的元素 -->
     <td width="660" valign="middle">
         <div >
         <img id="show" alt=""></img></div></td>
 </tr>
 </table>

 <div id="uploadDiv" >
 <form action="proUpload" method="post"
     enctype="multipart/form-data">
 <table width="400" cellspacing="1" cellpadding="10">
 <caption>上傳圖片</caption>
 <tr>
     <td height="25">圖片標題:</td>
     <td><input id="title" name="title" type="text" /></td>
 </tr>
 <tr>
     <td height="25">浏覽圖片:</td>
     <td><input id="file" name="file" type="file" /></td>
 </tr>
 <tr>
     <td colspan="2" >
     <input type="submit" value="上傳" />
     <input type="reset" value="重設" />
     </td>
 </tr>
 </table>
 </form>
 </div>
 <div id="tipDiv" >
 </div>
 </body>
 </html>

/ajax_0500_jQuery_album/WebRoot/WEB-INF/web.xml
代碼如下:

<?xml version="1.0" encoding="GBK"?>
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     version="2.5">

     <!-- 配置Web應用啟動時候加載Spring容器 -->
     <listener>
         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
     </listener>

     <servlet>
         <servlet-name>proLogin</servlet-name>
         <servlet-class>com.b510.album.web.ProLoginServlet</servlet-class>
     </servlet>
     <servlet-mapping>
         <servlet-name>proLogin</servlet-name>
         <url-pattern>/proLogin</url-pattern>
     </servlet-mapping>

     <servlet>
         <servlet-name>proRegist</servlet-name>
         <servlet-class>com.b510.album.web.ProRegistServlet</servlet-class>
     </servlet>
     <servlet-mapping>
         <servlet-name>proRegist</servlet-name>
         <url-pattern>/proRegist</url-pattern>
     </servlet-mapping>

     <servlet>
         <servlet-name>validateName</servlet-name>
         <servlet-class>com.b510.album.web.ValidateNameServlet</servlet-class>
     </servlet>
     <servlet-mapping>
         <servlet-name>validateName</servlet-name>
         <url-pattern>/validateName</url-pattern>
     </servlet-mapping>

     <servlet>
         <servlet-name>getPhoto</servlet-name>
         <servlet-class>com.b510.album.web.GetPhotoServlet</servlet-class>
     </servlet>
     <servlet-mapping>
         <servlet-name>getPhoto</servlet-name>
         <url-pattern>/getPhoto</url-pattern>
     </servlet-mapping>

     <servlet>
         <servlet-name>showImg</servlet-name>
         <servlet-class>com.b510.album.web.ShowImgServlet</servlet-class>
     </servlet>
     <servlet-mapping>
         <servlet-name>showImg</servlet-name>
         <url-pattern>/showImg</url-pattern>
     </servlet-mapping>

     <servlet>
         <servlet-name>pageLoad</servlet-name>
         <servlet-class>com.b510.album.web.PageLoadServlet</servlet-class>
     </servlet>
     <servlet-mapping>
         <servlet-name>pageLoad</servlet-name>
         <url-pattern>/pageLoad</url-pattern>
     </servlet-mapping>

     <servlet>
         <servlet-name>turnPage</servlet-name>
         <servlet-class>com.b510.album.web.TurnPageServlet</servlet-class>
     </servlet>
     <servlet-mapping>
         <servlet-name>turnPage</servlet-name>
         <url-pattern>/turnPage</url-pattern>
     </servlet-mapping>

     <servlet>
         <servlet-name>proUpload</servlet-name>
         <servlet-class>com.b510.album.web.ProUploadServlet</servlet-class>
     </servlet>
     <servlet-mapping>
         <servlet-name>proUpload</servlet-name>
         <url-pattern>/proUpload</url-pattern>
     </servlet-mapping>

     <welcome-file-list>
         <welcome-file>album.html</welcome-file>
     </welcome-file-list>

 </web-app>

/ajax_0500_jQuery_album/WebRoot/WEB-INF/applicationContext.xml
代碼如下:

<?xml version="1.0" encoding="GBK"?>
 <!-- 指定Spring配置文件的Schema信息 -->
 <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:aop="http://www.springframework.org/schema/aop"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     http://www.springframework.org/schema/tx
     http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

     <!-- 定義數據源Bean,使用C3P0數據源實現 -->
     <bean id="dataSource" destroy-method="close"
         class="com.mchange.v2.c3p0.ComboPooledDataSource">
         <!-- 指定連接數據庫的驅動 -->
         <property name="driverClass" value="com.mysql.jdbc.Driver"/>
         <!-- 指定連接數據庫的URL -->
         <property name="jdbcUrl"
             value="jdbc:mysql://localhost:3308/db_ajax"/>
         <!-- 指定連接數據庫的用戶名 -->
         <property name="user" value="root"/>
         <!-- 指定連接數據庫的密碼 -->
         <property name="password" value="root"/>
         <!-- 指定連接數據庫連接池的最大連接數 -->
         <property name="maxPoolSize" value="40"/>
         <!-- 指定連接數據庫連接池的最小連接數 -->
         <property name="minPoolSize" value="1"/>
         <!-- 指定連接數據庫連接池的初始化連接數 -->
         <property name="initialPoolSize" value="1"/>
         <!-- 指定連接數據庫連接池的連接的最大空閒時間 -->
         <property name="maxIdleTime" value="20"/>
     </bean>

     <!-- 定義Hibernate的SessionFactory -->
     <bean id="sessionFactory"
         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
         <!-- 依賴注入數據源,注入上面定義的dataSource -->
         <property name="dataSource" ref="dataSource"/>
         <!-- mappingResouces屬性用來列出全部映射文件 -->
         <property name="mappingResources">
             <list>
                 <!-- 以下用來列出Hibernate映射文件 -->
                 <value>com/b510/album/model/User.hbm.xml</value>
                 <value>com/b510/album/model/Photo.hbm.xml</value>
             </list>
         </property>
         <!-- 定義Hibernate的SessionFactory的屬性 -->
         <property name="hibernateProperties">
             <props>
                 <!-- 指定數據庫方言 -->
                 <prop key="hibernate.dialect">
                     org.hibernate.dialect.MySQLInnoDBDialect</prop>
                 <!-- 是否根據需要每次自動創建數據庫 -->
                 <prop key="hibernate.hbm2ddl.auto">update</prop>
                 <!-- 顯示Hibernate持久化操作所生成的SQL -->
                 <prop key="hibernate.show_sql">true</prop>
                 <!-- 將SQL腳本進行格式化後再輸出 -->
                 <prop key="hibernate.format_sql">true</prop>
             </props>
         </property>
     </bean>
     <!-- 配置UserDao組件 -->
     <bean id="userDao"
         class="com.b510.album.dao.impl.UserDaoHibernate">
         <!-- 注入SessionFactory引用 -->
         <property name="sessionFactory" ref="sessionFactory"/>
     </bean>
     <!-- 配置PhotoDao組件 -->
     <bean id="photoDao"
         class="com.b510.album.dao.impl.PhotoDaoHibernate">
         <property name="sessionFactory" ref="sessionFactory"/>
     </bean>
     <!-- 配置albumService業務邏輯組件 -->
     <bean id="albumService"
         class="com.b510.album.service.impl.AlbumServiceImpl">
         <!-- 為業務邏輯組件注入2個DAO組件 -->
         <property name="userDao" ref="userDao"/>
         <property name="photoDao" ref="photoDao"/>
     </bean>

     <!-- 配置Hibernate的局部事務管理器,使用HibernateTransactionManager類 -->
     <!-- 該類實現PlatformTransactionManager接口,是針對Hibernate的特定實現-->
     <bean id="transactionManager"
         class="org.springframework.orm.hibernate3.HibernateTransactionManager">
         <!-- 配置HibernateTransactionManager時需要依注入SessionFactory的引用 -->
         <property name="sessionFactory" ref="sessionFactory"/>
     </bean>

     <!-- 配置事務切面Bean,指定事務管理器 -->
     <tx:advice id="txAdvice" transaction-manager="transactionManager">
         <!-- 用於配置詳細的事務語義 -->
         <tx:attributes>
             <!-- 所有以'get'開頭的方法是read-only的 -->
             <tx:method name="get*" read-only="true"/>
             <!-- 其他方法使用默認的事務設置 -->
             <tx:method name="*"/>
         </tx:attributes>
     </tx:advice>
     <aop:config>
         <!-- 配置一個切入點,匹配lee包下所有以Impl結尾的類執行的所有方法 -->
         <aop:pointcut id="leeService"
             expression="execution(* com.b510.album.service.impl.*Impl.*(..))"/>
         <!-- 指定在leeService切入點應用txAdvice事務切面 -->
         <aop:advisor advice-ref="txAdvice"
             pointcut-ref="leeService"/>
     </aop:config>
 </beans>

/ajax_0500_jQuery_album/WebRoot/js/album.js
代碼如下:

$(document).ready(function(){
     $.getScript("pageLoad");
     //處理地址欄的resultCode參數
     var locationStr = document.location.toString();
     var resultIndex = locationStr.indexOf("resultCode");
     var resultCode = -1;
     if (resultIndex > 1)
     {
         resultCode = locationStr.substring(resultIndex + 11
             , resultIndex + 12);
         //根據不同的resultCode,系統進行不同處理
         switch(resultCode)
         {
             case "0" :
                 alert('恭喜你,上傳文件成功!');
                 $('#uploadDiv').dialog('close');
                 break;
             case "1" :
                 alert('本系統只允許上傳JPG、GIF、PNG圖片文件,請重試!');
                 $('#title,#file').val('');
                 break;
             case "2" :
                 alert('處理上傳文件出現錯誤,請重試!');
                 $('#title,#file').val('');
                 break;
         }
     }
 });

 function reset()
 {
     //清空user、pass兩個單行文本框
     $("#user").val("");
     $("#pass").val("");
 }

 //切換到注冊對話框
 function changeRegist()
 {
     //隱藏登錄用的兩個按鈕
     $("#loginDiv").hide("500");
     //顯示注冊用的兩個按鈕
     $("#registDiv").show("500");
 }

 //處理用戶登錄的函數
 function proLogin()
 {
     //獲取user、pass兩個文本框的值
     var user = $.trim($("#user").val());
     var pass = $.trim($("#pass").val());
     if (user == null || user == ""
         || pass == null|| pass =="")
     {
         alert("必須先輸入用戶名和密碼才能登錄");
         return false;
     }
     else
     {
         //向proLogin發送異步、POST請求
         $.post("proLogin", $('#user,#pass').serializeArray()
             , null , "script");
     }
 }

 //處理用戶注冊的函數
 function regist()
 {
     //獲取user、pass兩個文本框的值
     var user = $.trim($("#user").val());
     var pass = $.trim($("#pass").val());
     if (user == null || user == "" || pass == null || pass =="")
     {
         alert("必須先輸入用戶名和密碼才能注冊");
         return false;
     }
     else
     {
         //向proRegist發送異步、POST請求
         $.post("proRegist", $('#user,#pass').serializeArray()
             , null , "script");
     }
 }

 //驗證用戶名是否可用
 function validateName()
 {
     //獲取user文本框的值
     var user = $.trim($("#user").val());
     if (user == null || user == "")
     {
         alert("您還沒有輸入用戶名!");
         return false;
     }
     else
     {
         //向validateName發送異步、POST請求
         $.post("validateName", $('#user').serializeArray()
             , null , "script");
     }
 }

 //周期性地獲取當前用戶、當前頁的相片
 function onLoadHandler()
 {
     //向getPhoto發送異步、GET請求
     $.getScript("getPhoto");
     //指定1秒之後再次執行此方法
     setTimeout("onLoadHandler()", 1000);
 }

 //顯示照片
 function showImg(fileName)
 {
     $.getScript("showImg?img=" + fileName);
 //    document.getElementById("show").src="uploadfiles/" + fileName + "?now=" + new Date();
 //    $("#show").attr("src" , "uploadfiles/" + fileName);
 }

 //處理翻頁的函數
 function turnPage(flag)
 {
     $.getScript("turnPage?turn=" + flag);
 }

 //打開上傳窗口
 function openUpload()
 {

     $("#uploadDiv").show()
         .dialog(
         {
             modal: true,
             resizable: false,
             width: 428,
             height: 220,
             overlay: {opacity: 0.5 , background: "black"}
         });
 }

/ajax_0500_jQuery_album/src/com/b510/album/web/base/BaseServlet.java
代碼如下:

package com.b510.album.web.base;

 import javax.servlet.ServletConfig;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;

 import org.springframework.context.ApplicationContext;
 import org.springframework.web.context.support.WebApplicationContextUtils;

 import com.b510.album.service.AlbumService;
 /**
  *
  * @author Hongten
  *
  */
 public class BaseServlet extends HttpServlet {

     private static final long serialVersionUID = -2041755371540813745L;

     protected AlbumService as;

     // 定義構造器,獲得Spring容器的引用
     public void init(ServletConfig config) throws ServletException {
         super.init(config);
         ApplicationContext ctx = WebApplicationContextUtils
                 .getWebApplicationContext(getServletContext());
         as = (AlbumService) ctx.getBean("albumService");
     }
 }

/ajax_0500_jQuery_album/src/com/b510/album/web/ValidateNameServlet.java
代碼如下:

package com.b510.album.web;

 import java.io.IOException;
 import java.io.PrintWriter;

 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;

 import com.b510.album.exception.AlbumException;
 import com.b510.album.web.base.BaseServlet;
 /**
  *
  * @author Hongten
  *
  */
 public class ValidateNameServlet extends BaseServlet {

     private static final long serialVersionUID = 9038839276327742641L;

     public void service(HttpServletRequest request, HttpServletResponse response)
             throws IOException, ServletException {
         String name = request.getParameter("user");
         response.setContentType("text/javascript;charset=GBK");
         // 獲取輸出流
         PrintWriter out = response.getWriter();
         try {
             if (name != null) {
                 if (as.validateName(name)) {
                     out.println("alert('恭喜您,該用戶名還未使用,你可使用該用戶名!');");
                 } else {
                     out.println("alert('對不起,該用戶名已被他人占用!');");
                     out.println("$('#user').val('');");
                 }
             } else {
                 out.println("alert('驗證用戶名出現異常,請更換用戶名重試!');");
             }
         } catch (AlbumException ex) {
             out.println("alert('" + ex.getMessage() + "請更換用戶名重試!');");
         }
     }
 }

/ajax_0500_jQuery_album/src/com/b510/album/web/TurnPageServlet.java
代碼如下:

package com.b510.album.web;

 import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.List;

 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;

 import com.b510.album.exception.AlbumException;
 import com.b510.album.vo.PhotoHolder;
 import com.b510.album.web.base.BaseServlet;
 /**
  *
  * @author Hongten
  *
  */
 public class TurnPageServlet extends BaseServlet {

     private static final long serialVersionUID = -5097286750384714951L;

     public void service(HttpServletRequest request, HttpServletResponse response)
             throws IOException, ServletException {
         String turn = request.getParameter("turn");
         HttpSession session = request.getSession(true);
         String name = (String) session.getAttribute("curUser");
         Object pageObj = session.getAttribute("curPage");
         // 如果HttpSession中的curPage為null,則設置當前頁為第一頁
         int curPage = pageObj == null ? 1 : (Integer) pageObj;
         response.setContentType("text/javascript;charset=GBK");
         PrintWriter out = response.getWriter();
         if (curPage == 1 && turn.equals("-1")) {
             out.println("alert('現在已經是第一頁,無法向前翻頁!')");
         } else {
             // 執行翻頁,修改curPage的值。
             curPage += Integer.parseInt(turn);
             try {
                 List<PhotoHolder> photos = as.getPhotoByUser(name, curPage);
                 // 翻頁後沒有記錄
                 if (photos.size() == 0) {
                     out.println("alert('翻頁後找不到任何相片記錄,系統將自動返回上一頁')");
                     // 重新返回上一頁
                     curPage -= Integer.parseInt(turn);
                 } else {
                     // 把用戶正在浏覽的頁碼放入HttpSession中
                     session.setAttribute("curPage", curPage);
                 }
             } catch (AlbumException ex) {
                 out.println("alert('" + ex.getMessage() + "請重試!')");
             }
         }
     }
 }

/ajax_0500_jQuery_album/src/com/b510/album/web/ShowImgServlet.java
代碼如下:

package com.b510.album.web;

 import java.io.IOException;
 import java.io.PrintWriter;

 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;

 import com.b510.album.web.base.BaseServlet;
 /**
  *
  * @author Hongten
  *
  */
 public class ShowImgServlet extends BaseServlet {

     private static final long serialVersionUID = 1460203270448078666L;

     public void service(HttpServletRequest request, HttpServletResponse response)
             throws IOException, ServletException {
         String img = request.getParameter("img");
         HttpSession session = request.getSession(true);
         // 將用戶正在浏覽的圖片放入HttpSession中。
         session.setAttribute("curImg", img);
         response.setContentType("text/javascript;charset=GBK");
         // 獲取輸出流
         PrintWriter out = response.getWriter();
         out.println("$('#show').attr('src' , 'uploadfiles/" + img + "');");
     }
 }

/ajax_0500_jQuery_album/src/com/b510/album/web/ProUploadServlet.java
代碼如下:

package com.b510.album.web;

 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.PrintWriter;
 import java.util.Iterator;
 import java.util.List;

 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;

 import org.apache.commons.fileupload.FileItem;
 import org.apache.commons.fileupload.FileItemFactory;
 import org.apache.commons.fileupload.FileUploadException;
 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
 import org.apache.commons.fileupload.servlet.ServletFileUpload;

 import com.b510.album.exception.AlbumException;
 import com.b510.album.web.base.BaseServlet;
 /**
  *
  * @author Hongten
  *
  */
 @SuppressWarnings("unchecked")
 public class ProUploadServlet extends BaseServlet {

     private static final long serialVersionUID = 642229801989188793L;

     public void service(HttpServletRequest request, HttpServletResponse response)
             throws IOException, ServletException {
         Iterator iter = null;
         String title = null;
         response.setContentType("text/html;charset=GBK");
         // 獲取輸出流
         PrintWriter out = response.getWriter();
         out.println("<script type='text/javascript>'");
         try {
             // 使用Uploader處理上傳
             FileItemFactory factory = new DiskFileItemFactory();
             ServletFileUpload upload = new ServletFileUpload(factory);
             List items = upload.parseRequest(request);
             iter = items.iterator();
             // 遍歷每個表單控件對應的內容
             while (iter.hasNext()) {
                 FileItem item = (FileItem) iter.next();
                 // 如果該項是普通表單域
                 if (item.isFormField()) {
                     String name = item.getFieldName();
                     if (name.equals("title")) {
                         title = item.getString("GBK");
                     }
                 }
                 // 如果是需要上傳的文件
                 else {
                     String user = (String) request.getSession().getAttribute(
                             "curUser");
                     String serverFileName = null;
                     // 返回文件名
                     String fileName = item.getName();
                     // 取得文件後綴
                     String appden = fileName.substring(fileName
                             .lastIndexOf("."));
                     // 返回文件類型
                     String contentType = item.getContentType();
                     // 只允許上傳jpg、gif、png圖片
                     if (contentType.equals("image/pjpeg")
                             || contentType.equals("image/gif")
                             || contentType.equals("image/jpeg")
                             || contentType.equals("image/png")) {
                         InputStream input = item.getInputStream();
                         serverFileName = String.valueOf(System
                                 .currentTimeMillis());
                         FileOutputStream output = new FileOutputStream(
                                 getServletContext().getRealPath("/")
                                         + "uploadfiles\\" + serverFileName
                                         + appden);
                         byte[] buffer = new byte[1024];
                         int len = 0;
                         while ((len = input.read(buffer)) > 0) {
                             output.write(buffer, 0, len);
                         }
                         input.close();
                         output.close();
                         as.addPhoto(user, title, serverFileName + appden);
                         response.sendRedirect("album.html?resultCode=0");
                     } else {
                         response.sendRedirect("album.html?resultCode=1");
                     }
                 }
             }
         } catch (FileUploadException fue) {
             fue.printStackTrace();
             response.sendRedirect("album.html?resultCode=2");
         } catch (AlbumException ex) {
             ex.printStackTrace();
         }
     }
 }

 /ajax_0500_jQuery_album/src/com/b510/album/web/ProRegistServlet.java
代碼如下:

package com.b510.album.web;

 import java.io.IOException;
 import java.io.PrintWriter;

 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;

 import com.b510.album.exception.AlbumException;
 import com.b510.album.web.base.BaseServlet;
 /**
  *
  * @author Hongten
  *
  */
 public class ProRegistServlet extends BaseServlet {

     private static final long serialVersionUID = -3174994243043815566L;

     public void service(HttpServletRequest request, HttpServletResponse response)
             throws IOException, ServletException {
         String name = request.getParameter("user");
         String pass = request.getParameter("pass");
         response.setContentType("text/javascript;charset=GBK");
         // 獲取輸出流
         PrintWriter out = response.getWriter();
         try {
             out.println("$('#user,#pass').val('');");
             if (name != null && pass != null && as.registUser(name, pass) > 0) {
                 HttpSession session = request.getSession(true);
                 session.setAttribute("curUser", name);
                 out.println("alert('恭喜您,您已經注冊成功!');");
                 out.println("$('#noLogin').hide(500);");
                 out.println("$('#hasLogin').show(500);");
                 // 調用獲取相片列表的方法
                 out.println("onLoadHandler();");
             } else {
                 out.println("alert('您注冊出現失敗,請選擇合適的用戶名重試!');");
             }
         } catch (AlbumException ex) {
             out.println("alert('" + ex.getMessage() + "請更換用戶名重試!');");
         }
     }
 }

/ajax_0500_jQuery_album/src/com/b510/album/web/ProLoginServlet.java
代碼如下:

package com.b510.album.web;

 import java.io.IOException;
 import java.io.PrintWriter;

 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;

 import com.b510.album.exception.AlbumException;
 import com.b510.album.web.base.BaseServlet;
 /**
  *
  * @author Hongten
  *
  */
 public class ProLoginServlet extends BaseServlet {

     private static final long serialVersionUID = -1253530202224049958L;

     public void service(HttpServletRequest request, HttpServletResponse response)
             throws IOException, ServletException {
         String name = request.getParameter("user");
         String pass = request.getParameter("pass");
         response.setContentType("text/javascript;charset=GBK");
         // 獲取輸出流
         PrintWriter out = response.getWriter();
         try {
             // 清空id為user、pass輸入框的內容
             out.println("$('#user,#pass').val('');");
             if (name != null && pass != null && as.userLogin(name, pass)) {
                 HttpSession session = request.getSession(true);
                 session.setAttribute("curUser", name);
                 out.println("alert('您已經登錄成功!')");
                 out.println("$('#noLogin').hide(500)");
                 out.println("$('#hasLogin').show(500)");
                 // 調用獲取相片列表的方法
                 out.println("onLoadHandler();");
             } else {
                 out.println("alert('您輸入的用戶名、密碼不符,請重試!')");
             }
         } catch (AlbumException ex) {
             out.println("alert('" + ex.getMessage() + "請更換用戶名、密碼重試!')");
         }
     }
 }

/ajax_0500_jQuery_album/src/com/b510/album/web/PageLoadServlet.java
代碼如下:

package com.b510.album.web;

 import java.io.IOException;
 import java.io.PrintWriter;

 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;

 import com.b510.album.web.base.BaseServlet;

 /**
  *
  * @author Hongten
  *
  */
 public class PageLoadServlet extends BaseServlet {

     private static final long serialVersionUID = 7512001492425261841L;

     public void service(HttpServletRequest request, HttpServletResponse response)
             throws IOException, ServletException {
         response.setContentType("text/javascript;charset=GBK");
         // 獲取輸出流
         PrintWriter out = response.getWriter();
         HttpSession session = request.getSession(true);
         String name = (String) session.getAttribute("curUser");
         // 如果name不為null,表明用戶已經登錄
         if (name != null) {
             // 隱藏id為noLogin的元素(用戶登錄面板)
             out.println("$('#noLogin').hide()");
             // 隱藏id為hasLogin的元素(用戶控制面板)
             out.println("$('#hasLogin').show()");
             // 調用獲取相片列表的方法
             out.println("onLoadHandler();");
             // 取出HttpSession中的curImg屬性
             String curImg = (String) session.getAttribute("curImg");
             // 重新顯示用戶正在浏覽的相片
             if (curImg != null) {
                 out.println("$('#show').attr('src' , 'uploadfiles/" + curImg
                         + "');");
             }
         }
     }
 }

/ajax_0500_jQuery_album/src/com/b510/album/web/GetPhotoServlet.java
代碼如下:

package com.b510.album.web;

 import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.List;

 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;

 import com.b510.album.exception.AlbumException;
 import com.b510.album.vo.PhotoHolder;
 import com.b510.album.web.base.BaseServlet;

 /**
  *
  * @author Hongten
  *
  */
 public class GetPhotoServlet extends BaseServlet {

     private static final long serialVersionUID = -8380695760546582385L;

     public void service(HttpServletRequest request, HttpServletResponse response)
             throws IOException, ServletException {
         HttpSession session = request.getSession(true);
         // 從HttpSession中獲取系統當前用戶、相片列表的當前頁碼
         String name = (String) session.getAttribute("curUser");
         Object pageObj = session.getAttribute("curPage");
         // 如果HttpSession中的curPage為null,則設置當前頁為第一頁
         int curPage = pageObj == null ? 1 : (Integer) pageObj;
         response.setContentType("text/javascript;charset=GBK");
         // 獲取輸出流
         PrintWriter out = response.getWriter();
         try {
             List<PhotoHolder> photos = as.getPhotoByUser(name, curPage);
             // 清空id為list的元素
             out.println("var list = $('#list').empty();");
             for (PhotoHolder ph : photos) {
                 // 將每個相片動態添加到id為list的元素中
                 out.println("list.append(\"<div align='center'>"
                         + "<a href='javascript:void(0)' onclick=\\\"showImg('"
                         + ph.getFileName() + "');\\\">" + ph.getTitle()
                         + "</a></div>\");");
             }
         } catch (AlbumException ex) {
             out.println("alert('" + ex.getMessage() + "請重試!')");
         }
     }
 }

/ajax_0500_jQuery_album/src/com/b510/album/vo/PhotoHolder.java
代碼如下:

package com.b510.album.vo;

 /**
  *
  * @author Hongten
  *
  */
 public class PhotoHolder {
     // 相片的名稱
     private String title;
     // 相片在服務器上的文件名
     private String fileName;

     // 無參數的構造器
     public PhotoHolder() {
     }

     // 初始化全部屬性的構造器
     public PhotoHolder(String title, String fileName) {
         this.title = title;
         this.fileName = fileName;
     }

     // title屬性的setter和getter方法
     public void setTitle(String title) {
         this.title = title;
     }

     public String getTitle() {
         return this.title;
     }

     // fileName屬性的setter和getter方法
     public void setFileName(String fileName) {
         this.fileName = fileName;
     }

     public String getFileName() {
         return this.fileName;
     }
 }

/ajax_0500_jQuery_album/src/com/b510/album/service/impl/AlbumServiceImpl.java
代碼如下:

package com.b510.album.service.impl;

 import java.util.ArrayList;
 import java.util.List;

 import com.b510.album.dao.PhotoDao;
 import com.b510.album.dao.UserDao;
 import com.b510.album.exception.AlbumException;
 import com.b510.album.model.Photo;
 import com.b510.album.model.User;
 import com.b510.album.service.AlbumService;
 import com.b510.album.vo.PhotoHolder;

 /**
  *
  * @author Hongten
  *
  */
 public class AlbumServiceImpl implements AlbumService {
     // 業務邏輯組件所依賴的2個DAO組件
     private UserDao ud = null;
     private PhotoDao pd = null;

     // 依賴注入2個DAO組件所需的setter方法
     public void setUserDao(UserDao ud) {
         this.ud = ud;
     }

     public void setPhotoDao(PhotoDao pd) {
         this.pd = pd;
     }

     /**
      * 驗證用戶登錄是否成功。
      *
      * @param name
      *            登錄的用戶名
      * @param pass
      *            登錄的密碼
      * @return 用戶登錄的結果,成功返回true,否則返回false
      */
     public boolean userLogin(String name, String pass) {
         try {
             // 使用UserDao根據用戶名查詢用戶
             User u = ud.findByName(name);
             if (u != null && u.getPass().equals(pass)) {
                 return true;
             }
             return false;
         } catch (Exception ex) {
             ex.printStackTrace();
             throw new AlbumException("處理用戶登錄出現異常!");
         }
     }

     /**
      * 注冊新用戶
      *
      * @param name
      *            新注冊用戶的用戶名
      * @param pass
      *            新注冊用戶的密碼
      * @return 新注冊用戶的主鍵
      */
     public int registUser(String name, String pass) {
         try {
             // 創建一個新的User實例
             User u = new User();
             u.setName(name);
             u.setPass(pass);
             // 持久化User對象
             ud.save(u);
             return u.getId();
         } catch (Exception ex) {
             ex.printStackTrace();
             throw new AlbumException("新用戶注冊出現異常!");
         }
     }

     /**
      * 添加照片
      *
      * @param user
      *            添加相片的用戶
      * @param title
      *            添加相片的標題
      * @param fileName
      *            新增相片在服務器上的文件名
      * @return 新添加相片的主鍵
      */
     public int addPhoto(String user, String title, String fileName) {
         try {
             // 創建一個新的Photo實例
             Photo p = new Photo();
             p.setTitle(title);
             p.setFileName(fileName);
             p.setUser(ud.findByName(user));
             // 持久化Photo實例
             pd.save(p);
             return p.getId();
         } catch (Exception ex) {
             ex.printStackTrace();
             throw new AlbumException("添加相片過程中出現異常!");
         }
     }

     /**
      * 根據用戶獲得該用戶的所有相片
      *
      * @param user
      *            當前用戶
      * @param pageNo
      *            頁碼
      * @return 返回屬於該用戶、指定頁的相片
      */
     public List<PhotoHolder> getPhotoByUser(String user, int pageNo) {
         try {
             List<Photo> pl = pd.findByUser(ud.findByName(user), pageNo);
             List<PhotoHolder> result = new ArrayList<PhotoHolder>();
             for (Photo p : pl) {
                 result.add(new PhotoHolder(p.getTitle(), p.getFileName()));
             }
             return result;
         } catch (Exception ex) {
             ex.printStackTrace();
             throw new AlbumException("查詢相片列表的過程中出現異常!");
         }
     }

     /**
      * 驗證用戶名是否可用,即數據庫裡是否已經存在該用戶名
      *
      * @param name
      *            需要校驗的用戶名
      * @return 如果該用戶名可用,返回true,否則返回false。
      */
     public boolean validateName(String name) {
         try {
             // 根據用戶名查詢對應的User實例
             User u = ud.findByName(name);
             if (u != null) {
                 return false;
             }
             return true;
         } catch (Exception ex) {
             ex.printStackTrace();
             throw new AlbumException("驗證用戶名是否存在的過程中出現異常!");
         }
     }
 }

/ajax_0500_jQuery_album/src/com/b510/album/service/AlbumService.java
代碼如下:

package com.b510.album.service;

 import java.util.List;

 import com.b510.album.vo.PhotoHolder;

 /**
  *
  * @author Hongten
  *
  */
 public interface AlbumService {
     /**
      * 驗證用戶登錄是否成功。
      *
      * @param name
      *            登錄的用戶名
      * @param pass
      *            登錄的密碼
      * @return 用戶登錄的結果,成功返回true,否則返回false
      */
     boolean userLogin(String name, String pass);

     /**
      * 注冊新用戶
      *
      * @param name
      *            新注冊用戶的用戶名
      * @param pass
      *            新注冊用戶的密碼
      * @return 新注冊用戶的主鍵
      */
     int registUser(String name, String pass);

     /**
      * 添加照片
      *
      * @param user
      *            添加相片的用戶
      * @param title
      *            添加相片的標題
      * @param fileName
      *            新增相片在服務器上的文件名
      * @return 新添加相片的主鍵
      */
     int addPhoto(String user, String title, String fileName);

     /**
      * 根據用戶獲得該用戶的所有相片
      *
      * @param user
      *            當前用戶
      * @param pageNo
      *            頁碼
      * @return 返回屬於該用戶、指定頁的相片
      */
     List<PhotoHolder> getPhotoByUser(String user, int pageNo);

     /**
      * 驗證用戶名是否可用,即數據庫裡是否已經存在該用戶名
      *
      * @param name
      *            需要校驗的用戶名
      * @return 如果該用戶名可用,返回true,否則返回false。
      */
     boolean validateName(String name);
 }

/ajax_0500_jQuery_album/src/com/b510/album/model/Photo.java
代碼如下:

package com.b510.album.model;

 /**
  * Photo實體類
  *
  * @author Hongten
  *
  */
 public class Photo {
     // 標識屬性
     private Integer id;
     // 該相片的名稱
     private String title;
     // 相片在服務器上的文件名
     private String fileName;
     // 保存該相片所屬的用戶
     private User user;

     // 無參數的構造器
     public Photo() {
     }

     // 初始化全部屬性的構造器
     public Photo(Integer id, String title, String fileName, User user) {
         this.id = id;
         this.title = title;
         this.fileName = fileName;
         this.user = user;
     }

     // id屬性的setter和getter方法
     public void setId(Integer id) {
         this.id = id;
     }

     public Integer getId() {
         return this.id;
     }

     // title屬性的setter和getter方法
     public void setTitle(String title) {
         this.title = title;
     }

     public String getTitle() {
         return this.title;
     }

     // fileName屬性的setter和getter方法
     public void setFileName(String fileName) {
         this.fileName = fileName;
     }

     public String getFileName() {
         return this.fileName;
     }

     // user屬性的setter和getter方法
     public void setUser(User user) {
         this.user = user;
     }

     public User getUser() {
         return this.user;
     }
 }

/ajax_0500_jQuery_album/src/com/b510/album/model/User.java
代碼如下:

package com.b510.album.model;

 import java.util.Set;
 import java.util.HashSet;

 /**
  * User實體類
  *
  * @author Hongten
  *
  */
 public class User {
     // 標識屬性
     private Integer id;
     // 該用戶的用戶名
     private String name;
     // 該用戶的密碼
     private String pass;
     // 使用Set保存該用戶關聯的相片
     private Set<Photo> photos = new HashSet<Photo>();

     // 無參數的構造器
     public User() {
     }

     // 初始化全部屬性的構造器
     public User(Integer id, String name, String pass) {
         this.id = id;
         this.name = name;
         this.pass = pass;
     }

     // id屬性的setter和getter方法
     public void setId(Integer id) {
         this.id = id;
     }

     public Integer getId() {
         return this.id;
     }

     // name屬性的setter和getter方法
     public void setName(String name) {
         this.name = name;
     }

     public String getName() {
         return this.name;
     }

     // pass屬性的setter和getter方法
     public void setPass(String pass) {
         this.pass = pass;
     }

     public String getPass() {
         return this.pass;
     }

     // photos屬性的setter和getter方法
     public void setPhotos(Set<Photo> photos) {
         this.photos = photos;
     }

     public Set<Photo> getPhotos() {
         return this.photos;
     }

 }

/ajax_0500_jQuery_album/src/com/b510/album/model/Photo.hbm.xml
代碼如下:

<?xml version="1.0" encoding="GBK"?>
 <!DOCTYPE hibernate-mapping
     PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 <!-- Hibernate映射文件的根元素 -->
 <hibernate-mapping package="com.b510.album.model">
     <!-- 每個class元素映射一個持久化類 -->
     <class name="Photo" table="photo_table">
         <id name="id" type="int" column="photo_id">
             <!-- 指定主鍵生成器策略 -->
             <generator class="identity"/>
         </id>
         <!-- 映射普通屬性 -->
         <property name="title" type="string"/>
         <property name="fileName" type="string"/>
         <!-- 映射和User實體的N:1關聯 -->
         <many-to-one name="user" column="owner_id"
             class="User" not-null="true"/>
     </class>
 </hibernate-mapping>

/ajax_0500_jQuery_album/src/com/b510/album/model/User.hbm.xml
代碼如下:

<?xml version="1.0" encoding="GBK"?>
 <!DOCTYPE hibernate-mapping
     PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 <!-- Hibernate映射文件的根元素 -->
 <hibernate-mapping package="com.b510.album.model">
     <!-- 每個class元素映射一個持久化類 -->
     <class name="User" table="user_table">
         <!-- 映射標識屬性 -->
         <id name="id" type="int" column="user_id">
             <!-- 指定主鍵生成器策略 -->
             <generator class="identity"/>
         </id>
         <!-- 映射普通屬性 -->
         <property name="name" type="string" unique="true"/>
         <property name="pass" type="string"/>
         <!-- 映射和Photo實體的1:N關聯 -->
         <set name="photos" inverse="true">
             <key column="owner_id"/>
             <one-to-many class="Photo"/>
         </set>
     </class>
 </hibernate-mapping>

/ajax_0500_jQuery_album/src/com/b510/album/exception/AlbumException.java
代碼如下:

package com.b510.album.exception;

 /**
  * 自定義的Exception
  *
  * @author Hongten
  *
  */
 public class AlbumException extends RuntimeException {

     private static final long serialVersionUID = 8050756054850450421L;

     // 提供一個無參數的構造器
     public AlbumException() {
     }

     // 提供一個帶字符串參數的構造器
     public AlbumException(String msg) {
         super(msg);
     }
 }

/ajax_0500_jQuery_album/src/com/b510/album/enhance/HongtenHibernateDaoSupport.java
代碼如下:

package com.b510.album.enhance;

 import java.sql.SQLException;
 import java.util.List;

 import org.hibernate.HibernateException;
 import org.hibernate.Query;
 import org.hibernate.Session;
 import org.springframework.orm.hibernate3.HibernateCallback;
 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

 /**
  *
  * @author Hongten
  *
  */
 @SuppressWarnings("unchecked")
 public class HongtenHibernateDaoSupport extends HibernateDaoSupport {
     /**
      * 使用hql 語句進行分頁查詢操作
      *
      * @param hql
      *            需要查詢的hql語句
      * @param offset
      *            第一條記錄索引
      * @param pageSize
      *            每頁需要顯示的記錄數
      * @return 當前頁的所有記錄
      */
     public List findByPage(final String hql, final int offset,
             final int pageSize) {
         List list = getHibernateTemplate().executeFind(new HibernateCallback() {
             public Object doInHibernate(Session session)
                     throws HibernateException, SQLException {
                 List result = session.createQuery(hql).setFirstResult(offset)
                         .setMaxResults(pageSize).list();
                 return result;
             }
         });
         return list;
     }

     /**
      * 使用hql 語句進行分頁查詢操作
      *
      * @param hql
      *            需要查詢的hql語句
      * @param value
      *            如果hql有一個參數需要傳入,value就是傳入的參數
      * @param offset
      *            第一條記錄索引
      * @param pageSize
      *            每頁需要顯示的記錄數
      * @return 當前頁的所有記錄
      */
     public List findByPage(final String hql, final Object value,
             final int offset, final int pageSize) {
         List list = getHibernateTemplate().executeFind(new HibernateCallback() {
             public Object doInHibernate(Session session)
                     throws HibernateException, SQLException {
                 List result = session.createQuery(hql).setParameter(0, value)
                         .setFirstResult(offset).setMaxResults(pageSize).list();
                 return result;
             }
         });
         return list;
     }

     /**
      * 使用hql 語句進行分頁查詢操作
      *
      * @param hql
      *            需要查詢的hql語句
      * @param values
      *            如果hql有多個個參數需要傳入,values就是傳入的參數數組
      * @param offset
      *            第一條記錄索引
      * @param pageSize
      *            每頁需要顯示的記錄數
      * @return 當前頁的所有記錄
      */
     public List findByPage(final String hql, final Object[] values,
             final int offset, final int pageSize) {
         List list = getHibernateTemplate().executeFind(new HibernateCallback() {
             public Object doInHibernate(Session session)
                     throws HibernateException, SQLException {
                 Query query = session.createQuery(hql);
                 for (int i = 0; i < values.length; i++) {
                     query.setParameter(i, values[i]);
                 }
                 List result = query.setFirstResult(offset).setMaxResults(
                         pageSize).list();
                 return result;
             }
         });
         return list;
     }
 }

/ajax_0500_jQuery_album/src/com/b510/album/dao/impl/PhotoDaoHibernate.java
代碼如下:

package com.b510.album.dao.impl;

 import java.util.List;

 import com.b510.album.dao.PhotoDao;
 import com.b510.album.enhance.HongtenHibernateDaoSupport;
 import com.b510.album.model.Photo;
 import com.b510.album.model.User;
 /**
  *
  * @author Hongten
  *
  */
 @SuppressWarnings("unchecked")
 public class PhotoDaoHibernate extends HongtenHibernateDaoSupport implements
         PhotoDao {
     /**
      * 根據標識屬性來加載Photo實例
      *
      * @param id
      *            需要加載的Photo實例的標識屬性值
      * @return 指定標識屬性對應的Photo實例
      */
     public Photo get(Integer id) {
         return (Photo) getHibernateTemplate().get(Photo.class, id);
     }

     /**
      * 持久化指定的Photo實例
      *
      * @param photo
      *            需要被持久化的Photo實例
      * @return Photo實例被持久化後的標識屬性值
      */
     public Integer save(Photo photo) {
         return (Integer) getHibernateTemplate().save(photo);
     }

     /**
      * 修改指定的Photo實例
      *
      * @param photo
      *            需要被修改的Photo實例
      */
     public void update(Photo photo) {
         getHibernateTemplate().update(photo);
     }

     /**
      * 刪除指定的Photo實例
      *
      * @param photo
      *            需要被刪除的Photo實例
      */
     public void delete(Photo photo) {
         getHibernateTemplate().delete(photo);
     }

     /**
      * 根據標識屬性刪除Photo實例
      *
      * @param id
      *            需要被刪除的Photo實例的標識屬性值
      */
     public void delete(Integer id) {
         getHibernateTemplate().delete(get(id));
     }

     /**
      * 查詢全部的Photo實例
      *
      * @return 數據庫中全部的Photo實例
      */
     public List<Photo> findAll() {
         return (List<Photo>) getHibernateTemplate().find("from Photo");
     }

     /**
      * 查詢屬於指定用戶的相片,且進行分頁控制
      *
      * @param user
      *            查詢相片所屬的用戶
      * @param pageNo
      *            需要查詢的指定頁
      * @return 查詢到的相片
      */
     public List<Photo> findByUser(User user, int pageNo) {
         int offset = (pageNo - 1) * PAGE_SIZE;
         // 返回分頁查詢的結果
         return (List<Photo>) findByPage("from Photo b where b.user = ?", user,
                 offset, PAGE_SIZE);
     }
 }

/ajax_0500_jQuery_album/src/com/b510/album/dao/impl/UserDaoHibernate.java
代碼如下:

package com.b510.album.dao.impl;

 import java.util.List;

 import com.b510.album.dao.UserDao;
 import com.b510.album.enhance.HongtenHibernateDaoSupport;
 import com.b510.album.model.User;

 /**
  *
  * @author Hongten
  *
  */
 @SuppressWarnings("unchecked")
 public class UserDaoHibernate extends HongtenHibernateDaoSupport implements
         UserDao {
     /**
      * 根據標識屬性來加載User實例
      *
      * @param id
      *            需要加載的User實例的標識屬性值
      * @return 指定標識屬性對應的User實例
      */
     public User get(Integer id) {
         return (User) getHibernateTemplate().get(User.class, id);
     }

     /**
      * 持久化指定的User實例
      *
      * @param user
      *            需要被持久化的User實例
      * @return User實例被持久化後的標識屬性值
      */
     public Integer save(User user) {
         return (Integer) getHibernateTemplate().save(user);
     }

     /**
      * 修改指定的User實例
      *
      * @param user
      *            需要被修改的User實例
      */
     public void update(User user) {
         getHibernateTemplate().update(user);
     }

     /**
      * 刪除指定的User實例
      *
      * @param user
      *            需要被刪除的User實例
      */
     public void delete(User user) {
         getHibernateTemplate().delete(user);
     }

     /**
      * 根據標識屬性刪除User實例
      *
      * @param id
      *            需要被刪除的User實例的標識屬性值
      */
     public void delete(Integer id) {
         getHibernateTemplate().delete(get(id));
     }

     /**
      * 查詢全部的User實例
      *
      * @return 數據庫中全部的User實例
      */
     public List<User> findAll() {
         return (List<User>) getHibernateTemplate().find("from User");
     }

     /**
      * 根據用戶名查找用戶
      *
      * @param name
      *            需要查找的用戶的用戶名
      * @return 查找到的用戶
      */
     public User findByName(String name) {
         List<User> users = (List<User>) getHibernateTemplate().find(
                 "from User u where u.name = ?", name);
         if (users != null && users.size() == 1) {
             return users.get(0);
         }
         return null;
     }
 }

/ajax_0500_jQuery_album/src/com/b510/album/dao/PhotoDao.java
代碼如下:

package com.b510.album.dao;

 import java.util.List;

 import com.b510.album.model.Photo;
 import com.b510.album.model.User;

 
 /**
  * PhotoDao接口
  *
  * @author Hongten
  *
  */
 public interface PhotoDao {
     // 以常量控制每頁顯示的相片數
     final int PAGE_SIZE = 8;

     /**
      * 根據標識屬性來加載Photo實例
      *
      * @param id
      *            需要加載的Photo實例的標識屬性值
      * @return 指定標識屬性對應的Photo實例
      */
     Photo get(Integer id);

     /**
      * 持久化指定的Photo實例
      *
      * @param photo
      *            需要被持久化的Photo實例
      * @return Photo實例被持久化後的標識屬性值
      */
     Integer save(Photo photo);

     /**
      * 修改指定的Photo實例
      *
      * @param photo
      *            需要被修改的Photo實例
      */
     void update(Photo photo);

     /**
      * 刪除指定的Photo實例
      *
      * @param photo
      *            需要被刪除的Photo實例
      */
     void delete(Photo photo);

     /**
      * 根據標識屬性刪除Photo實例
      *
      * @param id
      *            需要被刪除的Photo實例的標識屬性值
      */
     void delete(Integer id);

     /**
      * 查詢全部的Photo實例
      *
      * @return 數據庫中全部的Photo實例
      */
     List<Photo> findAll();

     /**
      * 查詢屬於指定用戶的相片,且進行分頁控制
      *
      * @param user
      *            查詢相片所屬的用戶
      * @param pageNo
      *            需要查詢的指定頁
      * @return 查詢到的相片
      */
     List<Photo> findByUser(User user, int pageNo);
 }

/ajax_0500_jQuery_album/src/com/b510/album/dao/UserDao.java
代碼如下:

package com.b510.album.dao;

 import java.util.List;

 import com.b510.album.model.User;

 
 /**
  * UserDao接口
  *
  * @author Hongten
  *
  */
 public interface UserDao {
     /**
      * 根據標識屬性來加載User實例
      *
      * @param id
      *            需要加載的User實例的標識屬性值
      * @return 指定標識屬性對應的User實例
      */
     User get(Integer id);

     /**
      * 持久化指定的User實例
      *
      * @param user
      *            需要被持久化的User實例
      * @return User實例被持久化後的標識屬性值
      */
     Integer save(User user);

     /**
      * 修改指定的User實例
      *
      * @param user
      *            需要被修改的User實例
      */
     void update(User user);

     /**
      * 刪除指定的User實例
      *
      * @param user
      *            需要被刪除的User實例
      */
     void delete(User user);

     /**
      * 根據標識屬性刪除User實例
      *
      * @param id
      *            需要被刪除的User實例的標識屬性值
      */
     void delete(Integer id);

     /**
      * 查詢全部的User實例
      *
      * @return 數據庫中全部的User實例
      */
     List<User> findAll();

     /**
      * 根據用戶名查找用戶
      *
      * @param name
      *            需要查找的用戶的用戶名
      * @return 查找到的用戶
      */
     User findByName(String name);
 }
============================================================================================

由於放入jar包後,項目看起來比較大,所以這裡就把jar包取消了,所需的jar包如下圖:

下面是附件:ajax_jQuery_album_jb51net.rar(源碼下載)

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved