基于spring+hibernate+JQuery开发之电子相册(附源码下载)
项目结构:
项目首页:
注册页面:
上传图片:
效果图一:
效果图二:
效果图三:
=============================================================
下面是代码部分
=============================================================
需要用到的数据库sql:
由于放入jar包后,项目看起来比较大,所以这里就把jar包取消了,所需的jar包如下图:
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" border="0" cellspacing="1" align="center">
<caption><h3>电子相册系统</h3></caption>
<tr>
<td height="60" colspan="2">
<!-- 没有登录显示下面div元素 -->
<div id="nologin">
<!-- 这里是注册/登录的表格 -->
<table width="100%" border="0" 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" align="center">
<input id="login" type="button" onclick="prologin();" value="登录" />
<input id="resetlogin" type="button" onclick="reset();" value="重设" />
</div>
<div id="registdiv" align="center" style="display:none">
<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" align="center" style="display:none">
您已经登录成功,下面是您的相册,您也可以<a href="javascript:void(0);"
onclick="openupload();">增加相片</a>
</div>
</td>
</tr>
<tr>
<!-- 显示相片列表的元素 -->
<td width="120" height="440" valign="top">
<div align="center"><h3>相片列表</h3></div>
<div id="list"></div><hr />
<div align="center"><a href="javascript:void(0);" onclick="turnpage(-1);">上一页</a>
<a href="javascript:void(0);" onclick="turnpage(1);">下一页</a></div>
</td>
<!-- 显示相片的元素 -->
<td width="660" align="center" valign="middle">
<div style="width:640px;height:430px;overflow:auto">
<img id="show" alt="当前相片"></img></div></td>
</tr>
</table>
<div id="uploaddiv" style="display:none">
<form action="proupload" method="post"
enctype="multipart/form-data">
<table width="400" border="0" 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" align="center">
<input type="submit" value="上传" />
<input type="reset" value="重设" />
</td>
</tr>
</table>
</form>
</div>
<div id="tipdiv" style="display:none">
</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);
}
下一篇: vue视图不更新情况详解