posts - 54,  comments - 1,  trackbacks - 0
          原文
            編程思路:下面的UploadServlet.java ,其主要功能為從InputStream 中讀取文件內(nèi)容,將上傳文件保存在根目錄下,且文件名與上傳文件的文件名一致。
          import java.io.*;
          import javax.servlet.*;
          import javax.servlet.http.*;

          public class UploadServlet extends HttpServlet
          {
          //default maximum allowable file size is 1000k
          static final int MAX_SIZE = 1024000;
          //instance variables to store root and success message
          String rootPath, successMessage;
          /**
          * init method is called when servlet is initialized.
          */

          public void init(ServletConfig config) throws ServletException
          {
          super.init(config);
          //get path in which to save file
          rootPath = config.getInitParameter("RootPath");
          if (rootPath == null)
          {
          rootPath 
          = "/";
          }

          /*Get message to show when upload is complete. Used only if
          a success redirect page is not supplied.
          */

          successMessage 
          = config.getInitParameter("SuccessMessage");
          if (successMessage == null)
          {
          successMessage 
          = "File upload complete!";
          }

          }

          /**
          * doPost reads the uploaded data from the request and writes
          * it to a file.
          */

          public void doPost(HttpServletRequest request,
          HttpServletResponse response)
          {
          ServletOutputStream out
          =null;
          DataInputStream in
          =null;
          FileOutputStream fileOut
          =null;

          try
          {
          /*set content type of response and get handle to output
          stream in case we are unable to redirect client
          */

          response.setContentType(
          "text/plain");
          out 
          = response.getOutputStream();

          //get content type of client request
          String contentType = request.getContentType();
          out.println(
          "\ncontentType= " + contentType);

          //make sure content type is multipart/form-data
          if(contentType != null && contentType.indexOf(
          "multipart/form-data"!= -1)
          {
          //open input stream from client to capture upload file
          in = new DataInputStream(request.getInputStream());
          //get length of content data
          int formDataLength = request.getContentLength();
          out.println(
          "\nContentLength= " + formDataLength);

          //allocate a byte array to store content data
          byte dataBytes[] = new byte[formDataLength];
          //read file into byte array
          int bytesRead = 0;
          int totalBytesRead = 0;
          int sizeCheck = 0;
          while (totalBytesRead < formDataLength)
          {
          //check for maximum file size violation
          sizeCheck = totalBytesRead + in.available();
          if (sizeCheck > MAX_SIZE)
          {
          out.println(
          "Sorry, file is too large to upload.");
          return;
          }
          編程技巧說明:

            首先定義上傳文件最大字節(jié)為1024K(1M),上傳文件保存在根目錄(/)下,從請求的InputStream 讀取實體數(shù)據(jù),根據(jù)請求頭Content-Type 和contenLength 等值,從實體數(shù)據(jù)中解析出表單Form 數(shù)據(jù)中的filename 和Content-Type 等值,然后將實體數(shù)據(jù)中真正屬于上傳文件的內(nèi)容保存到服務(wù)器上的根目錄文件中。

            其中用到涉及中文輸出:
          String fileStr=new String(dataBytes,"ISO8859_1");
          fileOut
          =new FileOutputStream(rootPath+fileName);
          fileOut.write(fileStr.getBytes(
          "ISO8859_1"),0,fileStr.legth()); 
            UploadFile.html 的源代碼如下:
          <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
          <html>
          <head>
          <meta http-equiv="Content-Type" content="text/html; charset=gb_2312-80">
          <title>Upload a File</title>
          </head>
          <body>
          <h1>文件上傳 </h1>
          <h2>提示:您的瀏覽器必須能支持文件上傳!</h2>
          <form action="servlet/uploadServlet" method="POST" enctype="multipart/form-data">
          <div align="left">
          <pre>發(fā)送文件:<input type="file" size="40" name="upl-file"> </BR>
          <input type="submit" value="開始發(fā)送" now> 
          <input type="reset" value="重 設(shè)"></pre>
          </div>
          </form>
          </body>
          </html> 
            小結(jié):

            (1) Servlet 編程要求讀者已經(jīng)掌握了Java 語言程序設(shè)計,最好對面向?qū)ο笠灿幸欢ǖ牧私狻ava 語言程序設(shè)計最主要的是對Java 的類庫的使用,同樣掌握Servlet 編程也要求熟練使用Sun 公司提供的JSDK。

            (2) 一個好的Servlet 程序必須要考慮得全面。由于Servlet 在服務(wù)器上執(zhí)行,為客戶提供服務(wù),有時可能會有多個客戶同時向一個服務(wù)器發(fā)請求,這就要求Servlet 程序必須能夠保證良好的并發(fā)性。允許Servlet 并發(fā)執(zhí)行,就要解決Servlet 中變量和同步訪問以及共享的問題,尤其要特別注意服務(wù)器的一些昂貴的資源。另一方面,Servlet 要把處理結(jié)果返回給客戶,要求Servlet 充分考慮響應(yīng)的速度和響應(yīng)結(jié)果的簡潔明了,同時對客戶的錯誤請求有一定的容錯性。

            (3) 解決Servlet 中文輸出問題

            當(dāng)Servlet 輸出的文檔中有中文時,需要在Servlet 中使用下面的語句來指明:
          response.setContentType("text/html;charset=gb2312"); 
            在JSP中使用:
          <%@page contentType="text/html;charset=gb2312"%> 
            這兩者是等效的。

            如果在Servlet 中文顯示有問題,可從以下幾方面來考慮:

            * 修改區(qū)域設(shè)置---在控制面板中選擇區(qū)域設(shè)置,如設(shè)為英語(美國)。

            * 在編譯Servlet 時加入代碼選項,如:javac -encoding iso8859-1 ghqServlet.java

            * 在源程序中加入編碼轉(zhuǎn)換函數(shù),如:out.println(new String("請輸入用戶名").getBytes("GBK"),"ISO8859_1"));

            或者使用下面的方法:
          String Str="請輸入用戶名";
          Byte[] tempByte=Str.getBytes("ISO8859_1");
          String tempStr=new String(tempByte); 

            這樣tempStr 中的中文就可以正確顯示了。

            由于Servlet 采用不同的引擎,其中文的解決方法可能不同;因此,當(dāng)出現(xiàn)中文顯示問題時,建議一定要多實驗,最終總會得到解決。

            (4) Java Servlet 程序彌補了 Applet 程序的不足, Servlet 主要應(yīng)用在HTTP Servlet 接收請求(HttpServletRequest接口)和產(chǎn)生響應(yīng)(HttpServletResponse接口)、使用Cookies 及會話管理(HttpSession 接口)應(yīng)用、Java Servlet 在網(wǎng)絡(luò)上的編程應(yīng)用如利用Servlet 上傳和下載文件、Servlet 的數(shù)據(jù)庫編程、在Servlet 中發(fā)送和接受郵件以及Java Servlet 在RMI和XML等方面的應(yīng)用,因此Servlet 的編程應(yīng)用還是比較廣泛的。

            通常 Servlet 可以使用以下的方法調(diào)用:

            * 客戶通過訪問 Servlet 產(chǎn)生的文檔來調(diào)用

            Server 得到一個訪問文檔的請求后,查找配置參數(shù),就會發(fā)現(xiàn)所需文檔不是一個靜態(tài)文檔,而是由 Servlet 對象產(chǎn)生的,于是服務(wù)器就會把請求傳給 Servlet,Servlet 調(diào)用 "service" 方法產(chǎn)生輸出。這種方法與傳統(tǒng)的調(diào)用 CGI 的方法類似。

            * 直接通過 URL 調(diào)用 Servlet

            客戶(瀏覽器)使用以下格式的 URL 調(diào)用:

          http://Servlet_Host_Name/servlet/<servlet URL>

          <servlet URL>是指向 Servlet 位置的普通的URL,它的格式如下所示:

          name?para1=value1&para2=value2...

            其中,name 是 Servlet 的名字,"?" 后面跟的是一串參數(shù),para1 是第一個參數(shù)名,value1是它的值,para1 是第二個參數(shù)名,value2是它的值,以此類推。通常Servlet 存放的位置可能與服務(wù)器不在同一臺機器上,這時服務(wù)器就要動態(tài)加載、初始化和執(zhí)行Servlet 類。

            * 通過 SSI(Server-Side Includes) 標志調(diào)用

            任何一個以.sthml 為擴展名的文件都是服務(wù)器要分析的文件。在該文件中,如果出現(xiàn)了Servlet標志,那么服務(wù)器就會運行該Servlet,并把它的輸出結(jié)果插入標志所指示的地方。

            * 把 Servlet 放在/servlet/目錄下

            如果一個 Servlet 的類文件被放在/servlet/目錄下,那么就可以直接使用它的類名調(diào)用它。 

            * 通過 Filter Chain 調(diào)用

            這種方法一般要把 Servlet 配置成當(dāng)一個特定的 MIME 類型被設(shè)置為響應(yīng)時再調(diào)用。

            但Servlet 也有它的缺點:

            * 在復(fù)雜的HTML 網(wǎng)頁中,加入的動態(tài)部分如果用Servlet 來處理的話,那對程序員來說簡直是一場噩夢。

            * Servlet 要進行編譯、放入執(zhí)行碼等復(fù)雜的調(diào)用過程。

            正是由于Servlet存在的缺點,才出現(xiàn)使用JSP 技術(shù)來解決上面的問題,這也正是JSP 的優(yōu)點。


          posted on 2005-12-02 11:09 ZhuJun 閱讀(3730) 評論(0)  編輯  收藏 所屬分類: 他山の玉

          蜀中人氏,躬耕于珠海

          <2005年12月>
          27282930123
          45678910
          11121314151617
          18192021222324
          25262728293031
          1234567

          常用鏈接

          留言簿(2)

          隨筆分類(71)

          隨筆檔案(54)

          博客

          文檔

          站點

          論壇

          搜索

          •  

          積分與排名

          • 積分 - 51043
          • 排名 - 976

          最新評論

          閱讀排行榜

          主站蜘蛛池模板: 江油市| 平昌县| 普安县| 桐城市| 辽阳市| 泰来县| 股票| 盐源县| 博乐市| 永康市| 乃东县| 元朗区| 福建省| 巩义市| 民县| 剑川县| 怀集县| 工布江达县| 肥东县| 海伦市| 徐汇区| 旬阳县| 盈江县| 新干县| 桃园市| 望都县| 察哈| 宝兴县| 宁国市| 呈贡县| 高青县| 伊宁市| 固镇县| 博白县| 家居| 东阿县| 尼玛县| 原平市| 乐安县| 武隆县| 深水埗区|