Web常用對象(2)

來源:互聯網
上載者:User

標籤:ade   jar包   interval   輸入   上傳下載   表示   coding   cti   儲存   

一、Session

  1、介紹

    HttpSession是一個純粹的介面,session本身就屬於HTTP協議的範疇。

    session的作用就是為了標識一次會話,或者說確認一個使用者;並且在一次會話(一個使用者多次請求)期間共用資料。

  2、建立對象和屬性操作

    

 

  3、表示會話JSESSIONID

    每當一次請求到達伺服器,如果訪問了session,伺服器會第一步查看是否從用戶端回傳一個名為JSESSION的Cookie,如果沒有則認為這是一次新的會話,會建立一個新的session對象,並用唯一的JSESSIONID為此次會話做一個標誌,如果有則認為這是之前標誌過的一次會話,返回該對象,達到資料共用

 

  4、session範圍

    和request域一樣可以通過setAttribute(name,value);方法向域對象中添加資料,通過getAttribute(name)從域對象中擷取資料,通過removeAttribute(name)從域對象中移除資料。

    

  

  5、session的銷毀

    因為session底層依賴Cookie實現,並且該Cookie的有效時間為關閉瀏覽器,所以關閉瀏覽器session失效

    當非正常關閉伺服器時,session銷毀;當正常關閉伺服器時,session將被序列化到磁碟上,下次啟動服務自動載入到記憶體。

      序列化:把對象和其狀態存到本地磁碟

    1)預設時間到期

      Tomcat中session預設存活時間為30min,一旦有操作session會重新計時。

    2)自己設定到期時間

      ·可以在Tomcat中的web.xml檔案中進行修改

      ·session.setMaxInactiveInterval(int);  以秒為單位

    3)立刻失效

      session.invalidate();

 

    session的銷毀或失效意味著本次會話技術,資料共用結束。

 

二、ServletContext對象

  1、介紹

    每一個web應用有且僅有一個ServletContext對象,又稱Application對象,該對象是與應用程式相關的,當WEB容器啟動時,會為每一個WEB應用程式建立一個對應的ServletContext對象。

  2、ServletContext對象的作用

    1)作為域對象用來共用資料,此時資料在整個應用程式中共用

    2)該對象中儲存了當前應用程式的相關資訊,可以通過方法擷取。

       

 

  3、ServletContext對象的四種擷取方法

    

  4、作為域對象

    通過向ServletContext中存取資料,可以使得整個應用程式共用某些資料,不建議存放過多資料,因為ServletContext中的資料一旦儲存進去沒有手動移除會一直儲存

    

 

三、檔案上傳下載

  1、檔案上傳

    前台頁面:

      請求方式為POST,form表單的enctype必須設為“multipart/form-data”.

    後台:需要commos-io和commons-fileupload兩個jar包(2.5版本的動態web項目)    

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // 設定編碼,可以擷取中文檔案名稱        request.setCharacterEncoding("UTF-8");        // 擷取tomcat下的upload目錄的路徑        String path = getServletContext().getRealPath("/upload");        // 臨時檔案目錄        String tempPath = getServletContext().getRealPath("/temp");        // 檢查我們是否有檔案上傳請求        // boolean isMultipart = ServletFileUpload.isMultipartContent( req);        // 1、聲明DiskFileItemFactory工廠類,用於在指定磁碟上設定一個臨時目錄        DiskFileItemFactory disk = new DiskFileItemFactory(1024 * 10, new File(tempPath));        // 2、聲明ServletFileUpload,接收上面的臨時檔案。也可以預設值        ServletFileUpload up = new ServletFileUpload(disk);        // 3、解析request        try {            List<FileItem> list = up.parseRequest(request);            if (list.size() > 0) {                for (FileItem file : list)                    // 判斷是否是普通的表單項                    if (file.isFormField()) {                        String fieldName = file.getFieldName();                        // 中文亂碼,此時還需要指定擷取資料的編碼方式                        // String value = file.getString();                        String value = file.getString("UTF-8");                        System.out.println(fieldName + "=" + value);                    } else { // 說明是一個檔案                        // 擷取檔案本身的名稱                        String fileName = file.getName();                        System.out.println(file.getFieldName());                        // 處理檔案名稱                        fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);                        System.out.println("old Name : " + fileName);                        // 修改名稱                        String extName = fileName.substring(fileName.lastIndexOf("."));                        String newName = UUID.randomUUID().toString().replace("-", "") + extName;                        // 儲存新的名稱,並寫出到新檔案中                        file.write(new File(path + "/" + newName));                        System.out.println("檔案名稱是: " + fileName);                        System.out.println("檔案大小是: " + file.getSize());                        file.delete();                    }            }        } catch (FileUploadException e) {            e.printStackTrace();        } catch (Exception e) {            e.printStackTrace();        }    }
Upload

 

  2、檔案下載

    前台:

      設定download屬性

 

    後台實現下載:

      

public class DownloadServlet extends HttpServlet {    @Override    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        // 佈建要求 響應編碼        req.setCharacterEncoding("UTF-8");        resp.setContentType("text/html;charset=UTF-8");        // 擷取檔案名稱        String fileName = req.getParameter("fileName");        // 判斷檔案名稱是否為空白        if (fileName == null || fileName.length() < 1) {            PrintWriter out = resp.getWriter();            out.write("<h1>請輸入檔案名稱</h1><a href=‘download.html‘>返回</a>");            out.close();            return;        }        // 擷取存放檔案的目錄        String path = getServletContext().getRealPath("/upload/");        // 擷取檔案的路徑        String filePath = path + fileName;        // 通過路徑獲得file對象        File file = new File(filePath);        // 判斷file對象是不是存在而且是檔案        if (file.exists() && file.isFile()) {            // 下載            // 1、設定響應類型            resp.setContentType("application/x-msdownload");            // 2、設定下載的彈出框資訊            resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);            // 3、擷取位元組輸入資料流            InputStream is=new FileInputStream(filePath);            // 3、擷取位元組輸出資料流            ServletOutputStream out=resp.getOutputStream();            byte[] bs=new byte[1024];            int len=0;            while ((len=is.read(bs))!=-1) {                out.write(bs,0,len);            }            out.close();            is.close();        } else {            PrintWriter out = resp.getWriter();            out.write("<h1>檔案不存在</h1><a href=‘download.html‘>返回</a>");            out.close();        }    }}

 

Web常用對象(2)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.