Photo Album management system (Java form +xml database storage) _java

Source: Internet
Author: User
Tags flush uuid tomcat server

Upload, download and manage function files
Technology: 1. Use XML as database storage information (Dom4j,xpath)
2.Java form file upload and download
3. File directory Break (hash directory is a way to optimize the performance of file storage)


Required JAR Package:
Commons-fileupload-1.2.2.jar, Commons-io-2.1.jar, Dom4j-1.6.1.jar and Jaxen-1.1-beta-6.jar

--------------------------------------------------------------------------------

Write index.jsp first.

<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%> <!

DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
 
 

upload.jsp is the download page placed in the JSPs directory

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <!

DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
 
 

Photos.xml placed in the SRC directory

<?xml version= "1.0" encoding= "UTF-8"?>
<photos>
</photos>

Photomodel in write-valued objects

Package cn.hncu.demain;
 public class Photomodel {private String ID;
 Private String realname;
 Private String ext;
 Private String dir;
 Private String DateTime;
 Private String IP;
 Private String desc;
 Public String GetId () {return id;
 public void SetId (String id) {this.id = ID;
 Public String Getrealname () {return realname;
 } public void Setrealname (String realname) {this.realname = Realname;
 Public String Getext () {return ext;
 public void Setext (String ext) {this.ext = ext;
 Public String Getdir () {return dir;
 public void Setdir (String dir) {this.dir = dir;
 Public String GetDateTime () {return dateTime;
 public void SetDateTime (String dateTime) {this.datetime = datetime;
 Public String GetIP () {return IP;
 public void setIp (String IP) {this.ip = IP;
 Public String GetDesc () {return desc;
 } public void Setdesc (String desc) {THIS.DESC = desc; @Override public String toString () {return "PhoTomodel [id= + ID +], realname= "+ Realname +", ext= "+ ext +", dir= "+ dir +", datetime= "+ DateTime +", ip= "
 + IP + ", desc=" + desc + "]";

 }

}

Write Tool Class Two:
Myutil (date format, directory break code, random ID code)

Package cn.hncu.utils;

Import Java.text.SimpleDateFormat;
Import java.util.Date;
Import Java.util.UUID;

public class Myutils {
 private myutils () {
 }
 private static SimpleDateFormat format=new SimpleDateFormat (" YYYY year mm month DD Day Hh:mm:ss ");
 public static String GetCurrentDateTime () {return
  Format.format (new Date ());
 }
 public static String Getuuid () {
  UUID uuid=uuid.randomuuid ();
  String id=uuid.tostring (). ReplaceAll ("-", "");
  return ID;
 }
 public static string Getdir (String uuid) {
  string dir1=integer.tohexstring (Uuid.hashcode () & 0xf);
  String dir2=integer.tohexstring ((Uuid.hashcode () & 0xf0) >>4);
  return dir1+ "/" +DIR2;
 }
}

Dom4jfactory (DOM4J related operations, get Document object, save operation)

Package cn.hncu.utils;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;

Import java.io.UnsupportedEncodingException;
Import org.dom4j.Document;
Import org.dom4j.DocumentException;
Import Org.dom4j.io.OutputFormat;
Import Org.dom4j.io.SAXReader;

Import Org.dom4j.io.XMLWriter;
 public class Dom4jfactory {private static Document dom = null;
 private static String path;
   static {try {saxreader sax = new Saxreader ();  Learn how to load the resource path under the server (because our resources have been released from MyEclipse to the Tomcat server, so it's not the same as the original Pure Java Project)/////class loader with the current class to find its ClassLoader, and then get the resource path via the ClassLoader.
   Dom4jFactory.class.getClassLoader (). GetResource ("Photos.xml"). GetPath ();
  Dom = Sax.read (new FileInputStream (path));
  catch (Exception e) {throw new RuntimeException (E.getmessage (), E);
 The public static Document GetDOM () {return DOM;
   public static Boolean Save () {try {OutputFormat format=new outputformat (); Format.setencoding ("Utf-8");
   XMLWriter w = new XMLWriter (new FileOutputStream (New File (path)), format);
   W.write (DOM);
   W.close ();
  return true;
  catch (Exception e) {return false;

 }
 }
}

Write Photodao from the bottom

Package Cn.hncu.dao;
Import java.util.ArrayList;
Import Java.util.Iterator;

Import java.util.List;
Import org.dom4j.Document;

Import org.dom4j.Element;
Import Cn.hncu.demain.PhotoModel;


Import Cn.hncu.utils.Dom4jFactory;
  public class Photodao {//Add public boolean Add (Photomodel photo) {Document dom=dom4jfactory.getdom ();
  Element root=dom.getrootelement ();
  Element ephoto=root.addelement ("photo");
  Ephoto.addattribute ("id", Photo.getid ());
  Ephoto.addattribute ("Realname", Photo.getrealname ());
  Ephoto.addattribute ("dir", Photo.getdir ());
  Ephoto.addattribute ("IP", Photo.getip ());
  Ephoto.addattribute ("DateTime", Photo.getdatetime ());
  Ephoto.addattribute ("ext", Photo.getext ());

  Ephoto.addelement ("desc"). SetText (Photo.getdesc ());
  Boolean boo=dom4jfactory.save ();
 return boo;
  //Browse public list<photomodel> GetAll () {Document dom=dom4jfactory.getdom ();
  List<photomodel> list=new arraylist<photomodel> (); Element root=dom.getrootelement ();
  Iterator<element> It=root.elementiterator ();
   while (It.hasnext ()) {Photomodel photo=new photomodel ();
   Element E=it.next ();
   Photo.setid (E.attributevalue ("id"));
   Photo.setdatetime (E.attributevalue ("DateTime"));
   Photo.setdir (E.attributevalue ("dir"));
   Photo.setext (E.attributevalue ("ext"));
   Photo.setip (e.attributevalue ("IP"));
   Photo.setrealname (E.attributevalue ("Realname"));
   Photo.setdesc (E.elementtext ("desc"));
  List.add (photo);
 } return list;
  Public Photomodel Getsinglebyid (String id) {Document dom=dom4jfactory.getdom ();
  List<photomodel> List=getall ();
   for (Photomodel photo:list) {if (Photo.getid (). Equals (ID)) {return photo;
 } return null;
  public Boolean del (String id) {Document dom=dom4jfactory.getdom ();
  Element e= (Element) Dom.selectsinglenode ("//photo[@id = '" +id.trim () + "']");

 Return E.getparent (). Remove (e);

 }
}

Finally, write four servlet
Uploadservlet Upload servlet Code

Package cn.hncu.servlets;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.PrintWriter;

Import java.util.List;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.commons.fileupload.FileItem;
Import org.apache.commons.fileupload.FileUploadException;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;
Import Org.apache.commons.fileupload.servlet.ServletFileUpload;

Import Org.apache.commons.io.FileUtils;
Import Cn.hncu.dao.PhotoDao;
Import Cn.hncu.demain.PhotoModel;

Import Cn.hncu.utils.MyUtils; public class Uploadservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Respo
  NSE) throws Servletexception, IOException {response.setcontenttype ("text/html;charset=utf-8");
  PrintWriter out = Response.getwriter (); Out.println ("<! DOCTYPE HTML Public \ "-//w3c//dtd HTML 4.01 transitional//en\" > ");
  Out.println ("<HTML>");
  Out.println (" 

Showservlet Browsing the servlet side of albums

Package cn.hncu.servlets;
Import java.io.IOException;
Import Java.io.PrintWriter;

Import java.util.List;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import Cn.hncu.dao.PhotoDao;

Import Cn.hncu.demain.PhotoModel; public class Showservlet extends HttpServlet {ioexception If a error occurred public void doget (httpservletrequest
 Request, HttpServletResponse response) throws Servletexception, IOException {doPost (request, response); 

  public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
  Response.setcontenttype ("Text/html;charset=utf-8");
  Request.setcharacterencoding ("Utf-8");
  PrintWriter out = Response.getwriter (); Out.println ("<!
  DOCTYPE HTML public \-//w3c//dtd HTML 4.01 transitional//en\ ">");
  Out.println ("<HTML>"); Out.println (" 

Downservlet downloaded server code

Package cn.hncu.servlets;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.io.PrintWriter;

Import Java.net.URLEncoder;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import Cn.hncu.dao.PhotoDao;

Import Cn.hncu.demain.PhotoModel; public class Downservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse respons
 E) throws Servletexception, IOException {doPost (request, response); 
  public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
  String id=request.getparameter ("id");
  Response.setcontenttype ("Application/force-download");
  Photomodel p=new Photodao (). Getsinglebyid (ID);
   if (p!=null) {String realname=p.getrealname (); RealnamE=new String (realname.getbytes ("iso8859-1"), "Utf-8");
   Response.setheader ("Content-disposition", "attachment;filename=\", "+realname+");
   String Relpath=getservletcontext (). Getrealpath ("/photos/" +p.getdir () + "/" +p.getid () +p.getext ());
   InputStream in=new FileInputStream (RelPath);
   OutputStream Out=response.getoutputstream ();
   System.out.println (RelPath);
   byte buf[]=new byte[1024];
   int len=0;
   while ((Len=in.read (BUF))!=-1) {out.write (Buf,0,len);
  } out.close ();
   }else{Response.setcontenttype ("Text/html;charset=utf-8");
  Response.getwriter (). println ("The file has been deleted!");

 }
 }

}

Delservlet Server for delete operations

Package cn.hncu.servlets;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;

Import Java.io.PrintWriter;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import Cn.hncu.dao.PhotoDao;

Import Cn.hncu.demain.PhotoModel; public class Delservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse respons
 E) throws Servletexception, IOException {doPost (request, response); 

  public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
  Request.setcharacterencoding ("Utf-8");
  Response.setcontenttype ("Text/html;charset=utf-8");
  PrintWriter Out=response.getwriter ();
  String id=request.getparameter ("id");
  Photomodel p=new Photodao (). Getsinglebyid (ID); if (p!=null) {if (!p. GetIP (). Equals (Request.getremoteaddr ()) {out.println ("You have no right to delete!")
    ");
   Return
   //※※※※ the following part of the lesson to knock!!!!
   1 Delete the information in the database Photodao dao=new Photodao ();
   Boolean Boo=dao.del (ID);
    2 Remove files from the server hard disk if (boo) {String filename= "photos/" +p.getdir () + "/" +p.getid () +p.getext ();
    String pathfilename = Getservletcontext (). Getrealpath (FileName);
    File F=new file (pathfilename);
    if (f.exists ()) {f.delete ();
    String strpath = Request.getcontextpath () + "/servlets/showservlet";
   Out.println ("Photo deletion success!<a href= '" +strpath+ "' > Browse albums </a>");
   }else{out.println ("Photo deletion failed!");
   }}else{Response.setcontenttype ("Text/html;charset=utf-8");
  Response.getwriter (). println ("The file does not exist!");

 }
 }
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.