精細玲珑的java相冊制造辦法。本站提示廣大學習愛好者:(精細玲珑的java相冊制造辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是精細玲珑的java相冊制造辦法正文
本文實例為年夜家分享了java相冊制造辦法,供年夜家參考,詳細內容以下
注:
1)html上的圖片是靜態指定的。當更新了新的圖片時必需手工更新。所以應用Servlet讀取當地images中的一切圖片,靜態顯示給用戶。
2)假如存在中文名的圖片,因為get方法沒法直接傳遞中文,會招致失足。
主頁面–index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>小小相冊</title> </head> <body> <!-- http://localhost:8080/photosWeb/ --> <h2>小小相冊</h2> <a href="jsps/upload.jsp">上傳相片</a> <a href="<%=request.getContextPath() %>/servlet/showAllImg">閱讀相片</a> </body> </html>
頁面顯示:
上傳圖片功效:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>小小相冊</title> </head> <body> <h2>小小相冊</h2> <form action="<%=request.getContextPath() %>/servlet/uploadServlet" method="post" enctype="multipart/form-data"> 照片:<input type="file" name="file"/><br/> 解釋:<input type="text" name="desc"/><br/> <input type="submit" value="上傳"/> </form> </body> </html>
package cn.hncu.servlet; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import javax.servlet.RequestDispatcher; 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.PhotoDaoImpl; import cn.hncu.domain.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"); 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.print("毛病信息:提交方法毛病...不支撐Get方法上傳照片"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } 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(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>上傳照片頁面</TITLE></HEAD>"); out.println(" <BODY>"); //從上傳表單提守信息:一,封裝成photo值對象,挪用dao層存儲到後台 // 二,把上傳的照片存儲到辦事器硬盤 //數據庫:存儲照片的存儲情形的信息,,,真實的文件存儲到硬盤 DiskFileItemFactory dfi=new DiskFileItemFactory(); File file=new File("d:/a"); if(file.exists()){ file.mkdirs(); } dfi.setRepository(file); ServletFileUpload upload=new ServletFileUpload(dfi); upload.setSizeMax(1024*1024*8); upload.setHeaderEncoding("utf-8");//==>request.setCharacterEncoding("utf-8"); try { List<FileItem> list=upload.parseRequest(request); PhotoModel pm=new PhotoModel(); InputStream in=null; for(FileItem fI:list){ if(fI.isFormField()){//這個不會有暫時文件 String desc=fI.getString("utf-8"); pm.setDesc(desc); }else{ in=fI.getInputStream(); // String filename=fI.getFieldName(); // System.out.println("getFieldName:"+filename); String fileName=fI.getName(); // System.out.println("getName:"+fileName);//測試:C:\Users\adl1\Pictures\Saved Pictures\111.jpg? //衛前提 if(fileName==null||fileName.trim().equals("")){ out.println("沒有選擇文件,,,請必需選擇一個文件...<br/>"); String strPath2=request.getContextPath()+"/jsps/upload.jsp"; out.println("<a href=\""+strPath2+"\">前往上傳頁面</a>"); return; } pm.setDt(MyUtils.getCurrentDataime()); String realName=fileName.substring(fileName.lastIndexOf("\\"));//"\112.jpg" System.out.println(realName.substring(1, realName.length())); pm.setRealName(realName.substring(1, realName.length()));//把realName的"\"去失落 //ext擴大名 String ext=fileName.substring(fileName.lastIndexOf(".")); pm.setExt(ext); String id=MyUtils.getUUID(); pm.setId(id); pm.setIp(request.getRemoteAddr()); pm.setDir(MyUtils.getDir(id)); } } //完成photo值對象的封裝,挪用dao停止存儲 boolean boo=new PhotoDaoImpl().sava(pm); if(boo){ //完成數據庫的存儲,接上去是辦事器硬盤的存儲 //把照片存儲到項目根目次下的photos文件夾中存儲(以打散方法存儲) String path="photos/"+pm.getDir(); // System.out.println("path:"+path);//測試:photos/9/0 String filePath=getServletContext().getRealPath(path); // System.out.println("filePath:"+filePath);//測試:D:\apache-tomcat-7.0.30\webapps\photosWeb\photos\9\0 File dir=new File(filePath); if(!dir.exists()){ dir.mkdirs(); } FileUtils.copyInputStreamToFile(in, new File(filePath+"/"+pm.getId()+pm.getExt())); // //假如硬盤保留勝利就跳轉到主頁面--轉發 //// RequestDispatcher rd=request.getRequestDispatcher(getServletContext().getContextPath()+"/index.jsp");//"/photosWeb/photosWeb/index.jsp" // RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");//"/photosWeb/index.jsp"g // //java代碼塊和web.xml中url的開端"/"代表項目根目次 // rd.forward(request, response); //這裡不克不及應用轉發,詳細重定向和轉發差別:http://blog.csdn.net/xanlv/article/details/52701085 //重定向 response.sendRedirect(getServletContext().getContextPath()+"/index.jsp"); }else{ //數據庫保留掉敗--留在上傳頁面 RequestDispatcher rd=request.getRequestDispatcher("/jsps/upload..jsp");//"/photosWeb/index.jsp" rd.forward(request, response); } } catch (FileUploadException e) { throw new RuntimeException("上傳掉敗", e); }finally{//清暫時文件 File f=new File("d:/a"); File fs[]=f.listFiles(); for(File ff:fs){ ff.delete(); } } out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
頁面顯示後果:
閱讀圖片功效:
package cn.hncu.servlet; 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.PhotoDaoImpl; import cn.hncu.domain.PhotoModel; public class ShowAllImgServlet 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>相冊閱讀</TITLE></HEAD>"); out.println(" <BODY>"); String strPath=request.getContextPath()+"/jsps/upload.jsp"; out.println("<a href=\""+strPath+"\">前往上傳頁面</a>"); //String table="<table border='1px' width='100%' cellspacing='0' align='center'>"+//這類方法弗成以設置程度居中 String table="<table border='1px' width='100%' cellspacing='0' style='text-align: center;'>"+ "<tr><th>文件名</th><th>上傳日期時光</th><th>相片</th><th>相片解釋</th><th>操作</th></tr>"; out.println(table); //從dao層把一切的照片信息讀掏出來發送到前端頁面 List<PhotoModel> list=new PhotoDaoImpl().getAllPhotos(); for(PhotoModel pm:list){ out.println("<tr>"); out.println("<td width=80>"+pm.getRealName()); out.println("</td>"); out.println("<td width=120>"+pm.getDt()); out.println("</td>"); String path=request.getContextPath()+"/photos/"+pm.getDir()+"/"+pm.getId()+pm.getExt(); //System.out.println(path);//"/photosWeb/photos/d/7/e78e18352b42410f85dbd8df834bd718.jpg" //點擊圖片可以檢查年夜圖 out.println("<td width=100><a href='"+path+"'><img width=100 height=100 src='"+path+"'/></a>"); out.println("</td>"); out.println("<td width=200>"+pm.getDesc()); out.println("</td>"); out.println("<td width=80><a href='"+getServletContext().getContextPath()+"/servlet/delPhoto?id="+pm.getId()+"'>刪除圖片</a>"); //out.println("<a href='<%=request.getContextPath()%>/servlet/down?id="+pm.getId()+"'>下載圖片</a></td>"); out.println("<br/><a href='"+getServletContext().getContextPath()+"/servlet/down?id="+pm.getId()+"'>下載圖片</a></td>"); out.println("</tr>"); } out.println("</table>"); 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(); 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.print("不支撐Post方法。。。"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
頁面顯示後果:
刪除功效:
package cn.hncu.servlet; import java.io.File; import java.io.IOException; 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.PhotoDaoImpl; import cn.hncu.domain.PhotoModel; public class DelPhotoServlet 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>刪除照片頁面</TITLE></HEAD>"); out.println(" <BODY>"); String id=request.getParameter("id"); String ip=request.getRemoteAddr(); PhotoDaoImpl dao=new PhotoDaoImpl(); PhotoModel pm=dao.getSingleById(id); if(pm!=null){ if(!pm.getIp().equals(ip)){ out.println("您沒有該圖片的權限去刪除..."); String strPath=request.getContextPath()+"/servlet/showAllImg"; out.println("<br/><a href=\""+strPath+"\">前往持續閱讀</a>"); return ; } //刪除包括兩部門任務:消除數據庫中的信息 和 刪除辦事器硬盤中的圖片文件 //1消除數據庫中的信息 boolean boo = dao.del(id); //2刪除辦事器硬盤中的圖片文件 if(boo){ String path="photos/"+pm.getDir()+"/"+pm.getId()+pm.getExt(); String filePath=getServletContext().getRealPath(path); File f=new File(filePath); if(f.exists()){ f.delete(); } String strPath=request.getContextPath()+"/servlet/showAllImg"; // System.out.println(strPath);///photosWeb/servlet/showPhotos out.println("刪除勝利...<br/><a href=\""+strPath+"\">前往閱讀</a>"); }else{ out.println("刪除數據庫信息掉敗"); } }else{ out.println("文件不存在..."); String strPath=request.getContextPath()+"/servlet/showAllImg"; out.println("<br/><a href=\""+strPath+"\">前往持續閱讀</a>"); } out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>刪除照片頁面</TITLE></HEAD>"); out.println(" <BODY>"); out.print("不支撐POST方法..."); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
頁面顯示:
下載功效:
1.在HTML頁面上應用超銜接指向要下載的文件(不平安輕易被盜鏈)。
成績:
若何肯定當地資本?
ServletContext – 代表一個web項目。一個web項目只要一個ServletContext對像。
getRealPath(“/”); //d:/prm/tom/web/
需求剖析:
在現實的開辟中,下載哪個文件,都是由用戶靜態選擇的。
如,在我們項目images目次下,存在著許多圖片文件。用戶在頁面上顯示一切圖片,用戶可以點下載銜接下載愛好的圖片。
具體設計:
應用靜態網頁顯示一切圖片。給每個圖片一個下以下載的超銜接。
在超銜接前面傳遞要下載的圖片id。
在serivice中靜態吸收圖片名。完成下載 。
package cn.hncu.servlet; 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 java.net.URLEncoder; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import cn.hncu.dao.PhotoDaoImpl; import cn.hncu.domain.PhotoModel; public class DownServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲得被下載圖片的信息 tring id=request.getParameter("id"); PhotoModel pm=new PhotoDaoImpl().getSingleById(id); if(pm==null){ 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>"); response.getWriter().println("alert('該文本已不存在...')"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); //getServletContext().getContextPath() RequestDispatcher rd=request.getRequestDispatcher("/servlet/down");//"/photosWeb/index.jsp" //java代碼塊和web.xml中url的開端"/"代表項目根目次 rd.forward(request, response); }else{ //真正下載: 把辦事器硬盤的照片文件讀掏出來發送給客戶端(設置呼應頭) //獲得真實的文件 String realName=pm.getRealName(); realName=URLEncoder.encode(realName, "utf-8");//假如是中文名必需轉碼,避免文件名中文亂碼 // InputStream in=DownServlet.class.getClassLoader().getResourceAsStream(realName); //設置顯示類型為下載 response.setContentType("application/force-download"); //設置呼應頭 response.setHeader("content-Disposition", "attachment;filename=\""+realName+"\""); // String path=request.getContextPath()+"/photos/"+pm.getDir()+"/"+pm.getId()+pm.getExt(); String path="photos/"+pm.getDir()+"/"+pm.getId()+pm.getExt(); String filePath=getServletContext().getRealPath(path); FileUtils.copyInputStreamToFile(request.getInputStream(), new File(filePath)); InputStream in=new FileInputStream(filePath); OutputStream o=response.getOutputStream(); byte b[]=new byte[1024]; int len=0; while((len=in.read(b))!=-1){ o.write(b, 0, len); } o.close(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); 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.print(" 不支撐"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
頁面顯示後果:
設置裝備擺設文件web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.xsd"> <display-name></display-name> <servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>cn.hncu.servlet.UploadServlet</servlet-class> </servlet> <servlet> <servlet-name>ShowAllImgServlet</servlet-name> <servlet-class>cn.hncu.servlet.ShowAllImgServlet</servlet-class> </servlet> <servlet> <servlet-name>DownServlet</servlet-name> <servlet-class>cn.hncu.servlet.DownServlet</servlet-class> </servlet> <servlet> <servlet-name>DelPhotoServlet</servlet-name> <servlet-class>cn.hncu.servlet.DelPhotoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/servlet/uploadServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ShowAllImgServlet</servlet-name> <url-pattern>/servlet/showAllImg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>DownServlet</servlet-name> <url-pattern>/servlet/down</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>DelPhotoServlet</servlet-name> <url-pattern>/servlet/delPhoto</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
數據庫:photos.xml
<?xml version="1.0" encoding="UTF-8"?> <photos> <!-- 數據庫設計 <photo id="uuid" realName="真實文件名.jpg" dT="2016-10-03 19:51:31" ext=".jpg" dir="a/5" ip="192.168.12.12"> <desc>照片解釋信息</desc> </photo> --> </photos>
值對象:PhotoModel.java
package cn.hncu.domain; public class PhotoModel { //photo值對象 private String id;//UUID private String realName;//照片真實文件名 private String ext;//擴大名 private String dir;//文件打撒後存儲的目次 private String dt;//上傳日期時光 private String ip;//上傳客戶真個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 getDt() { return dt; } public void setDt(String dt) { this.dt = dt; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String Dreturn desc; } public void setDesc(String desc) { this.desc = desc; } }
dao層:這裡簡寫了,只寫了完成類PhotoDaoImpl.java
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.domain.PhotoModel; import cn.hncu.utils.DomFactory; public class PhotoDaoImpl { public boolean sava(PhotoModel pm){ Document dom=DomFactory.getDom(); Element root=dom.getRootElement(); Element e=root.addElement("photo"); e.addAttribute("id", pm.getId()); e.addAttribute("dir", pm.getDir()); e.addAttribute("dt", pm.getDt()); e.addAttribute("ext", pm.getExt()); e.addAttribute("ip", pm.getIp()); e.addAttribute("realName", pm.getRealName()); e.addElement("desc").setText(pm.getDesc()); boolean b=DomFactory.save(); if(b){ return true; } return false; } public List<PhotoModel> getAllPhotos(){ List<PhotoModel> li=new ArrayList<PhotoModel>(); Document dom=DomFactory.getDom(); Element e=dom.getRootElement(); Iterator<Element> it=e.elementIterator(); while(it.hasNext()){ Element ie=it.next(); PhotoModel pm=new PhotoModel(); pm.setId(ie.attributeValue("id")); pm.setDir(ie.attributeValue("dir")); pm.setDt(ie.attributeValue("dt")); pm.setExt(ie.attributeValue("ext")); pm.setIp(ie.attributeValue("ip")); pm.setRealName(ie.attributeValue("realName")); pm.setDesc(ie.elementText("desc")); li.add(pm); } return li; } public PhotoModel getSingleById(String id){ List<PhotoModel> li=getAllPhotos(); PhotoModel pm=new PhotoModel(); for(PhotoModel p:li){ if(p.getId().equals(id)){ return p; } } return null; } public boolean del(String id) { Document dom=DomFactory.getDom(); Element e=(Element) dom.selectSingleNode("//photo[@id='"+id+"']"); return e.getParent().remove(e); } }
對象類:
1.
package cn.hncu.utils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; public class MyUtils { private MyUtils() { } public static String getUUID(){ return UUID.randomUUID().toString().replace("-", ""); } private static SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd HH:mm:ss"); public static String getCurrentDataime(){ return sdf.format(new Date()); } public static String getDir(String uuid){ String dir1=Integer.toHexString(uuid.hashCode()&0xf); String dir2=Integer.toHexString((uuid.hashCode()&0xf0)>>4); return dir1+"/"+dir2; } }
2.
package cn.hncu.utils; import java.io.FileOutputStream; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class DomFactory { private static Document dom; private static String fileName; static{ try { SAXReader r=new SAXReader(); //獲得src下的資本文件 fileName=DomFactory.class.getClassLoader().getResource("photos.xml").getPath(); System.out.println("users.xml的途徑:"+fileName);//"/D:/apache-tomcat-7.0.30/webapps/photosWeb/WEB-INF/classes/photos.xml" //留意:獲得tomcat中以後項目classpath下的資本方法 dom=r.read(fileName); } catch (DocumentException e) { e.printStackTrace(); } } public static Document getDom(){ return dom; } public static boolean save(){ XMLWriter w; try { w = new XMLWriter(new FileOutputStream(fileName)); w.write(dom); w.close(); return true; } catch (Exception e) { return false; } } }
以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。