精致小巧的java相册制作方法
程序员文章站
2024-03-13 08:29:27
本文实例为大家分享了java相册制作方法,供大家参考,具体内容如下
注:
1)html上的图片是静态指定的。当更新了新的图片时必须手工更新...
本文实例为大家分享了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; } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。