顯示具有 JSP 標籤的文章。 顯示所有文章
顯示具有 JSP 標籤的文章。 顯示所有文章

2015年11月9日 星期一

Cookie Helper


對處理 Cookie 很煩嗎? 試試這個 Cookie Helper.
原作者: Vasil Lukach, 2014/01/05
Source: http://stackoverflow.com/questions/20934016/how-to-add-cookie-in-jsf

1:  public class CookieHelper {  
2:   public void setCookie(String name, String value, int expiry) {  
3:    FacesContext facesContext = FacesContext.getCurrentInstance();  
4:    HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();  
5:    Cookie cookie = null;  
6:    Cookie[] userCookies = request.getCookies();  
7:    if (userCookies != null && userCookies.length > 0 ) {  
8:      for (int i = 0; i < userCookies.length; i++) {  
9:        if (userCookies[i].getName().equals(name)) {  
10:          cookie = userCookies[i];  
11:          break;  
12:        }  
13:      }  
14:    }  
15:    if (cookie != null) {  
16:      cookie.setValue(value);  
17:    } else {  
18:      cookie = new Cookie(name, value);  
19:      cookie.setPath(request.getContextPath());  
20:    }  
21:    cookie.setMaxAge(expiry);  
22:    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();  
23:    response.addCookie(cookie);  
24:   }  
25:   public Cookie getCookie(String name) {  
26:    FacesContext facesContext = FacesContext.getCurrentInstance();  
27:    HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();  
28:    Cookie cookie = null;  
29:    Cookie[] userCookies = request.getCookies();  
30:    if (userCookies != null && userCookies.length > 0 ) {  
31:      for (int i = 0; i < userCookies.length; i++) {  
32:        if (userCookies[i].getName().equals(name)) {  
33:          cookie = userCookies[i];  
34:          return cookie;  
35:        }  
36:      }  
37:    }  
38:    return null;  
39:   }  
40:  }  

2011年2月13日 星期日

在 Netbean+GlassFish 下開發 Sessiong Bean 及其 client 程式

本文件介紹如何使用 Netbeans 及 Glassfish 開發 Session Bean 及其 client 程式。內容包括:
  1.  建立並佈署 Session Bean (EJB 3.1)
  2.  在 Servlet 中使用 Glassfish 上的 Session Bean
  3.   在 JSP 中使用 Glassfish 上的 Session Bean
  4.  在 Stand-along application 中使用 Glassfish 上的 Session Bean
PDF 檔下載

2011年2月7日 星期一

網頁自動更新使用 meta refresh 指令

要讓 browser 能自動更新, 或者自動轉到另一個網頁使用指令:

<meta http-equiv="refresh" content="5" />

為什麼要用 meta refresh 而不用 HttpServletRequest.sendRedirect() 方法呢? 因為 sendRedirect() 方法在重新導向時, 無法將 cookie 傳回伺服器端.

Reference:

* Meta refresh
* p174, 精通JAVA WEB程式設計, 葉雅美 - 維科出版社 ,2004-10-01 出版

將字串編碼成 html 格式

在寫 servlets/JSPs 時, 常要要輸出符合 html 格式的字串, 例如:

"bread" & "butter"  要變成 "bread" & "butter"


有現成的套件可以做此轉換.

org.apache.commons.lang.StringEscapeUtils 這個類別提供了:

public static String escapeHtml(String str)

可以將字串轉成 html 的格式.

Reference:
* Apache Commons
* escapeHtml()
* Robin's Tech Tips