JSP文件上傳下載

jsp:

<form id="update_form" method="post" enctype="multipart/form-data">

    <div class="form-group">

        <div class="validate_body col-xs-9">

            <input type="file" id="fileUpload" name="fileUpload"/>

        </div>

    </div>

</form>

java:

@RequestMapping(value = "/save")

public String save(ModelMap model, HttpServletRequest request)

{//TODO 保存

    String dirPath = "/pdffiles/"; //文件夾名

    dirPath = request.getRealPath(dirPath) "/";

    String fileName;

    try {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        List<MultipartFile> fileList = multipartRequest.getFiles("fileUpload");

        for (MultipartFile mf : fileList) {

            if(!mf.isEmpty()){

                if (mf.getContentType().equals("application/pdf")){

                    fileName = UUID.randomUUID() "." FilenameUtils.getExtension(mf.getOriginalFilename());

                    String savePath = dirPath  fileName;

                    File file =new File(savePath);    

                    if (!file.getParentFile().exists())

                    {

                        file.getParentFile().mkdirs();

                    }

                    InputStream in=mf.getInputStream(); 

                    FileOutputStream fos=new FileOutputStream(savePath); 

                    byte[] buffer=new byte[1024]; 

                    while(in.read(buffer)>0){ 

                        fos.write(buffer); 

                        fos.flush(); 

                    } 

                    in.close(); 

                    fos.close();

                    getParames().put("instructionBookDirectory", savePath);

                }

            }

        }

    }catch (Exception e) {

        e.printStackTrace();

    }

    service.update(getParames());

    return "redirect:list.jhtml";

}

jsp:

<div>

    <a href="downloadfile.jhtml?dir=${row.instructionBookDirectory}">下載</a>

</div>

java:

// 下載文件

@RequestMapping(value = "/downloadfile")

public void downloadfile(ModelMap model, HttpServletResponse response)

{

   response.setContentType("charset=UTF-8");

   Object dir = getParames().get("dir");

   if(dir!=null){

       File file = new File(dir.toString()); 

       response.setHeader("Content-Disposition", "attachment; filename=a");  

       BufferedInputStream bis = null; 

       BufferedOutputStream bos = null; 

       OutputStream fos = null; 

       InputStream fis = null; 

       try { 

            fis = new FileInputStream(file.getAbsolutePath()); 

            bis = new BufferedInputStream(fis); 

            fos = response.getOutputStream(); 

            bos = new BufferedOutputStream(fos); 

            int bytesRead = 0; 

            byte[] buffer = new byte[5 * 1024]; 

            while ((bytesRead = bis.read(buffer)) != -1) { 

                bos.write(buffer, 0, bytesRead); 

            } 

            bos.flush(); 

        }catch(Exception e){ 

            e.printStackTrace();

        }finally { 

            try { 

                bis.close(); 

                bos.close(); 

                fos.close(); 

                fis.close(); 

            } catch (Exception e) { 

                e.printStackTrace(); 

            } 

        }

   }

}
1、JSON語法是JavaScript對象表示語法的子集。JSON數據的書寫格式是:名稱/值對。

(1)數據在鍵值對中

(2)數據由逗號分離

(3)花括號保存對象

(4)方括號保存數組

2、JSON的值:

 (1)數字(整數或者浮點數)

 (2)字符串

 (3)邏輯值 (true或false)

   (4)  數組

 (5)對象

 (6) null

3、在 JSON裏[]是 Array(也就是數組),{}是Ojbect(也就是對象),

[] Array 的key 是 int,{} 的key 是 string。



例如 var dot1=["a"];就是一個數組

       var dot2={"a"};就是一個對象

一個數組是能夠包含多個對象的

例如: var dot1=[{a:"a"},{b:"b"}]; dot1就包含了2個對象

