最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

相冊(cè)管理系統(tǒng)(Java表單+xml數(shù)據(jù)庫(kù)存儲(chǔ))

 更新時(shí)間:2016年07月25日 09:15:54   作者:wangjian_an  
這篇文章主要為大家詳細(xì)介紹了相冊(cè)管理系統(tǒng)的實(shí)現(xiàn)步驟,Java表單的文件上傳和下載,xml數(shù)據(jù)庫(kù)存儲(chǔ)信息,感興趣的小伙伴們可以參考一下

功能文件的上傳,下載和管理
技術(shù):1.用xml當(dāng)做數(shù)據(jù)庫(kù)存儲(chǔ)信息(dom4j,xpath)
2.Java表單的文件上傳和下載
3.文件目錄的打散 ( Hash目錄是一種優(yōu)化文件存儲(chǔ)性能的方法)


需要的jar包:
commons-fileupload-1.2.2.jar、commons-io-2.1.jar、dom4j-1.6.1.jar和jaxen-1.1-beta-6.jar

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

先寫(xiě)index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>

 <title>相冊(cè)管理系統(tǒng)</title>
 </head>

 <body>
  <h1>我的小相冊(cè)</h1>
  <a href="jsps/upload.jsp">上傳相冊(cè)</a>
  <a href="servlets/ShowServlet">瀏覽相冊(cè)</a>
 </body>
</html>

upload.jsp是下載頁(yè)面放在jsps目錄下

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 </head>

 <body>
 <h1>相處上傳</h1>
 <form action="<%=request.getContextPath()%>/servlets/UploadServlet"
   method="post" enctype="multipart/form-data">
    文件:<input type="file" name="file1"/><br/>
    說(shuō)明:<input type="text" name="desc" /><br/>
  <input type="submit" value="上傳" />
 </form>
 </body>

</html>

photos.xml放在src目錄下

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

在寫(xiě)值對(duì)象PhotoModel

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 + "]";
 }

}

寫(xiě)工具類(lèi)兩個(gè):
MyUtil(日期格式化,目錄打散代碼,隨機(jī)id代碼)

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年MM月dd日 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的相關(guān)操作,獲取document對(duì)象,保存操作)

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();
   // 學(xué)習(xí)一下服務(wù)器下的資源路徑加載方式(因?yàn)槲覀兊馁Y源已經(jīng)從MyEclipse中發(fā)布到Tomcat服務(wù)器中了,所以跟原來(lái)純Java項(xiàng)目不一樣了)
   // 利用當(dāng)前類(lèi)找到它的類(lèi)加載器,然后通過(guò)該類(lèi)加載器再去獲得資源路徑
   path = Dom4jFactory.class.getClassLoader().getResource("photos.xml")
     .getPath();
   dom = sax.read(new FileInputStream(path));
  } catch (Exception e) {
   throw new RuntimeException(e.getMessage(), e);
  }
 }
 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;
  }
 }
}

從底層寫(xiě)PhotoDao

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 {
 //添加
 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;
 }

 //瀏覽
 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("http://photo[@id='"+id.trim()+"']");
  return e.getParent().remove(e);

 }
}

