1. 程式人生 > >Cookie的使用,自動填充使用者名稱和密碼

Cookie的使用,自動填充使用者名稱和密碼

test1.jsp

<body>
    <%
  		String name = "";
  		String word = "";
  		Cookie[] cc = request.getCookies();
  		if(cc == null || cc.length == 0){
  		
  		}else{
	  		for( Cookie c :cc){
	  			if(c.getName().equals("username")){
	  				name = c.getValue();
	  			}
	  			if(c.getName().equals("password")){
	  				word = c.getValue();
	  			}
	  		}
	  	}
  	 %>
  
    <form action="cookie/test2.jsp">
    	使用者名稱: <input type="text" name="username" value="<%=name %>"/><br/>
    	密碼:<input type="password" name="password" value="<%=word %>"/><br/>
    	<input type="submit" value="登陸"/>
    </form>
  </body>

test2.jsp
<body>
     <%
    	String username = request.getParameter("username");
    	String password = request.getParameter("password");
    	if(username.equals("zhangsan")&& password.equals("123456")){
    		Cookie c1 = new Cookie("username",username);
    		Cookie c2 = new Cookie("password",password);
    		c1.setMaxAge(60*60);
    		c2.setMaxAge(60*60);
    		response.addCookie(c1);
    		response.addCookie(c2);
    		out.print("登陸成功");    		
    	}else{
    		out.print("登陸失敗");
    	}
     %>
  </body>