Electronic album of of with source code download based on spring+hibernate+JQuery

  • 2020-04-01 01:48:32
  • OfStack

Project structure:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013050217183545.png "width = 265 height = 477 >

Project home page:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013050217183546.png "width = 621 height = 480 >

Registration page:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013050217183547.png "width = 621 height = 480 >

Photos uploaded:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013050217183548.png "width = 624 height = 480 >

Effect picture 1:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013050217183549.png "width = 624 height = 480 >

Effect picture 2:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013050217183550.png "width = 624 height = 480 >

Effect picture 3:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013050217183551.png "width = 625 height = 480 >

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

Here is the code section

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

Database SQL needed:


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>  Electronic photo album system  </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> Electronic photo album system </h3></caption>
 <tr>
 <td height="60" colspan="2">
 <!--  No login is shown below div The element  -->
 <div id="noLogin">
 <!--  This is registration / Login form  -->
 <table width="100%" border="0" cellspacing="0">
 <tr>
     <td width="38%"> User name: 
         <input id="user" type="text" name="user" /></td>
     <td width="38%"> The secret    Code: 
         <input id="pass" type="text" name="pass" /></td>
     <td width="24%"> I haven't registered yet, please let me <a href="javascript:void(0);"
         onclick="changeRegist();"> registered </a></td>
 </tr>
 <tr>
     <td colspan="5">
     <div id="loginDiv" align="center">
     <input id="login" type="button" onclick="proLogin();" value=" The login " />
     <input id="resetLogin" type="button" onclick="reset();" value=" reset " />
     </div>
     <div id="registDiv" align="center" style="display:none">
     <a href="javascript:void(0)" onclick="validateName();"> Verify that the username is available </a>
     <input id="regist" type="button" onclick="regist();" value=" registered " />
     <input id="resetRegist" type="button" onclick="reset();" value=" reset " />
     </div>
     </td>
 </tr>
 </table>
 </div>
 <!--  Logged in displays below div The element  -->
 <div id="hasLogin" align="center" style="display:none">
      You have logged in successfully, the following is your album, you can also <a href="javascript:void(0);" 
         onclick="openUpload();"> Add photos </a>
 </div>
 </td>
 </tr>
 <tr>
     <!--  Elements that display a list of photos  -->
     <td width="120" height="440" valign="top">
     <div align="center"><h3> Photo list </h3></div>
     <div id="list"></div><hr />
     <div align="center"><a href="javascript:void(0);" onclick="turnPage(-1);"> The previous page </a>
          <a href="javascript:void(0);" onclick="turnPage(1);"> The next page </a></div>
     </td>
     <!--  Elements that show the photo  -->
     <td width="660" align="center" valign="middle">
         <div style="width:640px;height:430px;overflow:auto">
         <img id="show" alt=" The current photo "></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> To upload pictures </caption>
 <tr>
     <td height="25"> Photo title: </td>
     <td><input id="title" name="title" type="text" /></td>
 </tr>
 <tr>
     <td height="25"> View 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>