一樣,dot1={[{a:"a"},{b:"b"}]} 就是一個對象,只是這個對象包含了一個數組
Session 在 web 開發中是一個很是重要的概念,在不一樣的場合,Session 一次 的 含義也很不相同。這裏只探討 HTTP Session 。這裏基於 Java Servlet 理解 Session 的概念與原理,由於 JSP 最終也會被編譯爲 Servlet,二者有着相同的本質,這裏所說 Servlet 已經涵蓋了 JSP 技術。在 Java 中,HTTP 的 Session 對象用 javax.servlet.http.HttpSession 來表示。

一、概念

Session 表明服務器與瀏覽器的一次會話過程,這個過程是連續的,也能夠時斷時續的。在 Servlet 中,Session 指的是HttpSession 類的對象。

二、Session建立的時間

一個常見的誤解是覺得 Session 在有客戶端訪問時就被建立,然而事實是直到某 Server 端程序調用

HttpServletRequest.getSession(true)

這樣的語句時,Session 才被建立,注意若是 JSP 沒有顯示的使用

 <% @page Session="false"%>

關閉 Session,則 JSP 文件在編譯成 Servlet 時將會自動加上這樣一條語句

HttpSession Session = HttpServletRequest.getSession(true);

這也是JSP中隱含的 Session 對象的來歷。因爲 Session 會消耗內存資源,所以,若是不打算使用 Session,應該在全部的 JSP 中關閉它。

引伸

1)、訪問*.html的靜態資源由於不會被編譯爲Servlet,也就不涉及Session的問題。

2)、當JSP頁面沒有顯式禁止Session的時候,在打開瀏覽器第一次請求該JSP的時候,服務器會自動爲其建立一個Session,並賦予其一個SessionID,發送給客戶端的瀏覽器。之後客戶端接着請求本應用中其餘資源的時候,會自動在請求頭上添加:

Cookie : JSESSIONID=客戶端第一次拿到的 Session ID

這樣,服務器端在接到請求時候,就會收到 Session ID,並根據 ID 在內存中找到以前建立的 Session 對象,提供給請求使用。這也是 Session 使用的基本原理 —— 搞不懂這個,就永遠不明白Session的原理。

下面是兩次請求同一個 JSP,請求頭信息:

經過圖能夠清晰的發現,第二次請求的時候,已經添加Session ID的信息。

 三、Session 刪除的時間是:

1)Session超時:超時指的是連續必定時間服務器沒有收到該Session所對應客戶端的請求,而且這個時間超過了服務器設置的Session超時的最大時間。

2)程序調用HttpSession.invalidate()

3)服務器關閉或服務中止

四、Session存放在哪裏:服務器端的內存中。不過Session能夠經過特殊的方式作持久化管理。

五、Session的id是從哪裏來的,SessionID是如何使用的

當客戶端第一次請求Session對象時候,服務器會爲客戶端建立一個Session,並將經過特殊算法算 出一個Session的ID,用來標識該Session對象,當瀏覽器下次(Session繼續有效時)請求別的資源的時候,瀏覽器會偷偷地將 SessionID放置到請求頭中,服務器接收到請求後就獲得該請求的SessionID,服務器找到該id的Session返還給請求者 (Servlet)使用。一個會話只能有一個Session對象,對Session來講是隻認id不認人。

六、Session會由於瀏覽器的關閉而刪除嗎?

不會,Session只會經過上面提到的方式去關閉。

七、同一客戶端機器屢次請求同一個資源,Session同樣嗎?

通常來講,每次請求都會新建立一個Session。

其實,這個也不必定的,總結下:對 於多標籤的瀏覽器(好比360瀏覽器)來講,在一個瀏覽器窗口中,多個標籤同時訪問一個頁面,Session是一個。對於多個瀏覽器窗口之間,同時或者相 隔很短期訪問一個頁面,Session是多個的,和瀏覽器的進程有關。對於一個同一個瀏覽器窗口,直接錄入url訪問同一應用的不一樣資 源,Session是同樣的。

八、Session是一個容器,能夠存放會話過程當中的任何對象。

