private void addUsernameCookie( String username, String firstname, String lastname, HttpServletRequest request, HttpServletResponse response) { StringBuilder un = new StringBuilder(new String(Base64.encodeBase64(username.getBytes()))); while (un.charAt(un.length() - 1) == '=') { un.deleteCharAt(un.length() - 1); } response.addCookie(createCookie(USERNAME, un.toString(), request)); StringBuilder fn = new StringBuilder(); if (!StringUtils.isBlank(firstname)) { fn.append(firstname); } fn.append(":"); if (!StringUtils.isBlank(lastname)) { fn.append(lastname); } String value = fn.toString(); fn = new StringBuilder(new String(Base64.encodeBase64(value.getBytes()))); while (fn.charAt(fn.length() - 1) == '=') { fn.deleteCharAt(fn.length() - 1); } Cookie c = createCookie(FULLNAME, fn.toString(), request); c.setMaxAge(Integer.MAX_VALUE); response.addCookie(c); }
public void login(HttpServletRequest request, HttpServletResponse response) throws IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); if (username == null) { response.sendRedirect("index.html"); return; } String sql = "SELECT id FROM curator WHERE name=" + SqlUtil.toSqlVarchar(username) + " AND passwd=PASSWORD(" + SqlUtil.toSqlVarchar(password) + ")"; String id = DBUtil.querySingle(sql); if (id == null) { response.sendRedirect("index.html"); return; } Cookie cookie = new Cookie("username", username); if (request.getParameter("remember_me") != null && request.getParameter("remember_me").equals("on")) { cookie.setMaxAge(86400 * 365); } else { cookie.setMaxAge(-1); } response.addCookie(cookie); cookie = new Cookie("userid", id); if (request.getParameter("remember_me") != null && request.getParameter("remember_me").equals("on")) { cookie.setMaxAge(86400 * 365); } else { cookie.setMaxAge(-1); } response.addCookie(cookie); }
/** * Resolve the user's current language from the cookie. * * @param request * @param response * @return * @throws Exception */ private String resolveLang(HttpServletRequest request, HttpServletResponse response) throws Exception { Cookie[] cookies = request.getCookies(); Cookie c = this.getCookie(cookies, Constants.COOKIE_NAME_LANG); if (c == null) { String defaultValue = this.getSystemConfig() .getSysParamValue( SysParams.CORE_DEFAULT_LANGUAGE, SysParams.CORE_DEFAULT_LANGUAGE_DEFVAL); if (defaultValue == null || defaultValue.equals("")) { defaultValue = Constants.DEFAULT_LANGUAGE; } c = this.createCookie(Constants.COOKIE_NAME_LANG, defaultValue, 60 * 60 * 24 * 365); response.addCookie(c); } String lang = request.getParameter(Constants.REQUEST_PARAM_LANG); if (lang == null || lang.equals("")) { lang = c.getValue(); } else { c.setMaxAge(0); c = this.createCookie(Constants.COOKIE_NAME_LANG, lang, 60 * 60 * 24 * 365); response.addCookie(c); } return lang; }
/** * Resolve the user's current theme from the cookie. * * @param request * @param response * @return * @throws Exception */ private String resolveTheme(HttpServletRequest request, HttpServletResponse response) throws Exception { Cookie[] cookies = request.getCookies(); Cookie c = this.getCookie(cookies, Constants.COOKIE_NAME_THEME); if (c == null) { String defaultValue = this.getSystemConfig() .getSysParamValue( SysParams.CORE_DEFAULT_THEME_EXTJS, SysParams.CORE_DEFAULT_THEME_EXTJS_DEFVAL); if (defaultValue == null || defaultValue.equals("")) { defaultValue = Constants.DEFAULT_THEME_EXTJS; } c = this.createCookie(Constants.COOKIE_NAME_THEME, defaultValue, 60 * 60 * 24 * 365); response.addCookie(c); } String theme = request.getParameter(Constants.REQUEST_PARAM_THEME); if (theme == null || theme.equals("")) { theme = c.getValue(); } else { c.setMaxAge(0); c = this.createCookie(Constants.COOKIE_NAME_THEME, theme, 60 * 60 * 24 * 365); response.addCookie(c); } return theme; }
/** * Handle POST request. * * @param req * @param resp * @throws javax.servlet.ServletException * @throws java.io.IOException */ @Override protected void doPost( javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp) throws javax.servlet.ServletException, java.io.IOException { // Get parameters. String city = req.getParameter(CITY_PARAMETER_COOKIE_NAME), category = req.getParameter(CATEGORY_PARAMETER_COOKIE_NAME); // Create response cookies. Cookie cookies[] = new Cookie[2]; Cookie cookie = new Cookie(CITY_PARAMETER_COOKIE_NAME, city); cookie.setMaxAge(COOKIE_MAX_AGE); resp.addCookie(cookie); cookies[0] = cookie; cookie = new Cookie(CATEGORY_PARAMETER_COOKIE_NAME, category); cookie.setMaxAge(COOKIE_MAX_AGE); resp.addCookie(cookie); cookies[1] = cookie; // Get print writer. PrintWriter writer = resp.getWriter(); // Render page. renderPage(writer, cookies); // Close print writer. writer.close(); }
@RequestMapping(value = "login", method = RequestMethod.POST) public String login( String email, String password, String saveEmail, HttpServletResponse response, HttpSession session) { response.setContentType("text/plain;charset=UTF-8"); Cookie emailCookie = null; if (saveEmail != null) { emailCookie = new Cookie("email", email); emailCookie.setMaxAge(60 * 60 * 24 * 15); response.addCookie(emailCookie); } else { emailCookie = new Cookie("email", ""); emailCookie.setMaxAge(0); } response.addCookie(emailCookie); Student student = studentService.retrieve(email, password); if (student == null) { session.invalidate(); return "/auth/LoginFail"; } session.setAttribute("loginUser", student); return "redirect:../board/list.do"; }
/** * 首页登录中添加记住我的功能 * * @param request * @param response * @throws UnsupportedEncodingException */ public static void remeberMeByCookie(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException { // 获取登录名和密码 String logonName = request.getParameter("name"); String pwd = request.getParameter("password"); // 处理cookie中存在中文字符的问题 String codeName = URLEncoder.encode(logonName, "UTF-8"); String codePwd = URLEncoder.encode(pwd, "UTF-8"); // 创建cookie Cookie nameCookie = new Cookie("name", codeName); Cookie pwdCookie = new Cookie("password", codePwd); // 设置cookie有效路径 nameCookie.setPath(request.getContextPath() + "/"); pwdCookie.setPath(request.getContextPath() + "/"); // 是否选中记住我 if (request.getParameter("remeberMe") != null && "yes".equals(request.getParameter("remeberMe"))) { // 设置cookie有效时长 nameCookie.setMaxAge(7 * 24 * 60 * 60); pwdCookie.setMaxAge(7 * 24 * 60 * 60); } else { // 清空cookie有效时长 pwdCookie.setMaxAge(0); nameCookie.setMaxAge(0); } // 将cookie存放到response中 response.addCookie(nameCookie); response.addCookie(pwdCookie); }
/* goodG2B() - use goodsource and badsink by changing the conditions on the first and second while statements */ private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; boolean local_f = false; while (true) { java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger"); /* FIX: Use a hardcoded string */ data = "foo"; break; } while (local_f) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ Logger log_bad = Logger.getLogger("local-logger"); /* get environment variable ADD */ data = System.getenv("ADD"); break; } while (true) { Cookie cookieSink = new Cookie("lang", data); /* POTENTIAL FLAW: Input not verified before inclusion in the cookie */ response.addCookie(cookieSink); break; } while (local_f) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ Cookie cookieSink = new Cookie("lang", URLEncoder.encode(data, "UTF-16")); /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */ response.addCookie(cookieSink); break; } }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("usrname"); String passwrd = request.getParameter("passwrd"); Cookie Mycookie1 = new Cookie("uname", name); Mycookie1.setMaxAge(10); response.addCookie(Mycookie1); Cookie Mycookie2 = new Cookie("pwd", passwrd); Mycookie2.setMaxAge(10); response.addCookie(Mycookie2); Cookie Mycookie3 = new Cookie("mobile", "9905216484"); Mycookie3.setMaxAge(10000); response.addCookie(Mycookie3); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML><BODY>"); out.println("<h3>Cookie Initialized</h3>"); out.println("<a href='index.html'>Go back to home page</a>"); out.println( "<a href='http://localhost:8080/SessionDemoHttp/CookieCheckingServlet'>check cookie</a>"); out.println("</BODY></HTML>"); }
public void json(RequestInfoHttp reqInfo, String content, List<Cookie> cookies) throws IOException { if (cookies.size() > 0) { HttpServletResponse res = reqInfo.getRes(); Cookie[] exists = reqInfo.getReq().getCookies(); for (Cookie ck : cookies) { Cookie found = null; for (Cookie eck : exists) { if (eck.getName().equals(ck.getName())) { found = eck; break; } } if (found == null) { res.addCookie(ck); } else { found.setValue(ck.getValue()); found.setMaxAge(ck.getMaxAge()); found.setPath(ck.getPath()); res.addCookie(found); } } } json(reqInfo, content); }
@SuppressWarnings("unchecked") public void setAttribute( HttpServletRequest request, HttpServletResponse response, String name, Serializable value) { Map<String, Serializable> session = (Map<String, Serializable>) request.getAttribute(CURRENT_SESSION); String root; if (session == null) { root = RequestUtils.getRequestedSessionId(request); if (root != null && root.length() == 32) { session = sessionCache.getSession(root); } if (session == null) { session = new HashMap<String, Serializable>(); do { root = sessionIdGenerator.get(); } while (sessionCache.exist(root)); response.addCookie(createCookie(request, root)); } request.setAttribute(CURRENT_SESSION, session); request.setAttribute(CURRENT_SESSION_ID, root); } else { root = (String) request.getAttribute(CURRENT_SESSION_ID); if (root == null) { do { root = sessionIdGenerator.get(); } while (sessionCache.exist(root)); response.addCookie(createCookie(request, root)); request.setAttribute(CURRENT_SESSION_ID, root); } } session.put(name, value); sessionCache.setSession(root, session, sessionTimeout); }
/* goodG2B1() - use goodsource and badsink by changing first 5==5 to 5!=5 */ private void goodG2B1(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; /* INCIDENTAL: CWE 570 Statement is Always False */ if (5 != 5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ Logger log_bad = Logger.getLogger("local-logger"); /* read parameter from cookie */ Cookie cookieSources[] = request.getCookies(); if (cookieSources != null) { data = cookieSources[0].getValue(); } else { data = null; } } else { java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger"); /* FIX: Use a hardcoded string */ data = "foo"; } /* INCIDENTAL: CWE 571 Statement is Always True */ if (5 == 5) { Cookie cookieSink = new Cookie("lang", data); /* POTENTIAL FLAW: Input not verified before inclusion in the cookie */ response.addCookie(cookieSink); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ Cookie cookieSink = new Cookie("lang", URLEncoder.encode(data, "UTF-16")); /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */ response.addCookie(cookieSink); } }
public static void setUserCookie(HttpServletResponse response, String email, String password) { Cookie cookie = new Cookie("appsaradev_us_email", email); Cookie cookie2 = new Cookie("appsaradev_us_password", password); cookie.setMaxAge(3600 * 24 * 30); cookie2.setMaxAge(3600 * 24 * 30); response.addCookie(cookie); response.addCookie(cookie2); }
/* * (non-Javadoc) * * @see * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest * , javax.servlet.http.HttpServletResponse) */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { log.info("GET got parameters: " + req.getParameterMap()); log.info("HTTP Session: " + req.getSession().getAttributeNames()); HttpSession httpsession = req.getSession(); try { OAuth2Provider provider = OAuth2Provider.valueOf((String) httpsession.getAttribute("oauth.service")); log.info("Got provider: " + provider); String oauthVerifier = ""; Token requestToken = null; Token accessToken = new Token("", provider.getSecret()); OAuthService service = provider.getOAuthService(); if (provider.getApi() instanceof DefaultApi20) { oauthVerifier = req.getParameter("code"); log.info("got OAuth 2.0 authorization code: " + oauthVerifier); } else if (provider.getApi() instanceof DefaultApi10a) { oauthVerifier = req.getParameter("oauth_verifier"); log.info("got OAuth 1.0a verifier: " + oauthVerifier); requestToken = req.getParameter("oauth_token") != null ? new Token((String) req.getParameter("oauth_token"), provider.getSecret()) : (Token) httpsession.getAttribute("oauth.requestToken"); } Verifier verifier = new Verifier(oauthVerifier); accessToken = service.getAccessToken(requestToken, verifier); log.info( "Got a OAuth access token: " + accessToken.getToken() + ", " + accessToken.getSecret()); Cookie accessTokenCookie = new Cookie("oauth.accessToken", accessToken.getToken()); accessTokenCookie.setMaxAge(14 * 24 * 60 * 60); accessTokenCookie.setPath("/"); resp.addCookie(accessTokenCookie); Cookie serviceCookie = new Cookie("oauth.service", provider.toString()); serviceCookie.setPath("/"); serviceCookie.setMaxAge(14 * 24 * 60 * 60); resp.addCookie(serviceCookie); Cookie secretCookie = new Cookie("oauth.secret", accessToken.getSecret()); secretCookie.setPath("/"); secretCookie.setMaxAge(14 * 24 * 60 * 60); resp.addCookie(secretCookie); resp.sendRedirect((String) req.getSession().getAttribute("http.referer")); } catch (Exception e) { log.log(Level.WARNING, e.getLocalizedMessage(), e); } }
@RequestMapping("/login.doAction") public String login(HttpServletRequest request, HttpServletResponse response) { String dlmc = request.getParameter("dlmc"); String password = request.getParameter("mm"); Login login = new Login(); /*if(!login.valiNum()){ request.setAttribute("ifdl", "true"); request.setAttribute("warning", "系统注册未成功"); return "/login.jsp"; }*/ String login_redirect = ""; boolean login_cookie = false; try { login_redirect = SysPara.getValue("login_redirect"); } catch (Exception e) { login_redirect = "/login.jsp"; } request.setAttribute("ifdl", "true"); if ("".equals(dlmc) || dlmc == null) { dlmc = login.getCookieValue(request, "com.ashburz_username"); password = login.getCookieValue(request, "com.ashburz_password"); if ("".equals(password) || password == null) { request.setAttribute("dlmc", dlmc); return login_redirect; } Des des = new Des(); password = des.getDesString(password); login_cookie = true; } String mainpage_url = (new StringBuilder("main.jsp?guid=")).append(Guid.get()).toString(); String yhid = ""; String isUSBKey = request.getParameter("isUSBKey"); String plain_pass = password; password = Md5.getMd5(password); if (login.validate(dlmc, password)) { yhid = login.getYhid(dlmc); if (!login_cookie) { Cookie cookie_username = new Cookie("com.ashburz_username", dlmc); cookie_username.setMaxAge(0x1e13380); response.addCookie(cookie_username); if ("1".equals(request.getParameter("mem_pass"))) { Cookie cookie_pass = new Cookie("com.ashburz_password", (new Des()).getEncString(plain_pass)); cookie_pass.setMaxAge(0x1e13380); response.addCookie(cookie_pass); } } if (login_cookie) login.resetLoginInfo(response, dlmc, yhid); else login.setLoginInfo(request, response, login, yhid, dlmc); return mainpage_url; } else { request.setAttribute("warning", "用户名或密码错误!!"); return login_redirect; } }
public void deleteRememberMeCookies(HttpServletResponse response) { Cookie tokenCookie = new Cookie(REMEMBER_ME_TOKEN, ""); tokenCookie.setPath("/"); tokenCookie.setMaxAge(0); response.addCookie(tokenCookie); Cookie rememberMeCookie = new Cookie(REMEMBER_ME_COOKIE, ""); rememberMeCookie.setPath("/"); rememberMeCookie.setMaxAge(0); response.addCookie(rememberMeCookie); }
public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException { Cookie cookie = HttpUtil.getCookie("userid", request); if (cookie == null) cookie = new Cookie("userid", ""); cookie.setMaxAge(0); response.addCookie(cookie); cookie = HttpUtil.getCookie("username", request); if (cookie == null) cookie = new Cookie("username", ""); cookie.setMaxAge(0); response.addCookie(cookie); }
/* goodG2B2() - use goodsource and badsink by reversing statements in first if */ private void goodG2B2(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; /* INCIDENTAL: CWE 571 Statement is Always True */ if (private_final_t) { java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger"); /* FIX: Use a hardcoded string */ data = "foo"; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ Logger log_bad = Logger.getLogger("local-logger"); data = ""; /* init data */ /* read user input from console with readLine*/ BufferedReader buffread = null; InputStreamReader instrread = null; try { instrread = new InputStreamReader(System.in); buffread = new BufferedReader(instrread); data = buffread.readLine(); } catch (IOException ioe) { log_bad.warning("Error with stream reading"); } finally { /* clean up stream reading objects */ try { if (buffread != null) { buffread.close(); } } catch (IOException ioe) { log_bad.warning("Error closing buffread"); } finally { try { if (instrread != null) { instrread.close(); } } catch (IOException ioe) { log_bad.warning("Error closing instrread"); } } } } /* INCIDENTAL: CWE 571 Statement is Always True */ if (private_final_t) { Cookie cookieSink = new Cookie("lang", data); /* POTENTIAL FLAW: Input not verified before inclusion in the cookie */ response.addCookie(cookieSink); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ Cookie cookieSink = new Cookie("lang", URLEncoder.encode(data, "UTF-16")); /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */ response.addCookie(cookieSink); } }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); String exitParam = req.getParameter("exit"); String deleteParam = req.getParameter("delete"); String settingsParam = req.getParameter("settings"); if ("settings".equals(settingsParam)) { resp.sendRedirect("/profileSettings"); return; } if ("exit".equals(exitParam)) { // обнуляем куку Cookie[] cookies = req.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("remember")) { cookie.setMaxAge(0); cookie.setValue(null); resp.addCookie(cookie); break; } } } session.setAttribute("user_a", null); resp.sendRedirect("/login"); } if ("delete".equals(deleteParam)) { // обнуляем куку Cookie[] cookies = req.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("remember")) { cookie.setMaxAge(0); cookie.setValue(null); resp.addCookie(cookie); break; } } } try { UserRepository.deleteUser((User) session.getAttribute("user_a")); } catch (SQLException e) { req.setAttribute("message", "Some problems with server"); resp.sendRedirect("/profile"); e.printStackTrace(); } session.setAttribute("user_a", null); resp.sendRedirect("/welcome"); } }
/* goodB2G() - use badsource and goodsink */ public void goodB2G_sink(String data, HttpServletRequest request, HttpServletResponse response) throws Throwable { String prefix = "Tru3ly 0b$scUre"; MessageDigest hash = MessageDigest.getInstance("SHA512"); /* FIX: credentials hashed prior to setting in cookie */ byte[] hashv = hash.digest((prefix + data).getBytes()); response.addCookie(new Cookie("auth", IO.toHex(hashv))); }
private void deleteCookies(HttpServletRequest request, HttpServletResponse response) { Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals("JSESSIONID")) { Cookie sessionCookie = new Cookie("JSESSIONID", null); sessionCookie.setPath(request.getContextPath()); sessionCookie.setMaxAge(0); response.addCookie(sessionCookie); } cookie.setMaxAge(0); response.addCookie(cookie); } }
@Override public void call(HttpServletRequest req, HttpServletResponse res) throws IOException { super.call(req, res); javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("test", "test"); cookie.setDomain(".localhost"); cookie.setMaxAge(360); res.addCookie(cookie); cookie = new javax.servlet.http.Cookie("test2", "test2"); cookie.setDomain(".localhost"); res.addCookie(cookie); }
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { Cookie c = new Cookie("Adminname", null); c.setMaxAge(0); Cookie student = new Cookie("Studentname", null); student.setMaxAge(0); Cookie teacher = new Cookie("Teachername", null); teacher.setMaxAge(0); resp.addCookie(c); resp.addCookie(student); resp.addCookie(teacher); resp.sendRedirect("/login.jsp"); }
public void writeCookie( HttpServletRequest servletRequest, HttpServletResponse servletResponse, com.hundsun.jresplus.web.nosession.cookie.Cookie cookie) { int startNum = 0; if (cookie.getValue() != null) { if (cookie.getValue().length() > maxLength * maxCount) { log.error( "Cookie store full! cookie[" + cookie.getName() + "] will be LOST! the cookies length=" + cookie.getValue().length() + ", and the config maxlength[maxLength * maxCount]=" + maxLength * maxCount); return; } if (cookie.getValue().length() + cookie.getName().length() > maxLength) { for (int beginOffset = 0, i = 1; beginOffset < cookie.getValue().length(); beginOffset += (maxLength - cookie.getName().length()), i++) { int endOffset = Math.min( beginOffset + (maxLength - cookie.getName().length()), cookie.getValue().length()); com.hundsun.jresplus.web.nosession.cookie.Cookie harpCookie = new com.hundsun.jresplus.web.nosession.cookie.Cookie( cookie.getName() + startNum, cookie.getValue().substring(beginOffset, endOffset), cookie.isHttpOnly(), cookie.getMaxAge(), cookie.getPath(), cookie.getDomain()); servletResponse.addCookie(harpCookie); startNum = i; } } else { servletResponse.addCookie(cookie); } } else { startNum = -1; } clearGarbage( servletRequest, servletResponse, cookie.getName(), startNum, cookie.getPath(), cookie.getDomain()); }
public UISearchBasisPortlet() throws Exception { HttpServletResponse response = Util.getPortalRequestContext().getResponse(); String url[] = Util.getPortalRequestContext().getRequestURI().split("BO:"); String nameBO[] = url[1].split("/"); Cookie cookie = new Cookie("dayCheck", "No"); response.addCookie(cookie); cookie = new Cookie("boName", nameBO[0]); response.addCookie(cookie); addChild(UISimpleSearchForm.class, null, "simpleSearch"); addChild(UIAdvancedSearchForm.class, null, "advancedSearch"); addChild(UIResultForm.class, null, "Result"); setRenderedChild("simpleSearch"); }
@RequestMapping(value = "/admin/login", method = RequestMethod.POST) public String logIn( @RequestParam(value = "accountName", required = false) String account, @RequestParam(value = "accPassword", required = false) String password, HttpServletResponse response) { if (account == null || password == null) { account = "new value"; password = "******"; } isLogin = true; response.addCookie(new Cookie("login", account)); response.addCookie(new Cookie("password", password)); return "redirect:/admin"; }
private void addCookie(ExternalContext extContext, Flash flash) { // Do not update the cookie if redirect after post if (flash.isRedirect()) { return; } String thisRequestSequenceString = null; HttpServletResponse servletResponse = null; // PortletRequest portletRequest = null; Object thisRequestSequenceStringObj, response = extContext.getResponse(); thisRequestSequenceStringObj = extContext.getRequestMap().get(Constants.FLASH_THIS_REQUEST_ATTRIBUTE_NAME); if (null == thisRequestSequenceStringObj) { return; } thisRequestSequenceString = thisRequestSequenceStringObj.toString(); if (response instanceof HttpServletResponse) { servletResponse = (HttpServletResponse) response; Cookie cookie = new Cookie(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME, thisRequestSequenceString); cookie.setMaxAge(-1); servletResponse.addCookie(cookie); } else { /** * *** portletRequest = (PortletRequest) request; // You can't add a cookie in portlet. // * http://wiki.java.net/bin/view/Portlet/JSR168FAQ#How_can_I_set_retrieve_a_cookie * portletRequest.getPortletSession().setAttribute(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME, * thisRequestSequenceString, PortletSession.PORTLET_SCOPE); ******* */ } }
private void addCookie(String cookieContent, HttpServletResponse response) { Cookie cookie = new Cookie(CookieSessionHandler.session, cookieContent); cookie.setSecure(SparkBase.isSecure()); cookie.setHttpOnly(true); cookie.setMaxAge(-1); response.addCookie(cookie); }
/** * Gets user email address, first and last name, puts them into a User object, puts the Object * user into session scope, adds a Cookie called emailCookie with the email address as its value, * stores the away into a EmailList.txt file that is store in openshift in OPENSHIFT_DATA_DIR * folder and locally under WEB-INF. * * @param request provides parameters for user information * @param response add the cookie to the response * @return String representing URL to go to next */ private String registerUser(HttpServletRequest request, HttpServletResponse response) { // get the user data String email = request.getParameter("email"); String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); // store the data in a User object User user = new User(); user.setEmail(email); user.setFirstName(firstName); user.setLastName(lastName); // write the User object to a file // ServletContext sc = getServletContext(); // String path = sc.getRealPath("/WEB-INF/EmailList.txt"); String path = this.getActualFile(); System.out.println("Path: " + path); UserIO.add(user, path); // store the User object as a session attribute HttpSession session = request.getSession(); session.setAttribute("user", user); // add a cookie that stores the user's email to browser Cookie c = new Cookie("emailCookie", email); c.setMaxAge(60 * 60 * 24 * 365 * 2); // set age to 2 years c.setPath("/"); // allow entire app to access it response.addCookie(c); // create and return a URL for the appropriate Download page String productCode = (String) session.getAttribute("productCode"); String url = "/" + productCode + "_download.jsp"; return url; }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { Cookie[] cookies = request.getCookies(); int userID = -1; boolean newUser = false; // determine whether we've seen this user before if (cookies != null) { for (Cookie c : cookies) { if (c.getName().equals("userID")) { userID = Integer.parseInt(c.getValue()); logger.log(Level.INFO, "Existing user: "******"userID", String.valueOf(userID)); response.addCookie(c); logger.log(Level.INFO, "New user: "******"text/html"); response.setStatus(HttpServletResponse.SC_OK); PrintWriter out = response.getWriter(); String title = "Cookie Servlet"; String bootstrapHeader = "<!DOCTYPE html>" + "<html lang=\"en\">\n" + " <head>\n" + " <title>" + title + "</title>\n" + " <meta charset=\"utf-8\">\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n" + " <link rel=\"stylesheet\" href=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\">\n" + " <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\n" + " <script src=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js\"></script>\n" + " </head>\n"; String body = " <body>\n" + " <div class=\"container\">\n" + " <p>Hello, " + (newUser ? "new" : "existing") + " user!</p>\n" + " </div>\n" + " </body>\n"; String footer = "</html>"; String page = bootstrapHeader + body + footer; out.println(page); }