文件下載代碼(2008-02-26 21:33:36)標簽:情感
String fileName = request.getParameter("fileName");
fileName = fileName.substring(fileName.indexOf("=")+1);
String filePath = servlet.getServletContext().getRealPath("")
+ "\\upload\\" ;
String file = filePath + fileName;
System.out.println(file);
FileInputStream fis = null;
OutputStream os = null;
byte[] bos = new byte[1024];
int length = 0;
try {
response.setContentType("application/x-msdownload");
response.setHeader("Content-disposition", "attachment;filename="
+ new String(fileName.getBytes("gb2312"),"iso8859-1"));
fis = new FileInputStream(file);
os = response.getOutputStream();
while((length=fis.read(bos))!=-1){
os.write(bos, 0, length);
// os.flush();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(os!=null)
os.close();
if(fis!=null)
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
注意:
1.response.setContentType("application/x-msdownload");
2.response.setHeader("Content-disposition", "attachment;filename="
+ new String(fileName.getBytes("gb2312"),"iso8859-1"));
PS:解決下載中文亂碼 fileName.getBytes("gb2312"),"iso8859-1")
3.待解決問題:選擇圖片下載時候點取消拋異常
----------------------------------------------------------------------------------------------
用commons.fileupload實現文件的上傳和下載2008年04月11日 星期五 15:27commons.fileupload實現文件的上傳,需要用到的組件如下:
1)Commons-fileupload-1.1.zip,下載地址為http://archive.apache.org/dist/jakarta/commons/fileupload/
2)commons-io-1.1.zip,下載地址為:http://archive.apache.org/dist/jakarta/commons/io/
代碼如下:
<%!
//服務器端保存上傳文件的路徑
String saveDirectory = "g:\\upload\\";
// 臨時路徑 一旦文件大小超過getSizeThreshold()的值時數據存放在硬盤的目錄
String tmpDirectory = "g:\\upload\\tmp\\";
// 最多只允許在內存中存儲的數據大小,單位:字節
int maxPostSize = 1024 * 1024;
%>
<%
// 文件內容
String FileDescription = null;
// 文件名(包括路徑)
String FileName = null;
// 文件大小
long FileSize = 0;
// 文件類型
String ContentType = null;
%>
<%
DiskFileUpload fu = new DiskFileUpload();//創建一個新的文件上傳句柄
// 設置允許用戶上傳文件大小,單位:字節
fu.setSizeMax(200*1024*1024);
// 設置最多只允許在內存中存儲的數據,單位:字節
fu.setSizeThreshold(maxPostSize);
// 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬盤的目錄
fu.setRepositoryPath("g:\\upload\\tmp\\");
//開始讀取上傳信息 得到所有文件
try{
List fileItems = fu.parseRequest(request);//解析上傳的請求
}catch(FileUploadException e){
//這里異常產生的原因可能是用戶上傳文件超過限制、不明類型的文件等
//自己處理的代碼
}
%>
<%
// 依次處理每個上傳的文件
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
//忽略其他不是文件域的所有表單信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
String contentType = item.getContentType();
if((name==null||name.equals("")) && size==0)
continue;
%>
<%
//保存上傳的文件到指定的目錄
String[] names=StringUtils.split(name,"\\"); //對原來帶路徑的文件名進行分割
name = names[names.length-1];
item.write(new File(saveDirectory+ name));
}
}
%>
下面是其簡單的使用場景:
A、上傳項目只要足夠小,就應該保留在內存里。
B、較大的項目應該被寫在硬盤的臨時文件上。
C、非常大的上傳請求應該避免。
D、限制項目在內存中所占的空間,限制最大的上傳請求,并且設定臨時文件的位置。
可以根據具體使用用servlet來重寫,具體參數配置可以統一放置到一配置文件
--------------------------------------------------------------------------------
文件的下載用servlet實現
public void doGet(HttpServletRequest request,
HttpServletResponse response)
{
String aFilePath = null; //要下載的文件路徑
String aFileName = null; //要下載的文件名
FileInputStream in = null; //輸入流
ServletOutputStream out = null; //輸出流
try
{
aFilePath = getFilePath(request);
aFileName = getFileName(request);
response.setContentType(getContentType(aFileName) + "; charset=UTF-8");
response.setHeader("Content-disposition", "attachment; filename=" + aFileName);
in = new FileInputStream(aFilePath + aFileName); //讀入文件
out = response.getOutputStream();
out.flush();
int aRead = 0;
while((aRead = in.read()) != -1 & in != null)
{
out.write(aRead);
}
out.flush();
}
catch(Throwable e)
{
log.error("FileDownload doGet() IO error!",e);
}
finally
{
try
{
in.close();
out.close();
}
catch(Throwable e)
{
log.error("FileDownload doGet() IO close error!",e);
}
}
}
1、拷貝pager-taglib.jar包
2、在JSP頁面中使用taglib指令引入pager-taglib標簽庫
3、使用pager-taglib標簽庫進行分頁處理
pg:pager【這個標簽用來設置分頁的總體參數】重要參數說明:
url:分頁的鏈接根地址,pager標簽會在這個鏈接的基礎上附加分頁參數
items:總記錄數,pager標簽正是根據這個值來計算分頁參數的
maxPageItems:每頁顯示的行數,默認為10
maxIndexPages:在循環輸出頁碼的時候,最大輸出多少個頁碼,默認是10
pg:first【第一頁的標簽】重要參數說明:
export變量的意義:
pageUrl - 分頁鏈接URL地址(最重要的export參數)
pageNumber - 頁碼
firstItem - 首頁第一行的索引值
lastItem - 首頁最后一行的索引值
pg:pre【上一頁標簽】重要參數說明:
export變量的意義:
pageUrl - 分頁鏈接URL地址(最重要的export參數)
pageNumber - 頁碼
firstItem - 前頁第一行的索引值
lastItem - 前頁最后一行的索引值
pg:next【下一頁標簽】重要參數說明:
export變量的意義:
pageUrl - 分頁鏈接URL地址(最重要的export參數)
pageNumber - 頁碼
firstItem - 下頁第一行的索引值
lastItem - 下頁最后一行的索引值
pg:last重要參數說明:
export變量的意義:
pageUrl - 分頁鏈接URL地址(最重要的export參數)
pageNumber - 頁碼
firstItem - 尾頁第一行的索引值
lastItem - 尾頁最后一行的索引值
pg:pages【這個標簽用來循環輸出頁碼信息】重要參數說明:
export變量的意義:
pageUrl - 分頁鏈接URL地址(最重要的export參數)
pageNumber - 頁碼
firstItem - pageNumber這個頁碼指定的那一頁的第一行的索引值
lastItem - pageNumber這個頁碼指定的那一頁的最后一行的索引值
文件上傳組件
1 Apache的Commons FileUpload
2 JavaZoom的UploadBean
3 jspSmartUpload
FileUpload下載網址:
http://commons.apache.org/fileupload/
步驟:
1 導入Apache的Commons FileUpload組件的兩個jar包
2 建上傳頁面
<form action="servlet/upload" method="post" enctype="multipart/form-data" name="form1">
上傳人:<input type="text" name="username"/><br/>
上傳文件:<input type="file" name="loadname"/><br/>
<input type="submit"/>
</form>
注意,form中enctype="multipart/form-data"屬性為上傳屬性,必寫
---------------------------------------------------------------------
3 建立servlet處理類
public class UploadServlet extends HttpServlet {
private ServletContext sc;//ServletContext定義了一系列方法用于與相應的servlet容器通信
private String savePath;
public void init(ServletConfig config) throws ServletException {
savePath = config.getInitParameter("savePath");//得到初始化信息
sc = config.getServletContext();//得到ServletContext接口的實例
}
private static final long serialVersionUID = 7093971456528100363L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
for (int i = 0; i < items.size(); i++) {
FileItem item = (FileItem) items.get(i);
if (item.isFormField()) {
System.out.println("表單的參數名稱:" + item.getFieldName()
+ ",對應的參數值:" + item.getString("UTF-8"));
} else {
if (item.getName() != null && !item.getName().equals("")) {
System.out.println("上傳文件的大小:" + item.getSize());
System.out.println("上傳文件的類型:" + item.getContentType());
System.out.println("上傳文件的名稱:" + item.getName());
File temFile = new File(item.getName());
File file = new File(sc.getRealPath("/") + savePath,
temFile.getName());
item.write(file);
request.setAttribute("upload.message", "上傳文件成功!");
} else {
request.setAttribute("upload.message", "沒有上傳文件成功!");
}
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("upload.message", "沒有上傳文件成功!");
}
request.getRequestDispatcher("/uploadresult.jsp").forward(request, response);
}
}
-----------------------------------------------------------------------------------
4 配置web.xml
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.webs.UploadServlet</servlet-class>
<init-param>
<param-name>savePath</param-name>
<param-value>uploads</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/servlet/upload</url-pattern>
</servlet-mapping>
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
Apache的commons-fileupload.jar可方便的實現文件的上傳功能,本文通過實例來介紹如何使用commons-fileupload.jar。
@author:ZJ 07-2-22
Blog: http://zhangjunhd.blog.51cto.com/
將Apache的commons-fileupload.jar放在應用程序的WEB-INF\lib下,即可使用。下面舉例介紹如何使用它的文件上傳功能。
所使用的fileUpload版本為1.2,環境為Eclipse3.3+MyEclipse6.0。FileUpload 是基于 Commons IO的,所以在進入項目前先確定Commons IO的jar包(本文使用commons-io-1.3.2.jar)在WEB-INF\lib下。
此文作示例工程可在文章最后的附件中下載。
示例1
最簡單的例子,通過ServletFileUpload靜態類來解析Request,工廠類FileItemFactory會對mulipart類的表單中的所有字段進行處理,不只是file字段。getName()得到文件名,getString()得到表單數據內容,isFormField()可判斷是否為普通的表單項。
demo1.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
//必須是multipart的表單數據。
<form name="myform" action="demo1.jsp" method="post"
enctype="multipart/form-data">
Your name: <br>
<input type="text" name="name" size="15"><br>
File:<br>
<input type="file" name="myfile"><br>
<br>
<input type="submit" name="submit" value="Commit">
</form>
</body>
</html>
demo1.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.util.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%
boolean isMultipart = ServletFileUpload.isMultipartContent(request);//檢查輸入請求是否為multipart表單數據。
if (isMultipart == true) {
FileItemFactory factory = new DiskFileItemFactory();//為該請求創建一個DiskFileItemFactory對象,通過它來解析請求。執行解析后,所有的表單項目都保存在一個List中。
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
//檢查當前項目是普通表單項目還是上傳文件。
if (item.isFormField()) {//如果是普通表單項目,顯示表單內容。
String fieldName = item.getFieldName();
if (fieldName.equals("name")) //對應demo1.html中type="text" name="name"
out.print("the field name is" + item.getString());//顯示表單內容。
out.print("<br>");
} else {//如果是上傳文件,顯示文件名。
out.print("the upload file name is" + item.getName());
out.print("<br>");
}
}
} else {
out.print("the enctype must be multipart/form-data");
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
</body>
</html>
結果:
the field name isjeff
the upload file name isD:\C語言考試樣題\作業題.rar
示例2
上傳兩個文件到指定的目錄。
demo2.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
<form name="myform" action="demo2.jsp" method="post"
enctype="multipart/form-data">
File1:<br>
<input type="file" name="myfile"><br>
File2:<br>
<input type="file" name="myfile"><br>
<br>
<input type="submit" name="submit" value="Commit">
</form>
</body>
</html>
demo2.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%String uploadPath="D:\\temp";
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart==true){
try{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);//得到所有的文件
Iterator<FileItem> itr = items.iterator();
while(itr.hasNext()){//依次處理每個文件
FileItem item=(FileItem)itr.next();
String fileName=item.getName();//獲得文件名,包括路徑
if(fileName!=null){
File fullFile=new File(item.getName());
File savedFile=new File(uploadPath,fullFile.getName());
item.write(savedFile);
}
}
out.print("upload succeed");
}
catch(Exception e){
e.printStackTrace();
}
}
else{
out.println("the enctype must be multipart/form-data");
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
</body>
</html>
結果:
upload succeed
此時,在"D:\temp"下可以看到你上傳的兩個文件。
示例3
上傳一個文件到指定的目錄,并限定文件大小。
demo3.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
<form name="myform" action="demo3.jsp" method="post"
enctype="multipart/form-data">
File:<br>
<input type="file" name="myfile"><br>
<br>
<input type="submit" name="submit" value="Commit">
</form>
</body>
</html>
demo3.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%
File uploadPath = new File("D:\\temp");//上傳文件目錄
if (!uploadPath.exists()) {
uploadPath.mkdirs();
}
// 臨時文件目錄
File tempPathFile = new File("d:\\temp\\buffer\\");
if (!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(4096); // 設置緩沖區大小,這里是4kb
factory.setRepository(tempPathFile);//設置緩沖區目錄
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(4194304); // 設置最大文件尺寸,這里是4MB
List<FileItem> items = upload.parseRequest(request);//得到所有的文件
Iterator<FileItem> i = items.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
String fileName = fi.getName();
if (fileName != null) {
File fullFile = new File(fi.getName());
File savedFile = new File(uploadPath, fullFile
.getName());
fi.write(savedFile);
}
}
out.print("upload succeed");
} catch (Exception e) {
e.printStackTrace();
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
</body>
</html>
示例4
利用Servlet來實現文件上傳。
Upload.java
package com.zj.sample;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@SuppressWarnings("serial")
public class Upload extends HttpServlet {
private String uploadPath = "D:\\temp"; // 上傳文件的目錄
private String tempPath = "d:\\temp\\buffer\\"; // 臨時文件目錄
File tempPathFile;
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(4096); // 設置緩沖區大小,這里是4kb
factory.setRepository(tempPathFile);// 設置緩沖區目錄
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(4194304); // 設置最大文件尺寸,這里是4MB
List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
Iterator<FileItem> i = items.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
String fileName = fi.getName();
if (fileName != null) {
File fullFile = new File(fi.getName());
File savedFile = new File(uploadPath, fullFile.getName());
fi.write(savedFile);
}
}
System.out.print("upload succeed");
} catch (Exception e) {
// 可以跳轉出錯頁面
e.printStackTrace();
}
}
public void init() throws ServletException {
File uploadFile = new File(uploadPath);
if (!uploadFile.exists()) {
uploadFile.mkdirs();
}
File tempPathFile = new File(tempPath);
if (!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
}
}
demo4.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
// action="fileupload"對應web.xml中<servlet-mapping>中<url-pattern>的設置.
<form name="myform" action="fileupload" method="post"
enctype="multipart/form-data">
File:<br>
<input type="file" name="myfile"><br>
<br>
<input type="submit" name="submit" value="Commit">
</form>
</body>
</html>
web.xml
<servlet>
<servlet-name>Upload</servlet-name>
<servlet-class>com.zj.sample.Upload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Upload</servlet-name>
<url-pattern>/fileupload</url-pattern>
</servlet-mapping>
JavaMail下載與安裝
http://java.sun.com/products/javamail/index.html
核心類與接口
javax.mail.Session
javax.mail.Message
javax.mail.Address
javax.mail.Authenticator
javax.mail.Transport
javax.mail.Store
javax.mail.Folder
-----------------------------------------------------
1 加載javamail的jar包
2 編寫處理類
public class SendMail {
public static void mian(String[] args){
Properties props=new Properties();
Session session=Session.getInstance(props,null);
props.put("mail.host", "127.0.0.1");//接收郵件的地址
props.put("mail.transport.protocol", "smtp");//傳輸郵件的協議
Message message=new MimeMessage(session);
try {
message.setFrom(new InternetAddress("ywj_sh110@163.com"));//設定發件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress("ywj_316@163.com"));//設定收件人
message.setSubject("你好嗎?");//設標題
message.setText("javamail發送郵件測試");//設內容
Transport.send(message);//發送信息
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
---------------------------------------------------
Apache Commons Email組件
1 加載javamail的jar包和Apache Commons Email的jar包
2 編寫servlet的處理類
public class SendCommMail extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
SimpleEmail email=new SimpleEmail();//生成SimpleEmail對象
email.setHostName("smtp.sina.com");//生成郵件
email.setAuthentication("web08", "web2008");//建立用戶
email.setCharset("UTF-8");//郵件內容編碼
try {
email.setFrom(request.getParameter("from"));//發件人
email.addTo(request.getParameter("to"));//收件人
email.setMsg(request.getParameter("context"));//內容
email.send();//發送郵件
request.setAttribute("sendmail.message", "郵件發送成功!");
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("sendmail.message", "郵件發送不成功!");
}
request.getRequestDispatcher("/sendResult.jsp").forward(request, response);
}
}
3 配置web.xml文件
4 頁面
----------------------------------------------------------------------
帶附件的郵件
1 1 加載javamail的jar包,Apache Commons Email的jar包和fileUpLoad
2 2 編寫servlet的處理類
public class SendCommMail extends HttpServlet {
private ServletContext sc;//ServletContext定義了一系列方法用于與相應的servlet容器通信
private String savePath;
File file;
private Map<String,String> parameters=new HashMap<String,String>();//存頁面信息
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
file=this.doAtta(request);
MultiPartEmail email=new MultiPartEmail();//生成SimpleEmail對象
email.setHostName("smtp.163.com");//生成郵件
email.setAuthentication("ywj_316", "1234567890");//建立用戶
email.setCharset("UTF-8");//郵件內容編碼
try {
email.setFrom(parameters.get("from"));//發件人
email.addTo(parameters.get("to"));//收件人
email.setMsg(parameters.get("context"));//內容
email.setSubject(parameters.get("title"));//主題
if(file!=null){
EmailAttachment attachment=new EmailAttachment();//附什對象
attachment.setPath(file.getParent());//附件路徑
attachment.setDescription(EmailAttachment.ATTACHMENT);//附件類型
attachment.setName(file.getName());//附件名稱
email.attach(attachment);
}
System.out.println("ssssssssssssssssssssssssssssssssssss");
email.send();//發送郵件
request.setAttribute("sendmail.message", "郵件發送成功!");
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("sendmail.message", "郵件發送不成功!");
}
request.getRequestDispatcher("/sendResult.jsp").forward(request, response);
}
public File doAtta(HttpServletRequest request)throws ServletException,IOException{
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
for (int i = 0; i < items.size(); i++) {
FileItem item = (FileItem) items.get(i);
if (item.isFormField()) {
parameters.put(item.getFieldName(), item.getString("UTF-8"));
System.out.println(item.getFieldName());
System.out.println(item.getString("UTF-8"));
} else {
if (item.getName() != null && !item.getName().equals("")) {
File temFile = new File(item.getName());
file = new File(sc.getRealPath("/") + savePath,
temFile.getName());
item.write(file);
request.setAttribute("upload.message", "上傳文件成功!");
} else {
request.setAttribute("upload.message", "沒有上傳文件成功!");
}
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("upload.message", "沒有上傳文件成功!");
}
return file;
}
public void init(ServletConfig config) throws ServletException {
savePath = config.getInitParameter("savePath");//得到初始化信息
sc = config.getServletContext();//得到ServletContext接口的實例
}
}
3 配置web.xml文件
<servlet>
<servlet-name>SendCommMail</servlet-name>
<servlet-class>com.webs.SendCommMail</servlet-class>
<init-param>
<param-name>savePath</param-name>
<param-value>uploads</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SendCommMail</servlet-name>
<url-pattern>/servlet/sendMail</url-pattern>
</servlet-mapping>
4 頁面
<body>
發送郵件的程序<br>
<form action="servlet/sendMail" name="form1" enctype="multipart/form-data" method="post">
收件人:<input type="text" name="to"/><br>
發件人:<input type="text" name="from"/><br>
主題:<input type="text" name="title"/><br>
附件:<input type="file" name="file"/><br>
內容:<input type="text" name="context"/><br>
<input type="submit"/>
</form>
</body>
序列化是把一個對象的狀態寫入一個字節流的過程,它執行RMI,RMI允許一臺機器上的JAVA對象調用不同機器上的JAVA對象方法,對象可以作為參數提供給那個遠程方法,發送機序列化該對象并傳送它,接收機執行反序列化。
序列化和反序列化的關系圖表可形成包含循環引用的順序圖表。這是整個序列化的總體思想。
而Serializable接口屬于支持序列化的一個接口,只有一個實現它的對象可以被序列化工具存儲和回復,Serializable接口沒有定義任何成員,只用來表示一個累可以被序列化,若該類可以序列化,那么它的所有子類都可以。
下面是關于序列化的一個實例:
程序名稱:SerializationDemo.java
程序主題:實現對象的序列化和反序列化
程序說明:該程序由實例化一個MyClass類的對象開始,該對象有三個實例變量,類型分別為String、int、double,是希望存儲和恢復的信息。
import java.io.*;
public class SerializationDemo{
public static void main(String args[]){
//Object serialization
try{
MyClass object1=new MyClass("Hello",-7,2.7e10);
System.out.println("object1:"+object1);
FileOutputStream fos=new FileOutputStream("serial");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(object1);
oos.flush();
oos.close();
}
catch(Exception e){
System.out.println("Exception during serialization:"+e);
System.exit(0);
}
//Object deserialization
try{
MyClass object2;
FileInputStream fis=new FileInputStream("serial");
ObjectInputStream ois=new ObjectInputStream(fis);
object2=(MyClass)ois.readObject();
ois.close();
System.out.println("object2:"+object2);
}
catch(Exception e){
System.out.println("Exception during deserialization:"+e);
System.exit(0);
}
}
}
class MyClass implements Serializable{
String s;
int i;
double d;
public MyClass(String s,int i,double d){
this.s=s;
this.i=i;
this.d=d;
}
public String toString(){
return "s="+s+";i="+i+";d="+d;
}
}
程序運行結果:object1和object2的實例變量是一樣的,輸出如下:
object1:s=Hello;i=-7;d=2.7E10
object2:s=Hello;i=-7;d=2.7E10
我補充一下:
Object serialization的定義:
Object serialization 允許你將實現了Serializable接口的對象轉換為字節序列,這些字節序列可以被完全存儲以備以后重新生成原來的對象。
serialization不但可以在本機做,而且可以經由網絡操作(就是貓小說的RMI)。這個好處是很大的----因為它自動屏蔽了操作系統的差異,字節順序(用Unix下的c開發過網絡編程的人應該知道這個概念,我就容易在這上面犯錯)等。比如,在Window平臺生成一個對象并序列化之,然后通過網絡傳到一臺Unix機器上,然后可以在這臺Unix機器上正確地重構這個對象。
Object serialization主要用來支持2種主要的特性:
1。Java的RMI(remote method invocation).RMI允許象在本機上一樣操作遠程機器上的對象。當發送消息給遠程對象時,就需要用到serializaiton機制來發送參數和接收返回直。
2。Java的JavaBeans. Bean的狀態信息通常是在設計時配置的。Bean的狀態信息必須被存起來,以便當程序運行時能恢復這些狀態信息。這也需要serializaiton機制。
二。sakulagi和rollingpig說的持久化我也說一下。
我覺得你們說的應該是英文里的persistence.但是Java語言里現在只支持lightweight persistence,就是輕量級持久化,這是通過serialization機制來實現的。
persistence是指一個對象的生命周期不由程序是否執行來決定,即使是在程序終止時這個對象也存在。它把一個serializable的對象寫到磁盤(本機或其他機器上的非RAM存儲器),并在程序重新調用時再讀取對象到通常的RAM存儲器。
為什么說Java的serialization機制實現的是lightweight persistence?因為你必須顯式的序列化和反序列化程序里的對象;而不是直接由一個關鍵詞來定義一個對象是序列化的然后由系統做相應的處理。 如果以后的Java版本出現一個新的關鍵字來實現這種機制,比如就是persistence,如果我用
persistence (String s="chinaunix")
然后系統自動做貓小程序里的那些處理,那么Java就實現了persistence.
public void synchronized getall(){}java.lang.Thread
【創建新線程的方法有兩種】
1 定義線程類實現Runnable接口
public class MyThred implements Runnable{
@overwrite
public void run(){}
}
起用線程:
MyThred myThred=new MyThred();
Thread t=new Thread(myThred);
t.start();
2 定義線程類繼承Thread類并重寫其run方法
public class MyThred extends Thread{
@overwrite
public void run(){}
}
起用線程:
MyThred myThred=new MyThred();
myThred.start();
說明:一般使用接口來實現
-------------------------------------------------
【線程狀態轉換】
【線程控制基本方法】:
isAlive() 判斷線程是否還“活”著
getPriority() 獲得線程的優先級
setPriority() 設置線程的優先級
Thread.sleep() 將當前線程睡眠指定的毫秒數
join() 調用某線程的該方法,將當前線程與該線程“合并”,即等待
該線程線束,再恢復當前線程的運行。
yield() 讓出CPU,當前線程進入就緒隊列等待調度
wait() 當膠線程進入對象的wait pool。
notify()/notifyAll() 喚醒對象的wait pool中的一個/所有等待線程。
Thread.currentThread() 得到當前線程
----------------------------------------------------------------
【sleep/join/yield 方法】
sleep示例:
public class TestInterrupt {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
//主線程睡眠
try {Thread.sleep(10000);}
catch (InterruptedException e) {}
//停下當前線程,這個方法一般不建議使用
thread.interrupt();
//使用這個結束線程
shutDown();
}
}
class MyThread extends Thread {
boolean flag = true;
public void run(){
while(flag){
System.out.println("==="+new Date()+"===");
try {
//當前子線程睡眠
sleep(1000);
//sleep時被打斷會拋InterruptedException
} catch (InterruptedException e) {
return;
}
}
}
//結束線程的方法
public void shutDown(){
flag = false;
}
}
jion示例:
public class TestJoin {
public static void main(String[] args) {
MyThread2 t1 = new MyThread2("abcde");
t1.start();
try {
//當前線程合并到主線程,相當于方法調用
t1.join();
} catch (InterruptedException e) {}
for(int i=1;i<=10;i++){
System.out.println("i am main thread");
}
}
}
class MyThread2 extends Thread {
//給當前線程起個別名
MyThread2(String s){
super(s);
}
public void run(){
for(int i =1;i<=10;i++){
System.out.println("i am "+getName());
try {
sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
}
yield示例:
public class TestYield {
public static void main(String[] args) {
//可以用同一個線程類創建不同的線程對象,分別執行
MyThread3 t1 = new MyThread3("t1");
MyThread3 t2 = new MyThread3("t2");
t1.start(); t2.start();
}
}
class MyThread3 extends Thread {
MyThread3(String s){super(s);}
public void run(){
for(int i =1;i<=100;i++){
System.out.println(getName()+": "+i);
if(i%10==0){
//讓出時間給其它線程執行
yield();
}
}
}
}
--------------------------------------------------------------
【線程的優先級別】getPriority()/setProority(int newPriority)
線程的優先級用數字表示,范圍從1到10,默認為5.
Thread.MIN_PRIORITY=1
Thread.MAX_PRIORITY=10
Thread.NORM_PRIORITY=5
示例:
public class TestPriority {
public static void main(String[] args) {
Thread t1 = new Thread(new T1());
Thread t2 = new Thread(new T2());
//將t1的優先級提高3級
t1.setPriority(Thread.NORM_PRIORITY + 3);
t1.start();
t2.start();
}
}
class T1 implements Runnable {
public void run() {
for(int i=0; i<1000; i++) {
System.out.println("T1: " + i);
}
}
}
class T2 implements Runnable {
public void run() {
for(int i=0; i<1000; i++) {
System.out.println("------T2: " + i);
}
}
}
--------------------------------------------------------------------
【線程的同步】未看完
生成jar包
jar -cvf test.jar *.*
*.*是指當前目錄下所有文件打包到目標目錄下
是否是該類或該類的子類類型的對象
instanceof
car instanceof Car
增加的for循環
int[] arr={1,2,4,5,6};
for(int i:arr){}//只用于顯示,不可以訪問i