Contoh -contoh dalam artikel ini berbagi dengan Anda metode membuat album java untuk referensi Anda. Konten spesifiknya adalah sebagai berikut
Catatan:
1) Gambar pada HTML ditentukan secara statis. Ketika gambar baru diperbarui, mereka harus diperbarui secara manual. Jadi gunakan Servlet untuk membaca semua gambar dalam gambar lokal dan menampilkannya secara dinamis kepada pengguna.
2) Jika ada gambar dengan nama Cina, itu akan menyebabkan kesalahan karena metode GET tidak dapat secara langsung meneruskan bahasa Cina.
Indeks halaman utama.jsp
<%@ page language = "java" import = "java.util.*" pageEncoding = "utf-8"%> <! Doctype html public "-// w3c // dtd html 4.01 transisi // en"> <html> <ekomin> <titeme> album kecil </title> </head> http: // localhost: 8080/photosweb/ -> <h2> album kecil </h2> <a href = "jsps/unggah.jsp"> Unggah foto </a> <a href = "< %= getcontextpath () %>/servlet/showallimg"> browse foto </a/howl </howler>/servlet/servlet/showlet "> browsextpath () <)/servlet/servlet/showlImg"> browse </a/howsextpath ()/servlet/servlet/showallImg "> browse </a/howlsy </howls>
Tampilan Halaman:
Unggah Fungsi Gambar:
<%@ page language = "java" import = "java.util.*" pageenCoding = "utf-8"%> <! Doctype html public "-// w3c // dtd html 4.01 transisi // en"> <html> <head> <liteme> album kecil </title> </head> <html> <html> <head> <liteme> album kecil </title> </head> <html> <head> <lited> album kecil </title> </head> action="<%=request.getContextPath() %>/servlet/uploadServlet" method="post" enctype="multipart/form-data"> Photo: <input type="file" name="file"/><br/> Description:<input type="text" name="desc"/><br/> <input type="submit" value="upload"/> </form> </body> </html>
Paket cn.hncu.servlet; impor java.io.file; impor java.io.ioException; import java.io.inputstream; import java.io.printwriter; impor java.util.list; import javax.servlet.requestdispatcher; impor javax.servlet; javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletResponse; impor org.apache.commons.fileupload.fileitem; 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 ("Teks/html"); Printwriter out = response.getWriter (); out.println ("<! Doctype html public/"-// w3c // dtd html 4.01 transisi // en/">"); out.println ("<Html>"); out.println ("<head> <title> a servlet </iteme> </head>"); out.println ("<body>"); out.println ("<body>"); out.println ("<body>"); out.println ("<body>"); out.close (); } public void dopost (permintaan httpservletRequest, respons httpservletResponse) melempar servletException, ioException {request.setcharacterencoding ("UTF-8"); response.setContentType ("Teks/html; charset = utf-8"); Printwriter out = response.getWriter (); out.println ("<! Doctype html public/"-// w3c // dtd html 4.01 transisi // en/">"); out.println ("<Html>"); out.println ("<head> <title> unggah halaman foto </iteme> </head>"); out.println ("<body>"); //Extract information from the upload form: 1. Encapsulate it into a photo value object, call the dao layer to store it in the background// 2. Store the uploaded photos to the server hard disk// Database: store the information about the storage of the photos,,, the real file is stored to the hard disk DiskFileItemFactory dfi=new DiskFileItemFactory(); File file = file baru ("d:/a"); if (file.exists ()) {file.mkdirs (); } dfi.setrepository (file); SERVLETFILEUPLOAD UPLOAD = SERVLETFILEUPLOAD baru (DFI); unggah.setsizeMax (1024*1024*8); unggah. coba {list <fileitem> list = unggah.parseRequest (permintaan); Photomodel PM = Photomodel baru (); Inputstream in = null; untuk (FileItem fi: list) {if (fi.isformField ()) {// Ini tidak akan memiliki string file sementara 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); // tes: c:/user/adl1/gambar/gambar yang disimpan/111.jpg? // Kondisi default if (fileName == null || filename.trim (). Sama ("tidak ada file yang dipilih ,,,,, harus memilih file ... <br/>"); string strpath2 = request.getContextPath ()+"/jsps/unggah." Halaman </a> "); return;} pm.setdt (myutils.getCurrentDataime ()); string realname = filename.substring (filename.lastIndexof (" // ")); //"/112.jpg "System.out.println (realName.substring (1, 1, 12.jpg" () (); pm.setrealname (RealName.substring (1, RealName.Length ())); // Hapus "/" RealName // Extension String Ext = FileName.substring (FileName.LastIndexof ("."); pm.setip (request.getRemoteAddr ()); Direktori root proyek (disimpan dengan cara yang rusak) string path = "Foto/"+pm.getDir (); // System.out.println ("Path:"+Path); // Test: Foto/9/0 String FilePath = GetServletContext (). GetRealPath (path); // System.out.println ("FilePath:"+Path); // System.out.println ("" Tes: d: /apache-tomcat-7.0.30/webapps/photosweb/photos/9/0 file dir = file baru (filepath); if (! dir.exists ()) {dir.mkdirs (); } Fileutils.copyInputStreamToFile (dalam, file baru (filepath+"/"+pm.getId ()+pm.getext ())); // // Jika hard disk disimpan dengan sukses, lompat ke halaman utama - maju ///requestDispatcher rd = request.getRequestDispatcher (getserVletContext (). getContextPath ()+"/index.jsp"); // "/photosweb/photosweb/index.jsp" // requestDispatcher rd = fotosy.getrequestdatcher " blok dan web.xml mewakili direktori root proyek // rd.forward (permintaan, respons); // Penerusan tidak dapat digunakan di sini. Perbedaan spesifik antara pengalihan dan penerusan: http://blog.csdn.net/xanlv/article/details/52701085 // redirect response.sendredirect (getServletContext (). GetContextPath ()+"/index.jsp"); } else {// saving basis data gagal-tetap pada halaman unggah requestDispatcher rd = request.getRequestDispatcher ("/jsps/unggah..jsp"); // "/photosweb/index.jsp" rd.forward (request, response); }} catch (FileuploAdException e) {lempar runtimeException baru ("Unggah gagal", e); } akhirnya {// hapus file file sementara f = file baru ("d:/a"); File fs [] = f.listFiles (); untuk (file ff: fs) {ff.delete (); }} out.println ("</body>"); out.println ("</html>"); out.flush (); out.close (); }} Efek tampilan halaman:
Jelajahi Fungsi Gambar:
Paket cn.hncu.servlet; import java.io.ioexception; import java.io.printwriter; impor java.util.list; javax.servlet.http.httpservletresponse; impor cn.hncu.dao.photodaImpl; impor cn.hncu.domain.photomodel; httpservlet explevletscepscepscepsressres {public void doget (httpservlet explexcepscepscepscepscrespscrespscress IoException {response.setContentType ("Teks/html; charset = utf-8"); Printwriter out = response.getWriter (); out.println ("<! Doctype html public/"-// w3c // dtd html 4.01 transisi // en/">"); out.println ("<Html>"); out.println ("<head> <title> album browse </iteme> </head>"); out.println ("<body>"); String strpath = request.getContextPath ()+"/jsps/unggah.jsp"; out.println("<a href=/""+strPath+"/">Return to upload page</a>");//String table="<table border='1px' width='100%' cellpacing='0' align='center'>"+//This method cannot be set to center horizontally String table="<table border='1px' width='100%' cellpacing='0' style = 'text-align: center;'> "+" <tr> <t th> nama file </t> <t th> unggah tanggal dan waktu </t> <th> foto </t> <t th> Deskripsi foto </t> <t th> operasi </t> </tr> "; out.println (tabel); // Baca semua informasi foto dari lapisan DAO dan kirim ke daftar halaman front-end <Thotomodel> Daftar = photodaoImpl baru (). GetAllphotos (); untuk (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 ()+"/foto/"+pm.getDir ()+"/"+pm.getId ()+pm.getext (); // System.out.println (path); // "/Foto/Foto/D/7/E783352B42410F85DBD. gambar yang lebih besar out.println ("<td width = 100> <a href = '"+path+"'> <width img = 100 tinggi = 100 src = '"+path+"' //"); 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 ()+"> Hapus gambar </a>"); // out.println ("a a href = '<%= request.getContextPath ()%>/servlet/down? id = "+pm.getId ()+"> Unduh gambar </a> </td> "); out.println ("<br/> <a href = '"+getServletContext (). getContextPath ()+"/servlet/down? id ="+pm.getId ()+"'> Unduh gambar </a> </td>"); out.println ("</tr>"); } out.println ("</boable>"); out.println ("</body>"); out.println ("</html>"); out.flush (); out.close (); } public void dopost (permintaan httpservletRequest, respons httpservletResponse) melempar servletException, ioException {response.setContentType ("Teks/html; charset = UTF-8"); Printwriter out = response.getWriter (); out.println ("<! Doctype html public/"-// w3c // dtd html 4.01 transisi // en/">"); out.println ("<Html>"); out.println ("<head> <title> a servlet </iteme> </head>"); out.println ("<body>"); out.print ("tidak didukung metode pos.."); out.println ("</body>"); out.println ("</html>"); out.flush (); out.close (); }} Efek tampilan halaman:
Hapus fungsi:
Paket cn.hncu.servlet; impor java.io.file; impor java.io.ioexception; impor java.io.printwriter; impor javax.servlet.servletException; import javax.servlet.htp.htpservlet; impor javax.servlet.htp.htp.htpservlet; impor javax.servlet.htp.htp.htpservlet; impor javax.servlet.htp.htp.htpservlet; impor javax.servlet.htp.htp.htpservlet; impor javax.servlet.htp.htp.htpservlet javax.servlet.http.httpservletResponse; impor cn.hncu.dao.photodaImpl; impor cn.hncu.domain.photomodel; httpservlet compresservlet {public void doGet (httpservletexervlet IoException {response.setContentType ("Teks/html; charset = utf-8"); Printwriter out = response.getWriter (); out.println ("<! Doctype html public/"-// w3c // dtd html 4.01 transisi // en/">"); out.println ("<Html>"); out.println ("<Head> <title> Hapus halaman foto </iteme> </head>"); out.println ("<body>"); String id = request.getParameter ("id"); String ip = request.getRemoteAddr (); PhotodaoImpl dao = PhotodaoImpl baru (); Photomodel PM = dao.getsinglebyId (id); if (pm! = null) {if (! pm.getip (). Equals (ip)) {out.println ("Anda tidak memiliki izin untuk menghapus gambar ..."); String strpath = request.getContextPath ()+"/servlet/showallimg"; out.println ("<br/> <a href =/" "+strpath+"/"> kembali untuk melanjutkan menjelajah </a>"); kembali ; } // Hapus berisi dua bagian pekerjaan: Membersihkan informasi dalam database dan menghapus file gambar di server hard disk // 1 membersihkan informasi dalam basis data boolean boo = dao.del (id); // 2 Menghapus file gambar di server hard disk if (boo) {string path = "foto/"+pm.getDir ()+"/"+pm.getId ()+pm.getext (); String filePath = getSerVletContext (). GetRealPath (path); File f = file baru (filepath); if (f.exists ()) {f.delete (); } String strpath = request.getContextPath ()+"/servlet/showallimg"; // system.out.println (strpath); /// photosweb/servlet/showphotos out.println ("hapus berhasil ... <br/> <a href =/" "+strpath+"> return ke ... } else {out.println ("Hapus informasi database gagal"); }} else {out.println ("File tidak ada ..."); String strpath = request.getContextPath ()+"/servlet/showallimg"; out.println ("<br/> <a href =/" "+strpath+"/"> kembali untuk melanjutkan menjelajah </a>"); } out.println ("</body>"); out.println ("</html>"); out.flush (); out.close (); } public void dopost (permintaan httpservletRequest, respons httpservletResponse) melempar servletException, ioException {response.setContentType ("Teks/html"); Printwriter out = response.getWriter (); out.println ("<! Doctype html public/"-// w3c // dtd html 4.01 transisi // en/">"); out.println ("<Html>"); out.println ("<Head> <title> Hapus halaman foto </iteme> </head>"); out.println ("<body>"); out.print ("Tidak ada metode pos yang didukung ..."); out.println ("</body>"); out.println ("</html>"); out.flush (); out.close (); }}Tampilan Halaman:
Fungsi Unduh:
1. Gunakan hyperconnection pada halaman HTML untuk menunjuk ke file yang akan diunduh (tidak aman dan mudah dicuri).
pertanyaan:
Bagaimana cara menentukan sumber daya lokal?
ServletContext mewakili proyek web. Proyek web hanya memiliki satu objek ServletContext.
getrealpath ("/"); // D:/prm/tom/web/
Analisis Persyaratan:
Dalam pengembangan aktual, file mana yang akan diunduh secara dinamis dipilih oleh pengguna.
Misalnya, di direktori gambar proyek kami, ada banyak file gambar. Pengguna menampilkan semua gambar di halaman, dan pengguna dapat mengklik tautan unduhan untuk mengunduh gambar favorit.
Desain terperinci:
Gunakan halaman web statis untuk menampilkan semua gambar. Berikan setiap gambar hyperlink yang diunduh.
Lewati ID gambar untuk diunduh setelah hyperconnection.
Secara dinamis menerima nama gambar di Layanan. Lengkapi unduhannya.
Paket cn.hncu.servlet; import java.io.file; impor java.io.fileInputStream; impor java.io.ioException; import java.io.inputStream; impor java.outputstream; impor java.io.printwriter; impor java.net.uretatch; javax.servlet.servletException; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletRequest; impor javax.servlet.http.httpservletResponse; impor org.apache.common.common.common.commonse.commonse.commonse.commonse.commonse.commonse.commonse.commonse.commonse.commonse.commonse.commonse.commonse.commonse.commonse.commonse.commons cn.hncu.dao.photodaoImpl; impor cn.hncu.domain.photomodel; kelas publik downservlet memperluas httpservlet {public void doGet (httpservletrequest, httpservletResponse response) Layanan Layanan, IOOException {httpservlete) id = request.getParameter ("id"); Photomodel PM = PhotodaoImpl baru (). 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 transisi // en/">"); out.println ("<Html>"); out.println ("<head> <title> a servlet </iteme> </head>"); out.println ("<body>"); response.getWriter (). println ("alert ('Teks ini tidak ada lagi ...')"); out.println ("</body>"); out.println ("</html>"); out.flush (); out.close (); // getServletContext (). getContextPath () requestDispatcher rd = request.getRequestDispatcher ("/servlet/down"); // "/photosweb/index.jsp" // Mulai URL dalam blok kode java dan web.xml "/" mewakili proyek root directory. } else {// unduh nyata: Baca file foto hard disk server dan kirim ke klien (atur header respons) // Dapatkan string file nyata realname = pm.getRealName (); RealName = urlencoder.encode (RealName, "UTF-8"); // Jika itu adalah nama Cina, itu harus ditranskode untuk mencegah nama file agar tidak rusak dalam bahasa Cina // inputStream in = downservlet.class.getClassLoader (). GetResourCeAstream (realName); // Atur tipe tampilan untuk mengunduh response.setContentType ("Application/Force-Download"); // Atur respons header respons.setHeader ("Disposisi Konten", "Lampiran; FileName =/" "+RealName+"/"); // String Path = Request.GetContextPath ()+"/Foto/"+pm.getDir ()+"/"+pm.getId ()+pm.getext (); string (); path = "" PM.GetDir ()+"/"+pm.getId ()+pm.getext (); o = GetOutputStream (); IOException {response.setContentType ("Text/html"); <head> <title> a servlet </iteme> </head> "); out.println (" <body> "); out.println (" </body> "); out.println (" </html> "); out.flush (); out.close (); }} Efek tampilan halaman:
File Konfigurasi Web.xml
<? Xml Version = "1.0" encoding = "UTF-8"?> <Web-app Versi = "3.0" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: xsi = "http:/www.w3.org/org/2001 =" http:/www.w3.org/org/p21 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-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>
Database: Foto.xml
<? Xml Version = "1.0" encoding = "UTF-8"?> <Foto> <!-Desain Basis Data <foto id = "UUID" RealName = "Name File Nyata.jpg" dt = "2016-10-03 <19.51:31" Ext = ". JPG" dir = "a/5" ip = "192.16.16" Ext = "JPG" Dir = "a/5" ip = "192.16.16.16 </hoto> -> </shoto>
Objek Nilai: Photomodel.java
Paket cn.hncu.domain; kelas publik photomodel {// Foto nilai objek pribadi string id; // uuid string pribadi realname; // foto nama file nyata string private ext; // ekstensi pribadi string dir; // direktori langsung disimpan setelah file spread private string dt; // unggah tanggal dan waktu string private string ip; // unggah alamat klien klien klien klien klien dt; } 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 getDT () {return dt; } public void setDt (String dt) {this.dt = dt; } string publik getIp () {return ip; } public void setip (string ip) {this.ip = ip; } public String Dreturn Desc; } public void setDesc (String desc) {this.desc = desc; }}DAO Layer: Ini singkatan, hanya kelas implementasi photodaoImpl.java ditulis
Paket cn.hncu.dao; impor java.util.arraylist; impor java.util.iterator; impor java.util.list; org.dom4j.document; impor org.dom4j.element; publicy publicory. Sava (photomodel pm) {document dom = domfactory.getDom (); Elemen root = dom.getrooteLement (); Elemen e = root.addelement ("foto"); 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; } Daftar Publik <Totomodel> getAllPhotos () {Daftar <Totomodel> Li = ArrayList baru <TotomoDel> (); Dokumen dom = domfactory.getDom (); Elemen e = dom.getrooteLement (); Iterator <semem Sedikit> itu = E.elementIterator (); while (it.hasnext ()) {elemen ie = it.next (); Photomodel PM = Photomodel baru (); 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 <othotomodel> li = getAllPhotos (); Photomodel PM = Photomodel baru (); untuk (photomodel p: li) {if (p.getId (). equals (id)) {return p; }} return null; } public boolean del (string id) {document dom = domfactory.getDom (); Elemen e = (elemen) dom.selectsinglenode ("// foto [@id = '"+id+"']"); return e.getparent (). Remove (e); }}Peralatan:
1.
Paket cn.hncu.utils; import java.text.simpledateFormat; impor java.util.date; import java.util.uuid; kelas publik myutils {private myutils () {} public string statis getuuid () {return uuid.randomuid (). " } private static SimpleDateFormat sdf = new SimpleDateFormat ("yy-mm-dd hh: mm: ss"); string statis publik getCurrentDataMe () {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); mengembalikan dir1+"/"+dir2; }}2.
Paket cn.hncu.utils; impor java.io.fileoutputStream; impor org.dom4j.document; impor org.dom4j.documentException; impor org.dom4j.io.saxreader; impor org.dom4j.xmlwriter; domfactory kelas publik {private domacory {private dOKSORIC; nama file string statis pribadi; static {coba {saxreader r = baru saxreader (); // Dapatkan file sumber daya fileName = domfactory.class.getClassLoader (). GetResource ("photos.xml"). GetPath (); System.out.println ("Users.xml Path:"+FileName); // "/d: /apache-tomcat-7.0.30/webapps/photosweb/web-inf/classes/photos.xml" // Catatan: Dapatkan metode sumber daya di bawah proyek kelas ini di Tomcat dom = r.) } catch (DocumentException e) {E.PrintStackTrace (); }} dokumen statis public getDom () {return dom; } public static boolean save () {xmlwriter w; coba {w = xmlwriter baru (FileOutputStream baru (fileName)); W.Write (DOM); w.close (); Kembali Benar; } catch (Exception e) {return false; }}}Di atas adalah semua konten artikel ini. Saya berharap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.