Java Servlet簡(jiǎn)單實(shí)例分享(文件上傳下載demo)
項(xiàng)目結(jié)構(gòu)
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.簡(jiǎn)單實(shí)例
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.文件上傳實(shí)例
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
//設(shè)置編碼
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
try {
//設(shè)置系統(tǒng)環(huán)境
DiskFileItemFactory factory = new DiskFileItemFactory();
//文件存儲(chǔ)的路徑
String storePath = getServletContext().getRealPath("/WEB-INF/files");
//判斷傳輸方式 form enctype=multipart/form-data
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart)
{
pw.write("傳輸方式有錯(cuò)誤!");
return;
}
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(4*1024*1024);//設(shè)置單個(gè)文件大小不能超過(guò)4M
upload.setSizeMax(4*1024*1024);//設(shè)置總文件上傳大小不能超過(guò)6M
//監(jiān)聽(tīng)上傳進(jìn)度
upload.setProgressListener(new ProgressListener() {
//pBytesRead:當(dāng)前以讀取到的字節(jié)數(shù)
//pContentLength:文件的長(zhǎng)度
//pItems:第幾項(xiàng)
public void update(long pBytesRead, long pContentLength,
int pItems) {
System.out.println("已讀去文件字節(jié) :"+pBytesRead+" 文件總長(zhǎng)度:"+pContentLength+" 第"+pItems+"項(xiàng)");
}
});
//解析
List<FileItem> items = upload.parseRequest(request);
for(FileItem item: items)
{
if(item.isFormField())//普通字段,表單提交過(guò)來(lái)的
{
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;
//按日期來(lái)建文件夾
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();//刪除臨時(shí)文件
}
}
// }
}catch(org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException e){
//單個(gè)文件超出異常
pw.write("單個(gè)文件不能超過(guò)4M");
}catch(org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException e){
//總文件超出異常
pw.write("總文件不能超過(guò)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();//創(chuàng)建多級(jí)目錄,mkdir只創(chuàng)建一級(jí)目錄
}
return path;
}
private String makeStorePath2(String storePath, String fileName) {
int hashCode = fileName.hashCode();
int dir1 = hashCode & 0xf;// 0000~1111:整數(shù)0~15共16個(gè)
int dir2 = (hashCode & 0xf0) >> 4;// 0000~1111:整數(shù)0~15共16個(gè)
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.文件下載實(shí)例
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);
//告訴瀏覽器是以下載的方法獲取到資源
//告訴瀏覽器以此種編碼來(lái)解析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簡(jiǎn)單實(shí)例分享(文件上傳下載demo)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
java使用Hashtable過(guò)濾數(shù)組中重復(fù)值的方法
這篇文章主要介紹了java使用Hashtable過(guò)濾數(shù)組中重復(fù)值的方法,涉及java數(shù)組遍歷及過(guò)濾的相關(guān)技巧,需要的朋友可以參考下2016-08-08
Java使用fill()數(shù)組填充的實(shí)現(xiàn)
這篇文章主要介紹了Java使用fill()數(shù)組填充的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Java將Word文檔轉(zhuǎn)換為PDF文件的幾種常用方法總結(jié)
這篇文章主要介紹了Java將Word文檔轉(zhuǎn)換為PDF文件的四種常用方法,分別使用ApachePOI+iText、Aspose.Words?for?Java、Docx4j和JODConverter,這些庫(kù)各有優(yōu)點(diǎn),但在使用時(shí)需要注意庫(kù)與Java環(huán)境的兼容性、安裝所需依賴、轉(zhuǎn)換速度和資源消耗,需要的朋友可以參考下2024-10-10
Java將日期類型Date時(shí)間戳轉(zhuǎn)換為MongoDB的時(shí)間類型數(shù)據(jù)
今天小編就為大家分享一篇關(guān)于Java將日期類型Date時(shí)間戳轉(zhuǎn)換為MongoDB的時(shí)間類型數(shù)據(jù),小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-10-10
Java?Hibernate中一對(duì)多和多對(duì)多關(guān)系的映射方式
Hibernate是一種Java對(duì)象關(guān)系映射框架,支持一對(duì)多和多對(duì)多關(guān)系的映射。一對(duì)多關(guān)系可以使用集合屬性和單向/雙向關(guān)聯(lián)來(lái)映射,多對(duì)多關(guān)系可以使用集合屬性和中間表來(lái)映射。在映射過(guò)程中,需要注意級(jí)聯(lián)操作、延遲加載、中間表的處理等問(wèn)題2023-04-04
springboot項(xiàng)目以jar包運(yùn)行的操作方法
公司一個(gè)springboot項(xiàng)目本來(lái)是打war包的,突然要改為打jar包,不知所措了,糾結(jié)該如何操作呢,折騰半天終于搞定了,下面把解決方案分享給大家,對(duì)springboot打jar包方式感興趣的朋友一起看看吧2021-06-06

