對處理 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: }
沒有留言:
張貼留言