/ 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">

     <!--  configuration Web Load at application startup Spring The container  -->
     <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"?>
 <!--  The specified Spring Profile's Schema information  -->
 <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">

     <!--  Define data source Bean , the use of C3P0 Data source implementation  -->
     <bean id="dataSource" destroy-method="close"
         class="com.mchange.v2.c3p0.ComboPooledDataSource">
         <!--  Specifies the driver to connect to the database  -->
         <property name="driverClass" value="com.mysql.jdbc.Driver"/>
         <!--  Specifies the connection to the database URL -->
         <property name="jdbcUrl"
             value="jdbc:mysql://localhost:3308/db_ajax"/>
         <!--  Specifies the user name to connect to the database  -->
         <property name="user" value="root"/>
         <!--  Specifies the password to connect to the database  -->
         <property name="password" value="root"/>
         <!--  Specifies the maximum number of connections to the connection database connection pool  -->
         <property name="maxPoolSize" value="40"/>
         <!--  Specifies the minimum number of connections to the connection database connection pool  -->
         <property name="minPoolSize" value="1"/>
         <!--  Specifies the number of initial connections to the connection database connection pool  -->
         <property name="initialPoolSize" value="1"/>
         <!--  Specifies the maximum idle time for a connection to a database connection pool  -->
         <property name="maxIdleTime" value="20"/>
     </bean>

     <!--  define Hibernate the SessionFactory -->
     <bean id="sessionFactory"
         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
         <!--  Dependency injection data sources, as defined above dataSource -->
         <property name="dataSource" ref="dataSource"/>
         <!-- mappingResouces Property to list all the mapping files  -->
         <property name="mappingResources">
             <list>
                 <!--  The following is used to list Hibernate The mapping file  -->
                 <value>com/b510/album/model/User.hbm.xml</value>
                 <value>com/b510/album/model/Photo.hbm.xml</value>
             </list>
         </property>
         <!--  define Hibernate the SessionFactory The properties of the  -->
         <property name="hibernateProperties">
             <props>
                 <!--  Specify database dialect  -->
                 <prop key="hibernate.dialect">
                     org.hibernate.dialect.MySQLInnoDBDialect</prop>
                 <!--  Whether the database is automatically created each time as needed  -->
                 <prop key="hibernate.hbm2ddl.auto">update</prop>
                 <!--  According to Hibernate Generated by a persistent operation SQL -->
                 <prop key="hibernate.show_sql">true</prop>
                 <!--  will SQL The script is formatted before output  -->
                 <prop key="hibernate.format_sql">true</prop>
             </props>
         </property>
     </bean>
     <!--  configuration UserDao component  -->
     <bean id="userDao"
         class="com.b510.album.dao.impl.UserDaoHibernate">
         <!--  injection SessionFactory reference  -->
         <property name="sessionFactory" ref="sessionFactory"/>
     </bean>
     <!--  configuration PhotoDao component  -->
     <bean id="photoDao"
         class="com.b510.album.dao.impl.PhotoDaoHibernate">
         <property name="sessionFactory" ref="sessionFactory"/>
     </bean>
     <!--  configuration albumService Business logic component  -->
     <bean id="albumService"
         class="com.b510.album.service.impl.AlbumServiceImpl">
         <!--  Inject the business logic component 2 a DAO component  -->
         <property name="userDao" ref="userDao"/>
         <property name="photoDao" ref="photoDao"/>
     </bean>

     <!--  configuration Hibernate Local transaction manager, using HibernateTransactionManager class  -->
     <!--  This class to implement PlatformTransactionManager Interface is for Hibernate Specific implementation -->
     <bean id="transactionManager" 
         class="org.springframework.orm.hibernate3.HibernateTransactionManager">
         <!--  configuration HibernateTransactionManager When injection is required SessionFactory A reference to the  -->
         <property name="sessionFactory" ref="sessionFactory"/>
     </bean>

     <!--  Configure the transaction aspect Bean, Specify the transaction manager  -->
     <tx:advice id="txAdvice" transaction-manager="transactionManager">
         <!--  Used to configure detailed transaction semantics  -->
         <tx:attributes>
             <!--  All to 'get' The way to start is read-only the  -->
             <tx:method name="get*" read-only="true"/>
             <!--  Other methods use the default transaction Settings  -->
             <tx:method name="*"/>
         </tx:attributes>
     </tx:advice>
     <aop:config>
         <!--  Configure a pointcut to match lee Pack all of them Impl All methods executed by the ending class  -->
         <aop:pointcut id="leeService"
             expression="execution(* com.b510.album.service.impl.*Impl.*(..))"/>
         <!--  Specified in the leeService Pointcut application txAdvice Affairs section  -->
         <aop:advisor advice-ref="txAdvice" 
             pointcut-ref="leeService"/>
     </aop:config>
 </beans>

/ ajax_0500_jQuery_album/WebRoot/js/album. Js

