Java Servlet简单实例分享(文件上传下载demo)
程序员文章站
2024-02-16 13:46:22
项目结构
src
com
servletdemo
downloadservlet.java
showservl...
项目结构
src com servletdemo downloadservlet.java showservlet.java uploadservlet.java webcontent jsp servlet download.html fileupload.jsp input.jsp web-inf lib commons-fileupload-1.3.1.jar commons-io-2.4.jar
1.简单实例
showservlet.java
package com.servletdemo; import java.io.ioexception; import java.io.printwriter; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; /** * servlet implementation class showservlet */ @webservlet("/showservlet") public class showservlet extends httpservlet { private static final long serialversionuid = 1l; printwriter pw=null; /** * @see httpservlet#httpservlet() */ public showservlet() { super(); // todo auto-generated constructor stub } /** * @see httpservlet#doget(httpservletrequest request, httpservletresponse response) */ protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub this.dopost(request, response); } /** * @see httpservlet#dopost(httpservletrequest request, httpservletresponse response) */ protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub request.setcharacterencoding("gb2312"); response.setcontenttype("text/html;charset=gb2312"); pw=response.getwriter(); string name=request.getparameter("username"); string password=request.getparameter("password"); pw.println("user name:" + name); pw.println("<br>"); pw.println("user password:" + password); } }
input.jsp
<%@ page language="java" contenttype="text/html; charset=iso-8859-1" pageencoding="iso-8859-1"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title>servlet demo</title> </head> <body> <form action="<%=request.getcontextpath()%>/showservlet"> <table> <tr> <td>name</td> <td><input type="text" name="username"></td> </tr> <tr> <td>password</td> <td><input type="text" name="password"></td> </tr> <tr> <td><input type="submit" value="login"></td> <td><input type="reset" value="cancel"></td> </tr> </table> </form> </body> </html>
2.文件上传实例
uploadservlet.java
package com.servletdemo; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.io.printwriter; import java.text.dateformat; import java.util.date; import java.util.list; import java.util.uuid; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; 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.progresslistener; import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servlet.servletfileupload; /** * servlet implementation class uploadservlet */ @webservlet("/servlet/uploadservlet") public class uploadservlet extends httpservlet { private static final long serialversionuid = 1l; /** * @see httpservlet#httpservlet() */ public uploadservlet() { super(); // todo auto-generated constructor stub } /** * @see httpservlet#doget(httpservletrequest request, httpservletresponse response) */ protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub //设置编码 request.setcharacterencoding("utf-8"); response.setcontenttype("text/html;charset=utf-8"); printwriter pw = response.getwriter(); try { //设置系统环境 diskfileitemfactory factory = new diskfileitemfactory(); //文件存储的路径 string storepath = getservletcontext().getrealpath("/web-inf/files"); //判断传输方式 form enctype=multipart/form-data boolean ismultipart = servletfileupload.ismultipartcontent(request); if(!ismultipart) { pw.write("传输方式有错误!"); return; } servletfileupload upload = new servletfileupload(factory); upload.setfilesizemax(4*1024*1024);//设置单个文件大小不能超过4m upload.setsizemax(4*1024*1024);//设置总文件上传大小不能超过6m //监听上传进度 upload.setprogresslistener(new progresslistener() { //pbytesread:当前以读取到的字节数 //pcontentlength:文件的长度 //pitems:第几项 public void update(long pbytesread, long pcontentlength, int pitems) { system.out.println("已读去文件字节 :"+pbytesread+" 文件总长度:"+pcontentlength+" 第"+pitems+"项"); } }); //解析 list<fileitem> items = upload.parserequest(request); for(fileitem item: items) { if(item.isformfield())//普通字段,表单提交过来的 { string name = item.getfieldname(); string value = item.getstring("utf-8"); system.out.println(name+"=="+value); }else { // string mimetype = item.getcontenttype(); 获取上传文件类型 // if(mimetype.startswith("image")){ inputstream in =item.getinputstream(); string filename = item.getname(); if(filename==null || "".equals(filename.trim())) { continue; } filename = filename.substring(filename.lastindexof("\\")+1); filename = uuid.randomuuid()+"_"+filename; //按日期来建文件夹 string newstorepath = makestorepath(storepath); string storefile = newstorepath+"\\"+filename; outputstream out = new fileoutputstream(storefile); byte[] b = new byte[1024]; int len = -1; while((len = in.read(b))!=-1) { out.write(b,0,len); } in.close(); out.close(); item.delete();//删除临时文件 } } // } }catch(org.apache.commons.fileupload.fileuploadbase.filesizelimitexceededexception e){ //单个文件超出异常 pw.write("单个文件不能超过4m"); }catch(org.apache.commons.fileupload.fileuploadbase.sizelimitexceededexception e){ //总文件超出异常 pw.write("总文件不能超过6m"); }catch (fileuploadexception e) { e.printstacktrace(); } } /** * @see httpservlet#dopost(httpservletrequest request, httpservletresponse response) */ protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub doget(request, response); } private string makestorepath(string storepath) { date date = new date(); dateformat df = dateformat.getdateinstance(dateformat.medium); string s = df.format(date); string path = storepath+"\\"+s; file file = new file(path); if(!file.exists()) { file.mkdirs();//创建多级目录,mkdir只创建一级目录 } return path; } private string makestorepath2(string storepath, string filename) { int hashcode = filename.hashcode(); int dir1 = hashcode & 0xf;// 0000~1111:整数0~15共16个 int dir2 = (hashcode & 0xf0) >> 4;// 0000~1111:整数0~15共16个 string path = storepath + "\\" + dir1 + "\\" + dir2; // web-inf/files/1/12 file file = new file(path); if (!file.exists()) file.mkdirs(); return path; } }
fileupload.jsp
<%@ page language="java" contenttype="text/html; charset=iso-8859-1" pageencoding="iso-8859-1"%> <% string path = request.getcontextpath(); string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/"; %> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title>upload file demo</title> </head> <body> <form action="${pagecontext.request.contextpath}/servlet/uploadservlet" method="post" enctype="multipart/form-data"> user name<input type="text" name="username"/> <br/> <input type="file" name="f1"/><br/> <input type="file" name="f2"/><br/> <input type="submit" value="save"/> </form> </body> </html>
3.文件下载实例
downloadservlet.java
package com.servletdemo; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.io.outputstream; import java.io.printwriter; import java.net.urlencoder; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.servletresponse; /** * servlet implementation class downloadservlet */ @webservlet("/downloadservlet") public class downloadservlet extends httpservlet { private static final long serialversionuid = 1l; /** * @see httpservlet#httpservlet() */ public downloadservlet() { super(); // todo auto-generated constructor stub } /** * @see httpservlet#doget(httpservletrequest request, httpservletresponse response) */ protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub download1(response); } /** * @see httpservlet#dopost(httpservletrequest request, httpservletresponse response) */ protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub doget(request, response); } public void download1(httpservletresponse response) throws ioexception{ //获取所要下载文件的路径 string path = this.getservletcontext().getrealpath("/files/web配置.xml"); string realpath = path.substring(path.lastindexof("\\")+1); //告诉浏览器是以下载的方法获取到资源 //告诉浏览器以此种编码来解析urlencoder.encode(realpath, "utf-8")) response.setheader("content-disposition","attachment; filename="+urlencoder.encode(realpath, "utf-8")); //获取到所下载的资源 fileinputstream fis = new fileinputstream(path); int len = 0; byte [] buf = new byte[1024]; while((len=fis.read(buf))!=-1){ response.getoutputstream().write(buf,0,len); } } }
download.html
<!doctype html> <html> <head> <meta charset="iso-8859-1"> <title>download demo</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> </head> <body> <a href = "/javabeandemo/downloadservlet">download</a> </body> </html>
以上这篇java servlet简单实例分享(文件上传下载demo)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
下一篇: ASP.NET窗体身份验证详解