spring+hibenate+JQuery 기반 전자 앨범(원본 다운로드)
프로젝트 첫 페이지:
등록 페이지:
사진 업로드:
효과 그림 1:
효과 그림 2:
효과 도 3:
=============================================================
다음은 코드 부분 입 니 다.
=============================================================
필요 한 데이터베이스 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" 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>
/ajax0500_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 가방 은 다음 그림 과 같 습 니 다.
다음은 첨부 파일 입 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
thymeleaf로 HTML 페이지를 동적으로 만듭니다 (spring + gradle)지난번에는 에서 화면에 HTML을 표시했습니다. 이번에는 화면을 동적으로 움직여보고 싶기 때문에 입력한 문자를 화면에 표시시키고 싶습니다. 초보자의 비망록이므로 이상한 점 등 있으면 지적 받을 수 있으면 기쁩니다! ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.