この記事の例は、あなたのリファレンスのためにJavaアルバムを作成する方法をあなたと共有しています。特定のコンテンツは次のとおりです
注記:
1)HTMLの画像は静的に指定されています。新しい画像が更新されたら、手動で更新する必要があります。したがって、サーブレットを使用して、ローカル画像のすべての画像を読み取り、ユーザーに動的に表示します。
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>リトルアルバム</head> </<body> <> < http:// localhost:8080/photoweb/ - > <h2>リトルアルバム</h2> <a href = "jsps/upload.jsp"> upload photo </a> <a href = "<%= request.getContextPath()%>/servlet/showallimg"
ページディスプレイ:
画像機能をアップロードします:
<%@ page Language = "Java" Import = "Java.util。*" PageEncoding = "UTF-8"%> <!doctype HTML public " - // w3c // dtd html 4.01 transitional // en" action = "<%= request.getContextPath()%>/servlet/uploadservlet" Method = "" post "enctype =" multipart/form-data ">写真:<入力タイプ="ファイル "name =" file "/> <br/>説明:<入力タイプ="テキストname = "desc"/> <ball/> </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.Servlet.ServletException;import javax.servlet.http.httpservlet; Import javax.servlet.http.httpservletrequest; Import javax.servlet.servlet.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.servlet.servletfileupload; cn.hncu.dao.photodaoimpl; Import cn.hncu.domain.photomodel; Import cn.hncu.utils.myutils; public class uploadservletはhttpservlet {httpservletrequest request、httpservletressponsexcepsection esprectince(httpservletrequest request)を拡張します。 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サーブレット</title> </head>"); out.println( "<body>"); out.println( "<body>"); out.println( "<body>"); out.println( "<body>"); out.close(); } public void dopost(httpservletrequest request、httpservletResponse応答)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>"); //アップロードフォームから情報を抽出します。1。写真値オブジェクトにカプセル化し、DAOレイヤーをバックグラウンドに保存してください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()){//一時ファイル文字列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); // test:/users/adl1/pictures/saved pictures/111.jpg? //デフォルト条件IF(filename == null || filename.trim()。equals( "file selected ,,,, selece file ... <br/>"); string strpath2 = request.getContextPath()+"/jsps/upload.jsp"; out.println( "<a href =/" "+strpath2+"/"/"> } pm.setdt(myutils.getCurrentDataime()); realname.length()); PM.setdir(myutils.getdir(id)); path = "photos/"+pm.getdir(); // System.out.println( "path:"+path); // test:photos/9/0 string filepath = getRealPath()。getRealPath()。テスト: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()); rd = request.getRequestDispatcher(getServletContext()。getContextPath()+"/index.jsp"); // "/"/"// requestdispatcher rd = request.getrequestdispatcher("/index.jsp "); Javaコードブロックとweb.xmlは、プロジェクトルートディレクトリ// rd.forward(request、response)を表します。 //ここでは転送を使用できません。リダイレクトと転送の特定の違い:http://blog.csdn.net/xanlv/article/details/52701085 // redirect response.sendredirect(getServletContext()。getContextPath()。 } else {//データベースの保存失敗 - アップロードページのrequestdispatcher rd = request.getRequestDispatcher( "/jsps..jsp"); // "/"/photosweb/index.jsp "rd.forward(request、response); }} catch(fileuploadexception e){新しいruntimeexception( "upload failed"、e); }最後に{//一時ファイルをクリアするFile f = newファイル( "d:/a");ファイルfs [] = f.listfiles(); for(file ff:fs){ff.delete(); }} out.println( "</body>"); out.println( "</html>"); out.flush(); out.close(); }}ページ表示効果:
画像関数を閲覧する:
パッケージ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.httptservletreqest; javax.servlet.http.httpservletresponse; Import cn.hncu.dao.photodaoimpl; Import cn.hncu.domain.photomodel; public class showallimgservletはhttpservleteを拡張します{public void do(httpserbletreletreletested request、httpservletreletreletreletreletreletreletreletreletreletrelete) {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>アルバムBrowse </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%' cellpacing = '' align = 'center'>"+// style = 'text-align:center;'> "+" <tr> <th> file name </th> <th>アップロード日付と時刻</th> <th>写真説明</th> <th>操作</th> </tr> "; out.println(表); // DAOレイヤーからすべての写真情報を読み、それをフロントエンドページリスト<Photomodel>リストに送信します= 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(// "/photosweb/photos/d/7/e78e18352b42410f85dbd8d834bbd718" ///より大きな画像out.println( "<td width = 100> <a href = '"+path+"'> <img width = 100 height = 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()+"/servet/delphoto?id ="+pm.getid()+"'> delete </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応答)throws servletexception、ioexception {respons.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サーブレット</title> </head>"); out.println( "<body>"); out.print( "サポートされていない投稿方法。。。"); out.println( "</body>"); out.println( "</html>"); out.flush(); out.close(); }}ページ表示効果:
関数の削除:
パッケージcn.hncu.servlet; import java.io.file; import java.io.io.ioexception; Import java.io.printwriter; Import javax.servlet.servletexception; Import javax.servlet.http.httpservlet; Import Javax.servlet.http.httpservletreqest; 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>");文字列id = request.getParameter( "id");文字列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+"/"> return to notun browing </a>");戻る ; } //削除には、2つの作業が含まれています。データベース内の情報をクリアし、サーバーハードディスクの画像ファイルを削除する// 1データベースの情報のクリアboo = dao.del(id); // 2サーバーで画像ファイルを削除するハードディスクif(boo){string path = "photos/"+pm.getdir()+"/"+pm.getid()+pm.getext(); string filepath = getServletContext()。getRealPath(PATH);ファイルf = new file(filepath); if(f.exists()){f.delete(); } string strpath = request.getContextPath()+"/servlet/showAllimg"; // System.out.println(strpath); /// whotosweb/showphotos out.println( "delete sustere ... <br/> <a href =/" "+strpath+"/" } else {out.println( "delete delete database Information failed"); }} else {out.println( "ファイルは存在しません..."); string strpath = request.getContextPath()+"/servlet/showallimg"; out.println( "<br/> <a href =/" "+strpath+"/"> return to notun browing </a>"); } out.println( "</body>"); out.println( "</html>"); out.flush(); out.close(); } public void dopost(httpservletrequest request、httpservletResponse応答)throws servletexception、ioexception {respons.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オブジェクトが1つしかありません。
getRealPath( "/"); // d:/prm/tom/web/
要件分析:
実際の開発では、ダウンロードするファイルはユーザーによって動的に選択されます。
たとえば、Project Images Directoryには、多くの画像ファイルがあります。ユーザーはページにすべての写真を表示し、ユーザーはダウンロードリンクをクリックしてお気に入りの写真をダウンロードできます。
詳細なデザイン:
静的Webページを使用して、すべての画像を表示します。各画像にダウンロードされたハイパーリンクを与えます。
画像IDを渡して、HyperConnection後にダウンロードします。
サービス内の画像名を動的に受け取ります。ダウンロードを完了します。
パッケージcn.hncu.servlet;インポートjava.io.file; import java.io.fileinputStream; Import java.io.ioexception; Import java.io.inputStream; Import java.OutputStream; Import java.io.Printwriter; Import Java.net.net.urlencoder.Requtder.Requtder.Requtder.Requtderter. javax.servlet.servletexception; Import javax.servlet.http.httpservlet; Import javax.servlet.http.httpservletrequest; Import javax.servlet.http.httpservletresponse; Import org.apache.commons.filetils; cn.hncu.dao.photodaoimpl; Import cn.hncu.domain.photomodel; public class downServletはhttpservletを拡張します{public void request(httpservletrequest request、httpservletresponse応答)servletexceptip、ioexception、ioexception、Ioexception {// id = request.getParameter( "id"); Photomodel PM = new Photodaoimpl()。getSinglebyid(id); if(pm == null){respons.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サーブレット</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. } else {// realダウンロード:サーバーハードディスクの写真ファイルを読み、クライアントに送信します(応答ヘッダーを設定)// realファイル文字列realname = pm.getRealName(); realname = urlencoder.encode(realname、 "utf-8"); //中国名の場合、ファイル名が中国語で飾られるのを防ぐためにトランスコードする必要があります// inputstream in = downServlet.class.getClassLoader()。 // [response.setContentType( "Application/Force-DownLoad")をダウンロードするように表示タイプを設定します。 //応答ヘッダーResponse.setheader( "content-disposition"、 "attachment; filename =/" "+realname+"/"); // string path = request.getContextPath()+"/photos/"+pm.getdir()+"/"+pm.getid()+pm.getext(); path = "+pm.getdir()+"+pm.getext(); o = responsedstream()= int len = 0; ioException {settcontenttype( "text/html"); <head> <title> aサーブレット</title> </head> "); out.println(" <body> "); out.println(" </body> "); out.println(" </html> "); out.flush(); out.close(); }}ページ表示効果:
構成ファイルweb.xml
<?xml version = "1.0" encoding = "utf-8"?> <web-appバージョン= "3.0" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:xsi = "http://www.w3.org/2001/xmlschema-instcance" 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> <サーブレットクラス> cn.hncu.servlet.uploadservlet </servlet-class> </servlet> <servlet> <servlet-name> showallimgservlet </servlet-name> <servlet-class> <サーブレットクラス> cn.hhncu.servlet.downServlet </servlet-class> </servlet> <servlet> <servet-name> delphotoservlet </servlet-name> <servlet-class> cn.hhncu.servlet.delphotoservlete </servlet-class> <url-pattern>/servlet/uploadservlet </url-pattern> </servlet-mapping> <servlet-name> showallimgservlet </servlet-name> <url-pattern>/servlet/showalimg </url-pattern> </servlet-mapplet> <servlet-mapplet> <url-pattern>/servlet/down </url-pattern> </servlet-mapping> <servlet-name> delphotoservlet </servet-name> <url-pattern>/servlet/delphoto </url-pattern> </servet-mapping> <welcome-file> <welcome-file> <welcome-file>
データベース:photos.xml
<?xml version = "1.0" encoding = "utf-8"?> <photos> <! - データベースデザイン<写真ID = "uuid" realname = "real file name.jpg" dt = "2016-10-03 19:51:31" ext = "。jpg" dir = "a/5"> desc> </photo> - > </photos>
値オブジェクト:Photomodel.java
パッケージcn.hncu.domain; public class photomodel {// photo valueオブジェクトプライベート文字列ID; // uuid private string realname; // photo Real File Name Private String ext; // extension Private String dir; // Direct Directory Spread Spread Private String 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; } 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のみが書かれています
パッケージ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.cu.utils.domecliean cncu.utils.domeftory cncu.utils.domeftory cncu.utils.domeftory cncu.utils.domeftory cncu.utils.domefutory sava(photomodel pm){document dom = domfactory.getdom();要素root = dom.getRootelement();要素E = root.Addelement( "写真"); 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; } falseを返します。 } public list <Photomodel> getAllphotos(){list <Photomodel> li = new ArrayList <Photomodel>();ドキュメントdom = domfactory.getdom();要素e = dom.getRootelement(); iterator <lement> it = e.elementiterator(); while(it.hasnext()){要素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; }} nullを返します。 } public boolean del(string id){document dom = domfactory.getdom();要素e =(要素)dom.selectsinglenode( "// photo [@id = '"+id+"']"); return e.getParent()。remove(e); }}ツール:
1。
パッケージcn.hncu.utils; Import java.text.simpledateformat; import java.util.date; import java.util.uuid; public class myutils {} public static string getuuid(){return uuid.randomuid()。 } 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); dir1+"/"+dir2を返します。 }}2。
パッケージ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; Private Static Doconmactory;プライベート静的文字列ファイル名; static {try {saxreader r = new saxreader(); //リソースファイル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" //注:Tomcat dom = R.read)の現在のプロジェクトクラスパスの下でリソースメソッドを取得します。 } 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(); trueを返します。 } catch(例外e){falseを返します。 }}}上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。