最后寫(xiě)四個(gè)servlet
UploadServlet 上傳Servlet代碼

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 response)
   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(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
  out.println(" <BODY>");

  out.println("不支持get方式上傳!");

  out.println(" </BODY>");
  out.println("</HTML>");
  out.flush();
  out.close();
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  response.setContentType("text/html;charset=utf-8");

  PrintWriter out = response.getWriter();

  String path=request.getServletContext().getRealPath("/photos");
  DiskFileItemFactory factory=new DiskFileItemFactory();
  factory.setRepository(new File("g:/a"));
  ServletFileUpload upload = new ServletFileUpload(factory);
  upload.setSizeMax(1024*1024*10);//最大10M
  upload.setHeaderEncoding("utf-8");//用于設(shè)置文件名的編碼,相當(dāng)于:request.setCharacterEncoding("utf-8");

   FileItem fi=null;
   try {
   List<FileItem> list=upload.parseRequest(request);
   PhotoModel photo = new PhotoModel();//數(shù)據(jù)封裝---需要7個(gè)屬性
   boolean boo=false;
   InputStream in = null;

   for(FileItem fi2:list){
    fi=fi2;
    if(fi.isFormField()){
     String desc=fi.getString("utf-8");
     photo.setDesc(desc);//desc
    }else{
     in=fi.getInputStream();
     String realName=fi.getName();
     if(realName==null || realName.trim().equals("")){
      out.print("沒(méi)有選擇文件!");
      return;
     }
     if(realName.indexOf("\\")!=-1){
      realName=realName.substring(realName.lastIndexOf("\\")+1);
     }
     photo.setRealName(realName);//真實(shí)文件名
     String ext=realName.substring(realName.lastIndexOf("."));
     photo.setExt(ext);//3
     photo.setDateTime(MyUtils.getCurrentDateTime());//4
     photo.setId(MyUtils.getUUid());//5
     photo.setDir(MyUtils.getDir(photo.getId()));//6
     photo.setIp(request.getRemoteAddr());//7

    }
   }

   //把相片信息存儲(chǔ)到數(shù)據(jù)庫(kù)
   PhotoDao dao=new PhotoDao();
   boo=dao.add(photo);
   //如果上面的相片信息保存成功,那么才開(kāi)始接收?qǐng)D片文件,把它保存到服務(wù)器硬盤(pán)
   if(boo){
    System.out.println(dao);
    path=path+"/"+photo.getDir();
    File dir=new File(path);
    if(!dir.exists()){
     dir.mkdirs();
    }
    String fileName=path+"/"+photo.getId()+photo.getExt();
    FileUtils.copyInputStreamToFile(in, new File(fileName));
    String strPath = request.getContextPath()+"/servlets/ShowServlet";
    out.print("上傳成功!<a href='"+strPath+"'>瀏覽相冊(cè)</a>");
   }else{
    out.print("上傳失敗!");
   }
   } catch (FileUploadException e) {
   throw new RuntimeException("上傳失??!", e);
  }finally{
   if(fi!=null){
    fi.delete();
   }
  }
  out.flush();
  out.close();
 }

}

ShowServlet 瀏覽相冊(cè)的Servlet端

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 an 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(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
  out.println(" <BODY>");

  String table="<table border='1' width='100%'>"+
     "<tr><th>文件名</th><th>上傳ip</th><th>上傳時(shí)間</th><th>圖片</th><th>說(shuō)明</th><th>操作</th></tr>"
     ;
  out.print(table);
  PhotoDao dao=new PhotoDao();
  List<PhotoModel> list=dao.getAll();
  for(PhotoModel p:list){
   out.print("<tr>");
   out.println("<td>"+p.getRealName()+"</td>");
   out.println("<td>"+p.getIp()+"</td>");
   out.println("<td>"+p.getDateTime()+"</td>");
   //輸出圖片
   String path=request.getContextPath()+"/photos/"+p.getDir()+"/"+p.getId()+p.getExt();
   out.println("<td><a href='"+path+"'><img src='"+path+"' width='200' height='200'></img></a></td>");
   String op="<a href='"+request.getContextPath()+"/servlets/DelServlet?id="+p.getId()+"'>刪除</a>&nbsp;";
   out.println("<td>"+p.getDesc()+"</td>");
   op+="<a href='"+request.getContextPath()+"/servlets/DownServlet?id="+p.getId()+"'>下載</a>";
   out.println("<td>"+op+"</td>");
   out.print("</tr>");
  }

  out.println("</table>");
  out.println(" </BODY>");
  out.println("</HTML>");
  out.flush();
  out.close();
 }

}

DownServlet 下載的服務(wù)器代碼

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 response)
   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("該文件已經(jīng)被刪除!");
  }
 }

}

