iT邦幫忙

0

【左京淳的JAVA WEB學習筆記】第四章 轉發、重定向、steam輸出

轉發、重定向與域的概念

之前的章節使用轉發(RequestDispatcher),將使用者送往下一個頁面。如下:

  request.getRequestDispatcher("/main/hello.jsp").forward(request, response);

但是轉發前與轉發後屬於同一次HTTP request,所以url列也會保持一樣。
如果使用者按了重新整理的話,可能就會造成問題。
例如在登入或付款頁面這種關鍵操作,就必須使用重定向(sendRedirect)。如下例:

  String path = request.getContextPath();
  response.sendRedirect(path + "/main/hello.jsp");

由於重定向是兩次不同的HTTP request,因此無法像轉發一樣使用request物件攜帶資料趴趴造,而是需要用生命週期更長的session來傳遞訊息。
召喚session的方式如下例:

request.getSession().setAttribute("username",username);

作用域分為四種,分別為:

page 在當前頁面有效(僅用於JSP中)
request 在當前請求中有效
session 在瀏覽器關閉前有效(也可設置逾期時間)
application 在伺服器關機前有效

召喚application的方式如下例:

request.getServletContext();

Servlet除了返回給使用者HTML頁面外,也可以返回文字列或byte stream資料(例如圖片)。
這在使用AJAX技術(部分更新頁面的技術)時會被使用到。

使用PrintWriter返回文字列

PrintWriter out = response.getWriter();
out.write("ABC"); //將文字寫到暫存區
out.flush(); //將暫存區的文字輸出
out.close(); //關閉writer

使用ServletOutputStream輸出byte stream資料

//取得專案路徑,並加上"/"。
String path = request.getServletContext().getRealPath("/");
//組合成完整圖片路徑
String picName = path + "/pic/picture.png";
//以二次元陣列的方式讀取檔案
byte[] pic = FileUtils.readFileToByteArray(new File(picname));

//使用ServletOutputStream輸出byte stream資料
ServletOutputStream out = response.getOutputStream();
out.write(pic);
out.flush();
out.close();

使用include動態嵌入頁首頁尾

在使用PrintWriter寫出資料時,也可以搭配include()來加入頁首頁尾。

RequestDispatcher head = request.getRequestDispatcher("/public/head.jsp");
RequestDispatcher foot = request.getRequestDispatcher("/public/foot.jsp");

PrintWriter out = response.getWriter();
head.include(request, response);
out.write("ABC");
foot.include(request, response);
out.flush();
out.close();

include()和forword()一樣都是屬於RequestDispatcher的方法。只不過一個是用來組裝頁面,一個用來前往頁面。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言