记住用户名密码(cookie的操作)

项目中要用到 记住用户名 密码

 

我用cookie实现

 

if (token != null) {
				if ("1".equals(remember)) {
					/**
					 * 查看是否 存在了 保存用户名 的cookie
					 */
					boolean flags = false;
					Cookie[] cookies = request.getCookies();
					if (cookies != null) {
						for (int i = 0; i < cookies.length; i++) {
							Cookie c = cookies[i];
							if (c.getName().equalsIgnoreCase("username")) {
								String uName = c.getValue();
								if (userName.equals(uName)) {
									break;
								} else {
									saveCookie(response, loginForm);
									flags = true;
								}
							}
						}
					} else {
						saveCookie(response, loginForm);
						flags = true;
					}
					if (!flags) {
						saveCookie(response, loginForm);
					}
				} else {  //没有选中 复选框 要清除cookie
					Cookie[] cookies = request.getCookies();
					for (int i = 0; i < cookies.length; i++) {
						Cookie c = cookies[i];
						if (c.getName().equalsIgnoreCase("username")) {
							String uName = c.getValue();
							if (userName.equals(uName)) {
								Cookie userCookie = new Cookie("username", null);
								userCookie.setMaxAge(0);
								userCookie.setPath("/VastisAgent/");
								response.addCookie(userCookie);
							}
						}
					}
				}
			}

 

	private void saveCookie(HttpServletResponse response, LoginForm loginForm) {
		Cookie userCookie = new Cookie("username", loginForm.getWorkCode());
		Cookie passwordCookie = new
		Cookie("password",loginForm.getPassword());
		userCookie.setPath("/workbase/"); // cookie路径问题
		 passwordCookie.setPath("/workbase/");
		userCookie.setMaxAge(7 * 24 * 60 * 60); // cookie 的有效时间
		 passwordCookie.setMaxAge(7*24*60*60);
		response.addCookie(userCookie);
		 response.addCookie(passwordCookie);
	}

 

 <%             页面中的一段代码
                    String username = ""; 
	    String password = ""; 
	Cookie[] cookies = request.getCookies(); 
	if(cookies!=null){ 
	
	    for (int i = 0; i < cookies.length; i++) { 
	       Cookie c = cookies[i];     
	       if(c.getName().equalsIgnoreCase("username")) { 
	          username = c.getValue(); 
	        } 
	        else if(c.getName().equalsIgnoreCase("password")) 
	       { 
	          password = c.getValue(); 
	       } 
	    } 
	  } 

 %>
<input type="checkbox" name="remember" value="1">记住用户名密码</td>

 

你可能感兴趣的:(C++,c,C#)