Delservlet 刪除操作的服務(wù)器

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 response)
   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("你無(wú)權(quán)進(jìn)行刪除!");
    return;
   }
   //※※※※以下部分課后補(bǔ)敲的!!!!
   //1刪除數(shù)據(jù)庫(kù)中的信息
   PhotoDao dao=new PhotoDao();
   boolean boo=dao.del(id);
   //2把服務(wù)器硬盤(pán)中的文件刪除
   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("相片刪除成功!<a href='"+strPath+"'>瀏覽相冊(cè)</a>");
   }else{
    out.println("相片刪除失敗!");
   }
  }else{
   response.setContentType("text/html;charset=utf-8");
   response.getWriter().println("該文件不存在!");
  }
 }
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 巧妙的利用Mongodb做地理空間查詢

    巧妙的利用Mongodb做地理空間查詢

    本篇文章將會(huì)以Mongodb為數(shù)據(jù)庫(kù),講述如何在數(shù)據(jù)庫(kù)層級(jí)進(jìn)行定位查詢。具有很好的參考價(jià)值,下面跟著小編一起來(lái)看下吧
    2017-02-02
  • java實(shí)現(xiàn)哈夫曼文件解壓縮

    java實(shí)現(xiàn)哈夫曼文件解壓縮

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)哈夫曼文件解壓縮,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-06-06
  • 詳解SpringCloud Config配置中心

    詳解SpringCloud Config配置中心

    這篇文章主要介紹了詳解SpringCloud Config配置中心,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2019-03-03
  • java poi解析word的方法

    java poi解析word的方法

    這篇文章主要為大家詳細(xì)介紹了java poi解析word的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-05-05
  • 淺談單例模式和線程安全問(wèn)題

    淺談單例模式和線程安全問(wèn)題

    這篇文章主要介紹了淺談單例模式和線程安全問(wèn)題,再某些特殊的情況下,存在一個(gè)類(lèi)僅能用來(lái)產(chǎn)生一個(gè)唯一對(duì)象的必要性,因此需要單例模式,需要的朋友可以參考下
    2023-04-04
  • java處理數(shù)據(jù)庫(kù)不支持的emoji表情符問(wèn)題解決

    java處理數(shù)據(jù)庫(kù)不支持的emoji表情符問(wèn)題解決

    這篇文章主要介紹了java處理數(shù)據(jù)庫(kù)不支持的emoji表情符問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09
  • SpringBoot實(shí)現(xiàn)版本升級(jí)到2.7.18

    SpringBoot實(shí)現(xiàn)版本升級(jí)到2.7.18

    這篇文章主要介紹了SpringBoot實(shí)現(xiàn)版本升級(jí)到2.7.18全過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • spring mvc配置bootstrap教程

    spring mvc配置bootstrap教程

    這篇文章主要為大家詳細(xì)介紹了spring mvc配置bootstrap,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-07-07
  • Yml轉(zhuǎn)properties文件工具類(lèi)YmlUtils的詳細(xì)過(guò)程(不用引任何插件和依賴)

    Yml轉(zhuǎn)properties文件工具類(lèi)YmlUtils的詳細(xì)過(guò)程(不用引任何插件和依賴)

    這篇文章主要介紹了Yml轉(zhuǎn)properties文件工具類(lèi)YmlUtils(不用引任何插件和依賴),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-08-08
  • Java通過(guò)百度地圖API獲取定位(普通IP定位)的方法教程

    Java通過(guò)百度地圖API獲取定位(普通IP定位)的方法教程

    這篇文章主要介紹了Java通過(guò)百度地圖API獲取定位的方法教程,首先說(shuō)明了實(shí)現(xiàn)這個(gè)功能的需求和初衷,然后詳細(xì)描述了利用百度地圖API實(shí)現(xiàn)這個(gè)功能的步驟,包括在百度地圖開(kāi)放平臺(tái)的準(zhǔn)備工作、學(xué)習(xí)官網(wǎng)API文檔、修改API的AK配置、Java代碼獲取定位等,需要的朋友可以參考下
    2024-11-11

最新評(píng)論

旺苍县| 枞阳县| 安塞县| 姚安县| 青冈县| 柳江县| 灵台县| 吉隆县| 库尔勒市| 驻马店市| 会同县| 隆子县| 永寿县| 榕江县| 贵州省| 临澧县| 邹城市| 曲阜市| 根河市| 荃湾区| 云阳县| 都昌县| 灌云县| 屏东县| 凤翔县| 洪江市| 浦东新区| 秀山| 凌云县| 凌海市| 会宁县| 天全县| 逊克县| 余庆县| 绥芬河市| 金川县| 凌海市| 江口县| 达拉特旗| 纳雍县| 孝义市|