이 기사의 예는 귀하의 참조를 위해 Java 앨범을 만드는 방법을 공유합니다. 특정 내용은 다음과 같습니다
메모:
1) HTML의 이미지는 정적으로 지정됩니다. 새 이미지가 업데이트되면 수동으로 업데이트해야합니다. 따라서 서블릿을 사용하여 로컬 이미지의 모든 이미지를 읽고 사용자에게 동적으로 표시하십시오.
2) 중국어 이름이있는 사진이 있으면 Get 메소드가 중국어를 직접 전달할 수 없기 때문에 오류가 발생합니다.
메인 페이지 index.jsp
<%@ page language = "java"import = "java.util.*"pageEncoding = "utf-8"%> <! doctype html public "-// w3c // dtd html 4.01"> <html> <head> <title> little 앨범 </head> <! <! http : // localhost : 8080/photosweb/ -> <h2> 작은 앨범 </h2> <a href = "jsps/upload.jsp"> 업로드 </a> </a> <a href = "< %= request.getConteppath () %>/servlet/showallimg"> body </a> </html> </html> </html> </html>
페이지 표시 :
이미지 기능 업로드 :
<%@ page language = "java"import = "java.util.*"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtd html 4.01 Transitional // en"> <html> <head> <title> 작은 앨범 </head> <h2> 앨범> </h2> < action = "< %= request.getContextPath () %>/servlet/uploadservlet"method "method ="post "enctarpe ="multipart/form-data "> photo : <input type ="file "name ="file "/> <br/> 설명 : <입력 유형 ="text "name ="desc "/> <br/> input type ="value = "upload"/>/> 형태 " </body> </html>
패키지 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.servlet.servletexmence; javax.servlet.http.httpservlet; import javax.servlet.http.htttp.httpervletrequest; import javax.servlet.http.http.htttp.httpervletresponse; import org.apache.commons.fileuplead.fileitem; import org.apache.commons.fileupload 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.htodel; cn.hncu.utils.myutils; public class uploadservlet는 httpservlet {public void doget (httpservletrequest request, httpservletreponse responsk)를 servletexception, ioexception ( "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.println ( "<body>"); out.println ( "<body>"); out.println ( "<body>"); out.close (); } public void dopost (httpservletRequest 요청, 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 레이어를 호출하여 배경에 저장하십시오. // 2. 업로드 된 사진을 서버 하드 디스크에 저장하십시오. // 데이터베이스 : 사진 저장에 관한 정보를 저장하십시오. 파일 = 새 파일 ( "d :/a"); if (file.exists ()) {file.mkdirs (); } dfi.setRepository (파일); ServletFileUpload 업로드 = 새로운 ServletFileUpload (DFI); upload.setsizemax (1024*1024*8); upload.setheaderEncoding ( "UTF-8"); // ==> request.SetchAracterEncoding ( "UTF-8"); try {list <fileitem> list = upload.parserequest (요청); 광 도메도 PM = 새로운 광도 모드 (); 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); 문자열 filename = fi.getName (); // system.out.println ( "getName :"+filename); // test : c :/user/adl1/pictures/saved pictures/111.jpg? // (filename == null || filename.trim (). equals ( "파일 없음 ,,,,,,,,,,,,,,, 그것은 파일을 선택해야한다 ... <br/>"); String stratp2 = request.getContextPath ()+"/jsps/upload.jsp"; out.println ( "<a href =/" "+"); } pm.setdt (myutils.getcurrentDataime ()); realname.length ()) "/"realname extension ext = filename.substring ( "."); pm.setdir (myutils.getDir (id))}; path = "photos/"+pm.getDir (); // system.out.println ( "path :"+path); // test : photos/9/0 String FilePath = getServletContext (). getRealPath (path); // system.out.println ( "filepath :"+felepath); // 테스트 : d : /apache-tomcat-7.0.30/webapps/photosweb/photos/9/0 파일 dir = 새 파일 (filepath); if (! dir.exists ()) {dir.mkdirs (); } fileUtils.copyInputStreamTofile (in, new File (filepath+"/"+pm.getId ()+pm.getext ())); // // 하드 디스크가 성공적으로 저장되면 기본 페이지로 점프하십시오. rd = request.getRequestDispatcher (getServletContext (). getContextPath ()+"/index.jsp"); // "/photoWeb/photosWeb/index.jsp"// requestDispatcher rd = request.getRequestDispatcher ( "/index.jsp"); // "/pictleswweb/th the start/the the Start"g getRequestDispatcher ( "/index.jsp"); Java Code Block 및 Web.xml은 프로젝트 루트 디렉토리 // rd.forward (요청, 응답)를 나타냅니다. // 여기에서 전달을 사용할 수 없습니다. 리디렉션과 전달의 구체적인 차이 : http://blog.csdn.net/xanlv/article/details/52701085 // rection.sendRedirect (getServletContext (). getContextPath ()+"/index.jsp"); } else {// 데이터베이스 저장 실패-업로드 페이지를 시작합니다. 페이지 업로드 요청 dispatcher rd = request.getRequestDispatcher ( "/jsps/upload..jsp"); // "/photosweb/index.jsp"rd.forward (요청, 응답); }} catch (fileUploadexception e) {throw new runtimeexception ( "업로드 실패", e); } 마침내 {// 임시 파일을 지우십시오. f = 새 파일 ( "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.httpervax; import javax.servlet.http.httpepest.httpepest.; javax.servlet.http.httpertresponse; import cn.hncu.dao.photodaoimpl; import cn.hncu.domain.photomodel; public class showallimgservlet는 httpservlet {public void do (httpervletrequest), httpservletrecest, httpservletr respence, httpservletr respence를 확장합니다. 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>"); 문자열 strath = request.getContextPath ()+"/jsps/upload.jsp"; out.println ( "<a href =/" "+strpath+"/"> 업로드 페이지 </a>"); // string table = "<테이블 테두리 = '1px'width = '100%'cellPacing = '0'align = 'center'>"+//이 메소드가 수평으로 설정할 수 없습니다. style = 'text-align : center;'> "+"<tr> <th> 파일 이름 </th> <th> 날짜와 시간을 업로드 </th> <th> 사진 </th> <th> 사진 설명 </th> <th> 작동 </th> </tr> "; out.println (표); // DAO 레이어에서 모든 사진 정보를 읽고 프론트 엔드 페이지 목록 <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>"); 문자열 path = request.getContextPath ()+"/photos/"+pm.getDir ()+"/"+pm.getId ()+pm.getext (); // system.out.println (path); // "/photosweb/photos/7/e78e18352b4242410f85dbd834bd 718.jpg 큰 이미지 out.println ( "<td width = 100> <a href = '+path+"'> <img width = 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 ()+"'> 사진 삭제 </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 요청, httpservletResponse 응답) 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 ( "지원되는 포스트 방법이 아님"); out.println ( "</body>"); out.println ( "</html>"); out.flush (); out.close (); }} 페이지 표시 효과 :
함수 삭제 :
패키지 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.httrequestrequestrequestrequestrequestrequestrequestrectrectpectp.htttp.http.http.http.http.http.http javax.servlet.http.http.httpervletresponse; import cn.hncu.dao.photodaoimpl; import cn.hncu.domain.photomodel; public class delphotoservlet 확장 httpservlet {public void doeception (httperverquest, iooxception). {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 = 새로운 photodaoimpl (); Photomodel pm = dao.getSingleByid (ID); if (pm! = null) {if (! pm.getip (). equals (ip)) {out.println ( "이미지를 삭제할 권한이 없습니다 ..."); 문자열 strath = request.getContextPath ()+"/servlet/showallimg"; out.println ( "<br/> <a href =/" "+stratp+"/"> 계속 탐색으로 돌아 가기 </a>"); 반품 ; } // DELETE는 작업의 두 부분이 포함되어 있습니다. 데이터베이스의 정보를 지우고 서버 하드 디스크에서 이미지 파일을 삭제합니다. // 2 서버 하드 디스크에서 이미지 파일 삭제 if (boo) {string path = "photos/"+pm.getDir ()+"/"+pm.getId ()+pm.getext (); 문자열 filepath = getServletContext (). getRealPath (path); 파일 F = 새 파일 (FilePath); if (f.exists ()) {f.delete (); } string strath = request.getContextPath ()+"/servlet/showallimg"; // system.out.println (strath); /// photosWeb/servlet/showphotos out.println ( "성공적으로 삭제 ... <br/"<a href =/""+strath+"/"> 브로우로 돌아갑니다 </a> "; } else {out.println ( "데이터베이스 정보 삭제 실패"); }} else {out.println ( "파일이 존재하지 않습니다 ..."); 문자열 strath = request.getContextPath ()+"/servlet/showallimg"; out.println ( "<br/> <a href =/" "+stratp+"/"> 계속 탐색으로 돌아 가기 </a>"); } out.println ( "</body>"); out.println ( "</html>"); out.flush (); out.close (); } public void dopost (httpservletRequest 요청, httpservletResponse 응답) 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 ( "포스트 메소드가 지원되지 않음 ..."); out.println ( "</body>"); out.println ( "</html>"); out.flush (); out.close (); }}페이지 표시 :
다운로드 기능 :
1. HTML 페이지의 하이퍼 연결을 사용하여 다운로드 할 파일을 가리 킵니다 (안전하지 않고 쉽게 도난당한).
질문:
현지 자원을 결정하는 방법?
ServletContext는 웹 프로젝트를 나타냅니다. 웹 프로젝트에는 ServletContext 객체가 하나뿐입니다.
getRealPath ( "/"); // d :/prm/tom/web/
요구 사항 분석 :
실제 개발에서 사용자는 다운로드 할 파일이 동적으로 선택됩니다.
예를 들어, 프로젝트 이미지 디렉토리에는 많은 이미지 파일이 있습니다. 사용자는 페이지에 모든 사진을 표시하며 사용자는 다운로드 링크를 클릭하여 좋아하는 사진을 다운로드 할 수 있습니다.
자세한 디자인 :
정적 웹 페이지를 사용하여 모든 이미지를 표시하십시오. 각 이미지에 다운로드 된 하이퍼 링크를 제공하십시오.
하이퍼 연결 후 이미지 ID를 다운로드 할 수 있습니다.
서비스에서 이미지 이름을 동적으로 수신합니다. 다운로드를 완료하십시오.
패키지 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 java.net.urlencoder; javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import org.apache.commons.io.fileutils; cn.hncu.dao.photodaoimpl; import cn.hncu.domain.photomodel; public class downservlet 확장 httpservlet {public void doget (httpservletrequest 요청, httpservletresponse 응답) servletexception, ioxception {// IMIDE TRENT의 정보를 얻으십시오. 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를 나타냅니다 (요청, 응답); } else {// 실제 다운로드 : 서버 하드 디스크의 사진 파일을 읽고 클라이언트로 보내십시오 (응답 헤더 설정) // 실제 파일 문자열 realName = pm.getRealName (); realName = urlencoder.encode (RealName, "UTF-8"); // 중국어 이름 인 경우 파일 이름이 중국어로 장식되는 것을 방지하기 위해 트랜스 코드로 변환되어야합니다. // inputStream in = downServlet.class.getCASSTREAM (realName); // 응답을 다운로드하도록 디스플레이 유형을 설정합니다 .SetContentType ( "application/force-download"); // 응답 헤더 응답을 설정합니다 .SetHeader ( "Content-Disposition", "첨부 파일; filename =/"+realName+"/"); // string path = request.getContextPath ()+"/photos/"+pm.getDir ()+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+"+" PHORES/"+"+"+pm.getId () getServletContext (path); O = BYTE B [] = int LEN = 0; IoExcept. <head> <title> servlet </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 version = "3.0"xmlns = "http://java.sun.com/xml/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> uploadservlet </servlet-name> <Servlet-class> cn.hncu.servlet.uploadservlet </servlet-class> </servlet> <servlet-name> showallimgservlet </servlet-name> <servlet-class> cn.hncu.servlet.showallimgservlet </servlest-clest> <servlet> <servlet-name> <Servlet-class> cn.hncu.servlet.downservlet </servlet-class> </servlet> <servlet> <servlet-name> delphotoservlet </servlet-name> <servlet-class> cn.hncu.servlet.delphotoServlet </servlet> <servlet-mapping> <servlet-name> up-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> down-name> down-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-list> index.jsp>
데이터베이스 : photos.xml
<? xml version = "1.0"alcoding = "utf-8"?> <photos> <!-데이터베이스 디자인 <photo id = "uuid"realName = "real file name.jpg"dt = "2016-10-03 19:51:31"ext = ". </photo> -> </photos>
값 객체 : Photomodel.java
패키지 cn.hncu.domain; public class photomodel {// photo value 객체 개인 문자열 id; // uuid private string realname; // photo Real File 이름 개인 문자열 ext; // 직접 디렉토리 파일 스프레드 개인 문자열 dt 다음에 저장된 직접 디렉토리; // 업로드 날짜 및 시간 및 시간 개인 문자열 ip; // probload의 ip string desc; // plop string getid (upload private string ip; // public string); } 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 (문자열 dt) {this.dt = dt; } public String getDt () {return dt; } public void setdt (문자열 dt) {this.dt = dt; } public String getIP () {return IP; } public void setip (String IP) {this.ip = ip; } 공개 문자열 dreturn desc; } public void setdesc (String desc) {this.desc = desc; }}DAO LAYER : 여기에 약어가 있습니다. 구현 클래스 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; public class cn.hncu.utils. SAVA (Photomodel PM) {document dom = domfactory.getdom (); 요소 root = dom.getRootElement (); 요소 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 ()); 부울 b = domfactory.save (); if (b) {return true; } false를 반환합니다. } public list <photomodel> getAllPhotos () {list <photomodel> li = new Arraylist <Photomodel> (); document dom = domfactory.getdom (); 요소 e = dom.getRootElement (); iterator <ELTECT> IT = E.ELENGITERATOR (); while (it.hasnext ()) {요소 ie = it.next (); 광 도메도 PM = 새로운 광도 모드 (); pm.setId (예 : attributeValue ( "id")); pm.setdir (예 : attributeValue ( "dir")); pm.setdt (예 : AttributeValue ( "dt")); pm.setext (예 : AttributeValue ( "ext")); pm.setip (예 : attributeValue ( "ip")); pm.setRealName (예 : attributeValue ( "realName")); pm.setdesc (예 : ElementText ( "desc")); li.add (PM); } 리턴 리; } public photomodel getsingleByid (문자열 ID) {list <Photomodel> li = getAllPhotos (); 광 도메도 PM = 새로운 광도 모드 (); for (photomodel p : li) {if (p.getid (). equals (id)) {return p; }} return null; } public boolean del (문자열 id) {document dom = domfactory.getdom (); 요소 e = (요소) dom.selectsingLenode ( "// photo [@id = '+id+"'] "); return e.getParent (). 제거 (e); }}도구 :
1.
패키지 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 (). " } 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); 문자열 dir2 = integer.tohexstring ((uuid.hashcode () & 0xf0) >> 4); 반환 dir1+"/"+dir2; }}2.
패키지 cn.hncu.utils; import java.io.fileoutputStream; import org.dom4j.document; import org.dodexception; import org.dom4j.io.saxreader; import org.dom4j.io.io.io.io.io.io.io.io.io.io.io.xmlwriter; 개인 정적 문자열 파일 이름; static {try {saxReader r = new SaxReader (); // 리소스 파일을 가져옵니다. filename = domfactory.class.getClassLoader (). getResource ( "photos.xml"). getPath (); system.out.println ( "user.xml path :"+filename); // "/d :/d :/d :/d :/d :/d :/d :/d :/d :/d :/d :/d :/d : photosweb/web-inf/classes/photos.xml. } 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 (); 진실을 반환하십시오. } catch (예외 e) {return false; }}}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.