$(document).ready(function(){
     $.getScript("pageLoad");
     //Handles the resultCode parameter for the address bar
     var locationStr = document.location.toString();
     var resultIndex = locationStr.indexOf("resultCode");
     var resultCode = -1;
     if (resultIndex > 1)
     {
         resultCode = locationStr.substring(resultIndex + 11 
             , resultIndex + 12);
         //According to different resultCode, the system can handle different processing
         switch(resultCode)
         {
             case "0" :
                 alert(' Congratulations! The file was uploaded successfully! ');
                 $('#uploadDiv').dialog('close');
                 break;
             case "1" :
                 alert(' Upload is only allowed in this system JPG , GIF , PNG Picture file, please try again! ');
                 $('#title,#file').val('');
                 break;
             case "2" :
                 alert(' An error occurred in processing the uploaded file. Please try again! ');
                 $('#title,#file').val('');
                 break;
         }
     }
 });

 function reset()
 {
     //Clear the user and pass single-line text boxes
     $("#user").val("");
     $("#pass").val("");
 }

 //Switch to the registration dialog box
 function changeRegist()
 {
     //Hide the two buttons for login
     $("#loginDiv").hide("500");
     //Displays two buttons for registration
     $("#registDiv").show("500");
 }

 //Functions that handle user login
 function proLogin()
 {
     //Gets the values of the user and pass text boxes
     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 to log in ");
         return false;
     }
     else
     {
         //Send an asynchronous, POST request to proLogin
         $.post("proLogin", $('#user,#pass').serializeArray()
             , null , "script");
     }
 }

 //Functions that handle user registration
 function regist()
 {
     //Gets the values of the user and pass text boxes
     var user = $.trim($("#user").val());
     var pass = $.trim($("#pass").val());
     if (user == null || user == "" || pass == null || pass =="")
     {
         alert(" You must enter a username and password to register ");
         return false;
     }
     else
     {
         //Send an asynchronous, POST request to the proRegist
         $.post("proRegist", $('#user,#pass').serializeArray()
             , null , "script");
     }
 }

 //Verify that the username is available
 function validateName()
 {
     //Gets the value of the user text box
     var user = $.trim($("#user").val());
     if (user == null || user == "")
     {
         alert(" You have not entered a user name! ");
         return false;
     }
     else
     {
         //Sends an asynchronous, POST request to validateName
         $.post("validateName", $('#user').serializeArray()
             , null , "script");
     }
 }

 //Periodically gets photos of the current user, the current page
 function onLoadHandler()
 {
     //Send an asynchronous, GET request to getPhoto
     $.getScript("getPhoto");
     //Specifies 1 second to execute this method again
     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);
 }

 //Handles page-turning functions
 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"}
         });
 }

/ 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;
 
 public class BaseServlet extends HttpServlet {

     private static final long serialVersionUID = -2041755371540813745L;

     protected AlbumService as;

     //Define a constructor to get 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");
     }
 }

/ 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;
 
 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, the user name is not yet used, you can use the user name! ');");
                 } else {
                     out.println("alert(' Sorry, the user name has been occupied by someone else! ');");
                     out.println("$('#user').val('');");
                 }
             } else {
                 out.println("alert(' Verify that the user name is abnormal, please change the user name and try again! ');");
             }
         } catch (AlbumException ex) {
             out.println("alert('" + ex.getMessage() + " Please change your username and try again! ');");
         }
     }
 }

/ 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;
 
 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 the 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, unable to turn the page forward! ')");
         } else {
             //Perform a page flip to change the value of the 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(' The system will automatically return to the previous page if no photo record can be found after turning the page ')");
                     //Return to the previous page
                     curPage -= Integer.parseInt(turn);
                 } else {
                     //Put the page number the user is browsing into HttpSession
                     session.setAttribute("curPage", curPage);
                 }
             } catch (AlbumException ex) {
                 out.println("alert('" + ex.getMessage() + " Please try again! ')");
             }
         }
     }
 }

/ 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;
 
 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);
         //Place the image the user is viewing into 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 + "');");
     }
 }

/ 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;
 
 @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();
             //Iterate over the contents of 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();
         }
     }
 }

  / 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;
 
 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 that gets the list of photos
                 out.println("onLoadHandler();");
             } else {
                 out.println("alert(' Your registration failed, please choose the appropriate user name to retry! ');");
             }
         } catch (AlbumException ex) {
             out.println("alert('" + ex.getMessage() + " Please change your username and try again! ');");
         }
     }
 }

/ 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;
 
 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 box with the id 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 that gets the list of photos
                 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! ')");
         }
     }
 }

/ 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;

 
 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 the name is not null, the user is logged in
         if (name != null) {
             //Hide 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 that gets the list of photos
             out.println("onLoadHandler();");
             //Take the curImg property in HttpSession
             String curImg = (String) session.getAttribute("curImg");
             //Redisplays the photos the user is viewing
             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
                

Related articles: