Cookie实现记住密码的功能

一、什么是Cookie

cookie是一种WEB服务器通过浏览器在访问者的硬盘上存储信息的手段。Cookie的目的就是为用户带来方便,为网站带来增值。虽然有着许多误传,事实上Cookie并不会造成严重的安全威胁。Cookie永远不会以任何方式执行,因此也不会带来病毒或攻击你的系统。另外,由于浏览器一般只允许存放300个Cookie,每个站点最多存放20个Cookie,每个Cookie的大小限制为4KB,因此Cookie不会塞满你的硬盘。

例如,当我们第一次访问网站输入用户名密码时,可以选择让系统记住用户名密码,下次就不用重新输入了,这就是典型的Cookie的应用。

二、Cookie带来的好处:

cookies给网站和用户带来的好处非常多:

  • 1. Cookie能使站点跟踪特定访问者的访问次数、最后访问时间等
  • 2. Cookie能告诉在线广告商广告被点击的次数,从而可以更精确的投放广告
  • 3. Cookie有效期限未到时,Cookie能使用户在不键入密码和用户名的情况下进入曾经浏览过的一些站点
  • 4. Cookie能帮助站点统计用户个人资料以实现各种各样的个性化服务在JSP中,我们也可以使用Cookie,来编写一些功能强大的应用程序。

有些浏览器可以禁用Cookie,所以不能使用Cookie来完成核心的业务。

 三、Cookie类的主要方法:

int getMaxAge() 返回Cookie过期之前的最大时间,以秒计算。
int setMaxAge() 设置Cookie过期时间,以秒计算。 
String getName() 返回Cookie的名字 
String getValue() 返回Cookie的值。
void setValue(String newValue) cookie创建后设置一个新的值。

四、代码实现记住密码登录功能:  

 前端页面代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
 <head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Excel数据上传系统-登录</title>
	<link href="${pageContext.request.contextPath}/content/css/page/login.css" rel="stylesheet" type="text/css" />
 </head>
 
 <body>
 	<div class="second_body">
    	<form data-bind="submit:loginClick">
        	<div class="logo"></div>
            <div class="title-zh">Excel数据上传系统</div>
            <div class="title-en" style="">Excel Data Upload System</div>
            <div class="message" data-bind="html:message"></div>
            <table border="0" style="width:300px;">
            	<tr>
                	<td style="white-space:nowrap; padding-bottom: 5px;width:55px;">用户名:</td>
                    <td colspan="2"><input type="text" id="userCode" class="login" data-bind="value:form.userCode" /></td>
                </tr>
                <tr>
                    <td class="lable" style="white-space:nowrap; letter-spacing: 0.5em; vertical-align: middle">密码:</td>
                    <td colspan="2"><input type="password" id="password" class="login" data-bind="value:form.password" /></td>
                </tr>
                <tr>
                    <td></td>
                    <td colspan="2"><input type="checkbox" data-bind="checked:form.remember" /><span>系统记住我</span></td>
                </tr>
                <tr>
                    <td colspan="3" style="text-align:center">
                        <input type="submit" value="登录" class="login_button" />
                        <input type="button" value="重置" class="reset_botton" data-bind="click:resetClick" />
                    </td>
                </tr>
            </table>
        </form>
    </div>
        
 	<script type="text/javascript" src="${pageContext.request.contextPath}/content/js/jquery/jquery-1.8.1.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/ligerUI/lib/jquery.cookie.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/content/js/core/utils.js"></script>
	<script type="text/javascript" src="${pageContext.request.contextPath}/content/js/core/common.js"></script> 
    <script type="text/javascript" src="${pageContext.request.contextPath}/content/js/core/knockout-3.4.1.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/login.js"></script>
 	<script type="text/javascript">
         $(function () {
             ko.applyBindings(new viewModel());
         });
     </script>
 </body>
 
</html>       

 后台业务处理代码:

 

//登录查询
	@RequestMapping(value={"/doLogin"},method ={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public AjaxJson doLogin(@RequestBody Map<String, String> json,HttpServletRequest request,HttpServletResponse response){
		AjaxJson resutl = new AjaxJson();
		String loginName = json.get("userCode");
	    String password = json.get("password");
	    //用户名密码检查
        if ( StringUtils.isBlank(loginName) || StringUtils.isBlank(password)){
        	resutl.setSuccess(false);
			resutl.setMsg("用户名或密码不能为空!");
        }else {
        	String passwordEncode = MD5Util.MD5Encode(password, "utf-8");
     		ExcelUser user = null;
     		user = loginService.findUserByLoginName(loginName);
     		if(user == null) {
     			resutl.setSuccess(false);
     			resutl.setMsg("该用户名不存在!");
     		}else {
 				user = loginService.findUserByNameAndPwd(loginName, passwordEncode);
 	     		if(user == null) {
 	     			resutl.setSuccess(false);
 	     			resutl.setMsg("密码输入错误,请重新输入");
 	     		}else {
 	     			if(user.getUser_status()!=null && user.getUser_status().equals("0")) {
 	     				resutl.setSuccess(false);
 	         			resutl.setMsg("该用户名已被禁用,请联系管理员!");
 	     			}else {
 	     				resutl.setObj(user);
     	     			Map<String, String> map = new HashMap<>();
     					map.put("userCode", loginName);
     					map.put("userName", user.getUser_name());
     					map.put("isOauthUser", "0");
     					JSONObject jsonObject=JSONObject.fromObject(map);
     					System.out.println(jsonObject.toString());
     					request.getSession().setAttribute("LOGIN_USER",jsonObject);
     					//创建两个Cookie对象
     		                   Cookie nameCookie = new Cookie("userCode", loginName);
     		                   Cookie pwdCookie = new Cookie("password", password);
     					if("true".equals(String.valueOf(json.get("remember")))){
     						//设置Cookie的有效期为10天
     						nameCookie.setMaxAge(60 * 60 * 24 * 10);
     						pwdCookie.setMaxAge(60 * 60 * 24 * 10);
     						response.addCookie(nameCookie);
          		                   response.addCookie(pwdCookie);
     			        }else {
     			        	//使其cookie失效
     			        	nameCookie.setMaxAge(0);
     					pwdCookie.setMaxAge(0);
     					response.addCookie(nameCookie);
          		                response.addCookie(pwdCookie);
     			        }
 	     			}
 	     			
 	     		}
     		}
     		
        }
		return resutl;
	}

 当登录成功之后,再退出的话,就无需要再输入用户名和密码了! 

如果这篇文章对您有所帮助,请随便打赏一下作为鼓励,我会再接再厉的!!!

猜你喜欢

转载自www.cnblogs.com/zhangliang88/p/11202618.html