Project structure:
Project homepage:
Registration page:
Upload image:
Effect picture one:
Effect picture two:
Effect picture three:
================================================== ===========
Below is the code part
================================================== ===========
Database SQL required:
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)
);
<div id="uploadDiv" style="display:none">
<form action="proUpload" method="post"
enctype="multipart/form-data">
<table cellspacing="1" cellpadding="10">
<caption>Upload pictures</caption>
<tr>
<td>Picture title:</td>
<td><input id="title" name="title" type="text" /></td>
</tr>
<tr>
<td>Browse pictures:</td>
<td><input id="file" name="file" type="file" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Upload" />
<input type="reset" value="Reset" />
</td>
</tr>
</table>
</form>
</div>
<div id="tipDiv" style="display:none">
</div>
</body>
</html>
<!-- Configure the Spring container to be loaded when the web application starts -->
<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>
<!-- Define data source Bean, implemented using C3P0 data source -->
<bean id="dataSource" destroy-method="close"
>
<!-- Specify the driver to connect to the database -->
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<!-- Specify the URL to connect to the database -->
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3308/db_ajax"/>
<!-- Specify the user name to connect to the database -->
<property name="user" value="root"/>
<!-- Specify the password to connect to the database -->
<property name="password" value="root"/>
<!--Specify the maximum number of connections to the database connection pool-->
<property name="maxPoolSize" value="40"/>
<!-- Specify the minimum number of connections to connect to the database connection pool -->
<property name="minPoolSize" value="1"/>
<!-- Specify the number of initial connections to connect to the database connection pool -->
<property name="initialPoolSize" value="1"/>
<!-- Specify the maximum idle time for connections to the database connection pool -->
<property name="maxIdleTime" value="20"/>
</bean>
<!-- Define Hibernate's SessionFactory -->
<bean id="sessionFactory"
>
<!-- Dependency injection data source, inject the dataSource defined above -->
<property name="dataSource" ref="dataSource"/>
<!-- The mappingResouces attribute is used to list all mapping files -->
<property name="mappingResources">
<list>
<!-- The following is used to list Hibernate mapping files-->
<value>com/b510/album/model/User.hbm.xml</value>
<value>com/b510/album/model/Photo.hbm.xml</value>
</list>
</property>
<!-- Define the properties of Hibernate's SessionFactory -->
<property name="hibernateProperties">
<props>
<!--Specify database dialect-->
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLInnoDBDialect</prop>
<!-- Whether to automatically create a database every time as needed -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- Display the SQL generated by Hibernate persistence operation -->
<prop key="hibernate.show_sql">true</prop>
<!-- Format the SQL script and then output it -->
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<!-- Configure UserDao component -->
<bean id="userDao"
>
<!--Inject SessionFactory reference-->
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Configure PhotoDao component -->
<bean id="photoDao"
>
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Configure albumService business logic component -->
<bean id="albumService"
>
<!-- Inject 2 DAO components into the business logic component -->
<property name="userDao" ref="userDao"/>
<property name="photoDao" ref="photoDao"/>
</bean>
<!-- Configure Hibernate's local transaction manager, use the HibernateTransactionManager class -->
<!-- This class implements the PlatformTransactionManager interface, which is a specific implementation for Hibernate -->
<bean id="transactionManager"
>
<!-- When configuring HibernateTransactionManager, you need to inject a reference to SessionFactory -->
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Configure the transaction aspect Bean and specify the transaction manager -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- Used to configure detailed transaction semantics-->
<tx:attributes>
<!-- All methods starting with 'get' are read-only -->
<tx:method name="get*" read-only="true"/>
<!-- Other methods use default transaction settings -->
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<aop:config>
<!-- Configure a pointcut to match all methods executed by all classes ending with Impl under the lee package -->
<aop:pointcut id="leeService"
expression="execution(* com.b510.album.service.impl.*Impl.*(..))"/>
<!-- Specify to apply the txAdvice transaction aspect at the leeService entry point -->
<aop:advisor advice-ref="txAdvice"
pointcut-ref="leeService"/>
</aop:config>
</beans>
function reset()
{
//Clear the two single-line text boxes of user and pass
$("#user").val("");
$("#pass").val("");
}
//Switch to the registration dialog box
function changeRegist()
{
//Hide the two buttons for login
$("#loginDiv").hide("500");
//Display two buttons for registration
$("#registDiv").show("500");
}
//Function to handle user login
function proLogin()
{
//Get the values of the two text boxes user and pass
var user = $.trim($("#user").val());
var pass = $.trim($("#pass").val());
if (user == null || user == ""
|| pass == null|| pass == "")
{
alert("You must enter your username and password before you can log in");
return false;
}
else
{
//Send asynchronous, POST request to proLogin
$.post("proLogin", $('#user,#pass').serializeArray()
, null , "script");
}
}
//Function that handles user registration
functionregist()
{
//Get the values of the two text boxes user and pass
var user = $.trim($("#user").val());
var pass = $.trim($("#pass").val());
if (user == null || user == "" || pass == null || pass =="")
{
alert("You must enter your username and password before registering");
return false;
}
else
{
//Send asynchronous, POST request to proRegist
$.post("proRegist", $('#user,#pass').serializeArray()
, null , "script");
}
}
//Verify if the username is available
function validateName()
{
//Get the value of user text box
var user = $.trim($("#user").val());
if (user == null || user == "")
{
alert("You have not entered your username yet!");
return false;
}
else
{
//Send an asynchronous, POST request to validateName
$.post("validateName", $('#user').serializeArray()
, null , "script");
}
}
// Periodically obtain photos of the current user and current page
function onLoadHandler()
{
//Send asynchronous, GET request to getPhoto
$.getScript("getPhoto");
//Execute this method again after specifying 1 second
setTimeout("onLoadHandler()", 1000);
}
//display photos
function showImg(fileName)
{
$.getScript("showImg?img=" + fileName);
// document.getElementById("show").src="uploadfiles/" + fileName + "?now=" + new Date();
// $("#show").attr("src" , "uploadfiles/" + fileName);
}
//Function to handle page turning
function turnPage(flag)
{
$.getScript("turnPage?turn=" + flag);
}
//Open the upload window
function openUpload()
{
$("#uploadDiv").show()
.dialog(
{
modal: true,
resizable: false,
width: 428,
height: 220,
overlay: {opacity: 0.5 , background: "black"}
});
}
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;
//Define the constructor and obtain a reference to the Spring container
public void init(ServletConfig config) throws ServletException {
super.init(config);
ApplicationContext ctx = WebApplicationContextUtils
.getWebApplicationContext(getServletContext());
as = (AlbumService) ctx.getBean("albumService");
}
}
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");
// Get the output stream
PrintWriter out = response.getWriter();
try {
if (name != null) {
if (as.validateName(name)) {
out.println("alert('Congratulations, this username has not been used yet, you can use this username!');");
} else {
out.println("alert('Sorry, this username is already occupied by someone else!');");
out.println("$('#user').val('');");
}
} else {
out.println("alert('An exception occurred while verifying the username, please change the username and try again!');");
}
} catch (AlbumException ex) {
out.println("alert('" + ex.getMessage() + "Please change your username and try again!');");
}
}
}
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");
// If curPage in HttpSession is null, set the current page to the first page
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('Now is the first page, cannot page forward!')");
} else {
// Execute page turning and modify the value of curPage.
curPage += Integer.parseInt(turn);
try {
List<PhotoHolder> photos = as.getPhotoByUser(name, curPage);
// There is no record after turning the page
if (photos.size() == 0) {
out.println("alert('No photo record found after turning the page, the system will automatically return to the previous page')");
//Return to the previous page
curPage -= Integer.parseInt(turn);
} else {
//Put the page number the user is browsing into the HttpSession
session.setAttribute("curPage", curPage);
}
} catch (AlbumException ex) {
out.println("alert('" + ex.getMessage() + "Please try again!')");
}
}
}
}
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);
//Put the image the user is browsing into the HttpSession.
session.setAttribute("curImg", img);
response.setContentType("text/javascript;charset=GBK");
// Get the output stream
PrintWriter out = response.getWriter();
out.println("$('#show').attr('src' , 'uploadfiles/" + img + "');");
}
}
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");
// Get the output stream
PrintWriter out = response.getWriter();
out.println("<script type='text/javascript>'");
try {
//Use Uploader to handle uploads
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
iter = items.iterator();
// Traverse the content corresponding to each form control
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// If the item is a normal form field
if (item.isFormField()) {
String name = item.getFieldName();
if (name.equals("title")) {
title = item.getString("GBK");
}
}
// If it is a file that needs to be uploaded
else {
String user = (String) request.getSession().getAttribute(
"curUser");
String serverFileName = null;
//return file name
String fileName = item.getName();
// Get file suffix
String appden = fileName.substring(fileName
.lastIndexOf("."));
//return file type
String contentType = item.getContentType();
// Only jpg, gif, and png images are allowed to be uploaded
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();
}
}
}
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");
// Get the output stream
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('Congratulations, you have successfully registered!');");
out.println("$('#noLogin').hide(500);");
out.println("$('#hasLogin').show(500);");
//Call the method to get the photo list
out.println("onLoadHandler();");
} else {
out.println("alert('Your registration failed, please choose a suitable username and try again!');");
}
} catch (AlbumException ex) {
out.println("alert('" + ex.getMessage() + "Please change your username and try again!');");
}
}
}
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");
// Get the output stream
PrintWriter out = response.getWriter();
try {
// Clear the contents of the input boxes with IDs of user and 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('You have logged in successfully!')");
out.println("$('#noLogin').hide(500)");
out.println("$('#hasLogin').show(500)");
//Call the method to get the photo list
out.println("onLoadHandler();");
} else {
out.println("alert('The user name and password you entered do not match, please try again!')");
}
} catch (AlbumException ex) {
out.println("alert('" + ex.getMessage() + "Please change your username and password and try again!')");
}
}
}
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");
// Get the output stream
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
String name = (String) session.getAttribute("curUser");
// If name is not null, it indicates that the user has logged in
if (name != null) {
//Hide the element with id noLogin (user login panel)
out.println("$('#noLogin').hide()");
//Hide the element with id hasLogin (User Control Panel)
out.println("$('#hasLogin').show()");
//Call the method to get the photo list
out.println("onLoadHandler();");
// Take out the curImg attribute in HttpSession
String curImg = (String) session.getAttribute("curImg");
//Redisplay the photo the user is browsing
if (curImg != null) {
out.println("$('#show').attr('src' , 'uploadfiles/" + curImg
+ "');");
}
}
}
}
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);
// Get the current page number of the current user and photo list of the system from HttpSession
String name = (String) session.getAttribute("curUser");
Object pageObj = session.getAttribute("curPage");
// If curPage in HttpSession is null, set the current page to the first page
int curPage = pageObj == null ? 1 : (Integer) pageObj;
response.setContentType("text/javascript;charset=GBK");
// Get the output stream
PrintWriter out = response.getWriter();
try {
List<PhotoHolder> photos = as.getPhotoByUser(name, curPage);
// Clear the element with id of list
out.println("var list = $('#list').empty();");
for (PhotoHolder ph : photos) {
// Dynamically add each photo to the element with the id of 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() + "Please try again!')");
}
}
}
/**
*
* @author Hongten
*
*/
public class PhotoHolder {
//The name of the photo
private String title;
//The file name of the photo on the server
private String fileName;
// Constructor without parameters
public PhotoHolder() {
}
// Constructor to initialize all properties
public PhotoHolder(String title, String fileName) {
this.title = title;
this.fileName = fileName;
}
//The setter and getter methods of the title attribute
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return this.title;
}
//Setter and getter methods of fileName attribute
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
return this.fileName;
}
}
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 components that the business logic component depends on
private UserDao ud = null;
private PhotoDao pd = null;
// Dependency injection of the setter methods required by 2 DAO components
public void setUserDao(UserDao ud) {
this.ud = ud;
}
public void setPhotoDao(PhotoDao pd) {
this.pd = pd;
}
/**
* Verify whether the user login is successful.
*
* @param name
* Login user name
* @param pass
* Login password
* @return The result of user login, returns true if successful, otherwise returns false
*/
public boolean userLogin(String name, String pass) {
try {
// Use UserDao to query users based on username
User u = ud.findByName(name);
if (u != null && u.getPass().equals(pass)) {
return true;
}
return false;
} catch (Exception ex) {
ex.printStackTrace();
throw new AlbumException("An exception occurred while processing user login!");
}
}
/**
* Register new user
*
* @param name
* Username of newly registered user
* @param pass
* Password for newly registered users
* @return the primary key of the newly registered user
*/
public int registUser(String name, String pass) {
try {
//Create a new User instance
User u = new User();
u.setName(name);
u.setPass(pass);
// Persist the User object
ud.save(u);
return u.getId();
} catch (Exception ex) {
ex.printStackTrace();
throw new AlbumException("An exception occurred during new user registration!");
}
}
/**
* Add photos
*
* @param user
* User who added photo
* @param title
* Add a title to your photo
* @param fileName
* Add the file name of the photo on the server
* @return the primary key of the newly added photo
*/
public int addPhoto(String user, String title, String fileName) {
try {
//Create a new Photo instance
Photo p = new Photo();
p.setTitle(title);
p.setFileName(fileName);
p.setUser(ud.findByName(user));
// Persistent Photo instance
pd.save(p);
return p.getId();
} catch (Exception ex) {
ex.printStackTrace();
throw new AlbumException("An exception occurred during adding photos!");
}
}
/**
* Get all photos of the user based on the user
*
* @param user
* Current user
* @param pageNo
*Page number
* @return Returns the photos belonging to the user and the specified page
*/
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("An exception occurred while querying the photo list!");
}
}
/**
* Verify whether the username is available, that is, whether the username already exists in the database
*
* @param name
* Username that needs to be verified
* @return Returns true if the username is available, otherwise returns false.
*/
public boolean validateName(String name) {
try {
// Query the corresponding User instance based on the user name
User u = ud.findByName(name);
if (u != null) {
return false;
}
return true;
} catch (Exception ex) {
ex.printStackTrace();
throw new AlbumException("An exception occurred during the process of verifying whether the user name exists!");
}
}
}
import java.util.List;
import com.b510.album.vo.PhotoHolder;
/**
*
* @author Hongten
*
*/
public interface AlbumService {
/**
* Verify whether user login is successful.
*
* @param name
* Login user name
* @param pass
* Login password
* @return The result of user login, returns true if successful, otherwise returns false
*/
boolean userLogin(String name, String pass);
/**
* Register new user
*
* @param name
* Username of newly registered user
* @param pass
* Password for newly registered users
* @return the primary key of the newly registered user
*/
int registerUser(String name, String pass);
/**
* Add photos
*
* @param user
* User who added photo
* @param title
* Add a title to your photo
* @param fileName
* Add the file name of the photo on the server
* @return The primary key of the newly added photo
*/
int addPhoto(String user, String title, String fileName);
/**
* Get all photos of the user based on the user
*
* @param user
* Current user
* @param pageNo
*Page number
* @return Returns the photos belonging to the user and the specified page
*/
List<PhotoHolder> getPhotoByUser(String user, int pageNo);
/**
* Verify whether the username is available, that is, whether the username already exists in the database
*
* @param name
* Username that needs to be verified
* @return Returns true if the username is available, otherwise returns false.
*/
boolean validateName(String name);
}
/**
* Photo entity class
*
* @author Hongten
*
*/
public class Photo {
//Identification attribute
privateInteger id;
//The name of the photo
private String title;
//The file name of the photo on the server
private String fileName;
// Save the user to whom the photo belongs
private User user;
// Constructor without parameters
public Photo() {
}
// Constructor to initialize all properties
public Photo(Integer id, String title, String fileName, User user) {
this.id = id;
this.title = title;
this.fileName = fileName;
this.user = user;
}
//Setter and getter methods of id attribute
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return this.id;
}
//The setter and getter methods of the title attribute
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return this.title;
}
//Setter and getter methods of fileName attribute
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
return this.fileName;
}
//Setter and getter methods of user attribute
public void setUser(User user) {
this.user = user;
}
public User getUser() {
return this.user;
}
}
import java.util.Set;
import java.util.HashSet;
/**
* User entity class
*
* @author Hongten
*
*/
public class User {
//Identification attribute
private Integer id;
//The user's username
private String name;
//Password of this user
private String pass;
// Use Set to save the photos associated with this user
private Set<Photo> photos = new HashSet<Photo>();
// Constructor without parameters
public User() {
}
// Constructor to initialize all properties
public User(Integer id, String name, String pass) {
this.id = id;
this.name = name;
this.pass = pass;
}
//Setter and getter methods of id attribute
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return this.id;
}
//Setter and getter methods of name attribute
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
//Setter and getter methods of pass attribute
public void setPass(String pass) {
this.pass = pass;
}
public String getPass() {
return this.pass;
}
//Setter and getter methods of photos attribute
public void setPhotos(Set<Photo> photos) {
this.photos = photos;
}
public Set<Photo> getPhotos() {
return this.photos;
}
}
/**
* Customized Exception
*
* @author Hongten
*
*/
Public Class Albumexception Extends Runtimeexception {
Private Static Final Long SerialVersionuid = 8050756054850450421L;
// Provide a constructor without parameters
public albumexception () {
}
// Provide a constructor with string parameters
Public Albumexception (String MSG) {{
Super (msg);
}
}
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 ("Unched")
public class hongtenhibernatedaosUpport Extends Hibernatedaosupport {
/**
* Use HQL statement for paging inquiry operation
*
* @param HQL
* HQL statement you need to query
* @param Offset
* The first record index
* @param PageSize
* Number of records that need to be displayed per page
* All records of @Return current page
*/
Public list findbypage (final string HQL, final int office,
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;
}
/**
* Use HQL statement for paging inquiry operation
*
* @param HQL
* HQL statement you need to query
* @param value
* If HQL has a parameter that needs to be passed in, value is the parameter that is introduced
* @param Offset
* The first record index
* @param PageSize
* Number of records that need to be displayed per page
* All records of @Return current page
*/
Public list findbypage (final string HQL, Final Object Value,
final int office, final int
List list = GethibernateTemplate (). Executefind (new hibernateCallback () {
Public Object Doinhibernate (Session Session)
Throws HibernateException, Sqlexception {
List result = session.createquery (HQL) .setparameter (0, value)
.setFirsult (offset) .setmaxResults (PAGESIZE). List ();
return result;
}
});
return list;
}
/**
* Use HQL statement for paging inquiry operation
*
* @param HQL
* HQL statement you need to query
* @param value
* If HQL has multiple parameters that need to be passed in, Values is the parameter array that is introduced
* @param Offset
* The first record index
* @param PageSize
* Number of records that need to be displayed per page
* All records of @Return current page
*/
Public list findbypage (final string HQL, Final object [] values,
final int office, final int
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;
}
}
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 ("Unched")
Public Class Photodaohibernate Extends HongtenhibernatedaOSUPPORT Implements
Photodao {
/**
* Load the Photo instance according to the identifier attribute
*
* @param ID
* The attribute value of the identifier of the Photo instance that needs to be loaded
* @Return Specify Photo instance corresponding to the logo attribute
*/
Public Photo Get (Integer ID) {
Return (Photo) getHibernateTemplate (). Get (Photo.Class, ID);
}
/**
* Specific Photo instance
*
* @param Photo
* Need to be persistent Photo instance
* @Return Photo instance that is persistent after the identifier attribute value
*/
Public Integer Save (Photo Photo) {
Return (Integer) getHibernateTemplate (). Save (Photo);
}
/**
* Modify the specified Photo instance
*
* @param Photo
* Photo instance that needs to be modified
*/
public void update (Photo Photo) {
GethibernateTemplate (). Update (Photo);
}
/**
* Delete the specified Photo instance
*
* @param Photo
* Photo instance that needs to be deleted
*/
public void delete (Photo Photo) {
getHibernateTemplate (). Delete (Photo);
}
/**
* Delete Photo instance according to the identifier attribute
*
* @param ID
* The attribute value of the identifier of the Photo instance that needs to be deleted
*/
public void delete (integer id) {
getHibernateTemplate (). Delete (get (ID));
}
/**
* Query all Photo instances
*
* All Photo instances in @Return database
*/
public list <photo> findall () {
Return (list <photo>) GethibernateTemplate (). Find ("From Photo");
}
/**
* The query is a photo of the designated user, and paging control
*
* @param user
* Query the user of the photo to belong to
* @param Pageno
* The specified page you need to query
* Photos querying @Return
*/
public list <Photo> FindByuser (User User, Int Pageno) {
int office = (pageno -1) * page_size;
// Return to the results of pagination query
Return (list <photo>) Findbypage ("From Photo B WHERE B.User =?", User,
Offset, page_size);
}
}
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 ("Unched")
Public Class UserDaohibernate Extends Hongtenhibernatedaosupport Implements
UserDao {
/**
* Load the user instance according to the identifier attribute
*
* @param ID
* The identifier attribute value of the user instance that needs to be loaded
* @Return Specify the user instance corresponding to the logo attribute
*/
public user get (integer id) {
Return (user) getHibernateTemplate (). Get (user.class, id);
}
/**
* Specific User instance
*
* @param user
* Need to be durable User instance
* @Return user instance that is persistently identifiable attribute value
*/
Public Integer Save (User User) {
Return (Integer) getHibernateTemplate (). Save (user);
}
/**
* Modify the specified user instance
*
* @param user
* User instance that needs to be modified
*/
public void update (user user) {
getHibernateTemplate (). Update (user);
}
/**
* Delete the specified user instance
*
* @param user
* User instance that needs to be deleted
*/
public void delete (user user) {
getHibernateTemplate (). Delete (user);
}
/**
* Delete the USER instance according to the identifier attribute
*
* @param ID
* Need the identifier attribute value of the user instance that needs to be deleted
*/
public void delete (integer id) {
getHibernateTemplate (). Delete (get (ID));
}
/**
* Query all user instances
*
* @Return Database all the User instances in the database
*/
public list <user> Findall () {{
Return (list <user>) GethibernateTemplate (). Find ("From User");
}
/**
* Find users according to the username
*
* @param name
* The user name of the user who needs to be found
* @Return found users
*/
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;
}
}
import java.util.List;
import com.b510.album.model.photo;
import com.b510.album.model.user;
/**
* Photodao interface
*
* @author Hongten
*
*/
Public Interface Photodao {
// Control the number of photos displayed at each page with constant constant
final int page_size = 8;
/**
* Load the Photo instance according to the identifier attribute
*
* @param ID
* The attribute value of the identifier of the Photo instance that needs to be loaded
* @Return Specify Photo instance corresponding to the logo attribute
*/
Photo Get (Integer ID);
/**
* Specific Photo instance
*
* @param Photo
* Need to be persistent Photo instance
* @Return Photo instance that is persistent after the identifier attribute value
*/
Integer save (Photo Photo);
/**
* Modify the specified Photo instance
*
* @param Photo
* Photo instance that needs to be modified
*/
void update (Photo Photo);
/**
* Delete the specified Photo instance
*
* @param Photo
* Photo instance that needs to be deleted
*/
void delete (Photo Photo);
/**
* Delete Photo instance according to the identifier attribute
*
* @param ID
* The attribute value of the identifier of the Photo instance that needs to be deleted
*/
void delete (integer id);
/**
* Query all Photo instances
*
* All Photo instances in @Return database
*/
List <photo> findall ();
/**
* The query is a photo of the designated user, and paging control
*
* @param user
* Query the user of the photo to belong to
* @param Pageno
* The specified page you need to query
* Photos querying @Return
*/
List <photo> FindByuser (user user, int Pageno);
}
import java.util.List;
import com.b510.album.model.user;
/**
* UserDao interface
*
* @author Hongten
*
*/
Public Interface UserDao {
/**
* Load the user instance according to the identifier attribute
*
* @param ID
* The identifier attribute value of the user instance that needs to be loaded
* @Return Specify the user instance corresponding to the logo attribute
*/
User get (integer ID);
/**
* Specific User instance
*
* @param user
* Need to be durable User instance
* @Return user instance that is persistently identifiable attribute value
*/
Integer save (user user);
/**
* Modify the specified user instance
*
* @param user
* User instance that needs to be modified
*/
void update (user user);
/**
* Delete the specified user instance
*
* @param user
* User instance that needs to be deleted
*/
void delete (user user);
/**
* Delete the USER instance according to the identifier attribute
*
* @param ID
* Need the identifier attribute value of the user instance that needs to be deleted
*/
void delete (integer id);
/**
* Query all user instances
*
* @Return Database all the User instances in the database
*/
List <user> Findall ();
/**
* Find users according to the username
*
* @param name
* The user name of the user who needs to be found
* @Return found users
*/
User FindByname (String name);
}
Since the project looks larger after putting the jar package, the jar package is canceled here. The required jar package is shown below:
Below is attachment : ajax_jquery_album_jb51net.rar (source code download)