SpringMVC框架利用cookie实现记住密码功能

登录时可以利用cookie来实现记住密码功能,但是此功能有一定的弊端,因为用户名与密码存放在cookie中,不安全,由于原生的js获取cookie后需要对字符串进行切割,比较麻烦,所以这里使用jquery的cookie

前端页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户登录</title>
<script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script  type="text/javascript" src="js/jquery.cookie.js"></script>
<script type="text/javascript">
$(function(){
// 	编写函数,在按键升起时触发,监测cookie中是否存在该用户名的key,如果有,则把value赋值给密码框
	  $("#yhm").keyup(function(){	  
		   var yhm = $("#yhm").val();	  
		   if(yhm != ""){
			   var mima = $.cookie(yhm);	 
			   if(mima!=null){
				   $("#mima").val(mima);
				   $("#jizhumima").attr("checked",true);
			   }
		   }
	   
	   })
}
)
</script>
</head>

<body>

<form action="cookie.do" method="post">
  用户名:<input type="text" name="uname" id="yhm"><br>
  密码:<input type="password" name="psw" id="mima"><br>
  <input type="checkbox" name="state" value="1" id="jizhumima">记住密码 
  <input type="submit" value="登录">
</form>
${ts}<br>
</body>
</html>

后台java

@Controller
public class CookieController {
	@RequestMapping("/cookie")
    public String creatCookie(@RequestParam(required=false,defaultValue="0")int state,User user,HttpServletResponse response,HttpServletRequest request,ModelMap map){
    	if(user.getUname().equals("aaa") && user.getPsw().equals("aaa")){
    		//如果选择记住密码,则创建cookie,并将账号密码注入cookie
    		if(state==1){
    		//创建cookie对象
        		Cookie ck = new Cookie(user.getUname(), user.getPsw());
        			//设置Cookie有效时间,单位为妙
        		ck.setMaxAge(60*60*24);
        		  //设置Cookie的有效范围,/为全部路径
        		ck.setPath("/");
        		response.addCookie(ck);	
        	}else{
        	//如果没有选中记住密码,则将已记住密码的cookie失效.即有效时间设为0
        		Cookie[] cookies = request.getCookies();
        		for (Cookie cookie : cookies) {
    				if(cookie.getName().equals(user.getUname())){
    					cookie.setMaxAge(0);
    					cookie.setPath("/");
    					response.addCookie(cookie);
    				}
    			}
        	}
    		return "success";
    	}else {
    		map.put("ts", "用户名或密码错误");
			return "loginUser";
		}	
    }
  }

猜你喜欢

转载自blog.csdn.net/qq_36677358/article/details/84565587
今日推荐