九、Session由於請求(request對象)而產生,同一個會話中多個request共享了一個 Session 對象,能夠直接從請求中獲取到 Session 對象。

 十、其實,Session 的建立和使用總在服務端,而瀏覽器歷來都沒獲得過Session對象。但瀏覽器能夠請求Servlet(JSP 也是 Servlet)來獲取 Session 的信息。客戶端瀏覽器僅僅拿到的是 Session ID,而這個對於瀏覽器操做的人來講,是不可見的,而且用戶也無需關心本身處於哪一個會話過程當中。
摘要: 在Java模板引擎 FreeMarker介紹中,咱們已經對freemarker有了必定的瞭解,這一節是FreeMarker入門教程。下載freemarker,定義模板文件,輸出到控制檯和文件中。

在Java模板引擎 FreeMarker介紹中,咱們已經對freemarker有了必定的瞭解,如下是FreeMarker入門教程。



下載freemarker

http://freemarker.sourceforge.net/freemarkerdownload.html

項目文件:freemarker-2.3.19.tar.gz

中文文檔:FreeMarker_Manual_zh_CN.pdf

解壓後把freemarker.jar加到classpath中便可完成環境的配置



定義模板文件

咱們建立兩個模板文件,一個是純文本的模板文件,另外一個是HTML格式的模板文件,主要是爲了說明,freemarker的模板文件能夠是任何格式的

01.ftl

你好:${username}

02.ftl

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

<h1>${username}</h1>

</body>

</html>

建立freemarker工具類

這個類,主要是獲取模板定義文件,並根據輸入的數據輸出到控制檯和文件中

package com.naxsu.freemarker;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Map;

import freemarker.template.Configuration;

import freemarker.template.Template;

import freemarker.template.TemplateException;

public class FreemarkerUtil {

    /**

     * 獲取模板

     * @param name

     * @return

     */

    public Template getTemplate(String name) {

    try {

        //經過Freemaker的Configuration讀取相應的ftl

        Configuration cfg = new Configuration();

        //設定去哪裏讀取相應的ftl模板文件

        cfg.setClassForTemplateLoading(this.getClass(),"/ftl");

        //在模板文件目錄中找到名稱爲name的文件

        Template temp = cfg.getTemplate(name);

        return temp;

    } catch (IOException e) {

        e.printStackTrace();

    }

    return null;

    }

    /**

     * 輸出到控制檯

     * @param name 模板文件名

     * @param root

     */

    public void print(String name,Map<String,Object> root) {

        try {

            //經過Template能夠將模板文件輸出到相應的流

        Template temp = this.getTemplate(name);

        temp.process(root, new PrintWriter(System.out));

    } catch (TemplateException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

    }

    /**

     * 輸出到文件

     * @param name

     * @param root

     * @param outFile

     */

    public void fprint(String name,Map<String,

                       Object> root,String outFile) {

    FileWriter out = null;

    try {

            //經過一個文件輸出流,就能夠寫到相應的文件中

        out = new FileWriter(

                      new File("E:\\freemarker\\ftl\\" outFile));

        Template temp = this.getTemplate(name);

        temp.process(root, out);

    } catch (IOException e) {

        e.printStackTrace();

    } catch (TemplateException e) {

        e.printStackTrace();

    } finally {

        try {

        if(out!=null) out.close();

        } catch (IOException e) {

        e.printStackTrace();

        }

    }

    }

}

模擬數據,進行測試

public class TestFreemarker {

    FreemarkerUtil fu;

    Map<String,Object> root = null;

    @Before

    public void setUp() {

        fu = new FreemarkerUtil();

        root = new HashMap<String,Object>();

    }

    @Test

    public void test01() {

        //一、建立數據模型

        Map<String,Object> root = new HashMap<String,Object>();

        //二、爲數據模型添加值

        root.put("username", "張三");

        //三、將數據模型和模板組合的數據輸出到控制檯

        fu.print("01.ftl", root);

        fu.fprint("02.ftl", root, "01.html");

    }

}



好了,helloword到此爲止,簡單入門就是如此簡單
相關文章
相關標籤/搜索