1. 程式人生 > >Cookie實現一個簡單的“記住使用者名稱”的功能

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>Insert title here</title>
</head>
<body> 
     <!--全域性變數,未賦值時為null  -->
     <%!  String userName;%>
      <%
         
      Cookie[] cookie = request.getCookies();
         for(Cookie coo:cookie){
             if(coo.getName().equals("remName")){ 
                userName = coo.getValue();               
             }             
         }
      %> 
      <form action="check.jsp" method="post">
                                    使用者名稱:<input type="text" id="dog" name="uname" value="<%=userName==null?"":userName%>"><br/>
                                    密碼:<input type="password"><br/>
                                              <input type="submit" value="提交" id="ah">

    </form>
</body>
</html>

------------------------------------------------------------------------------------------------------------------

<%@ 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>Insert title here</title>
</head>
<body>
       <% 
            request.setCharacterEncoding("UTF-8");
            String username = request.getParameter("uname");
            Cookie cookie = new Cookie("remName",username);
            //一分鐘後cookie失效
            cookie.setMaxAge(60);
            response.addCookie(cookie);
       %>
</body>
</html>

第一次訪問時,先輸入使用者名稱:zs及密碼並點選登入,之後再次訪問登陸頁面,就會發現頁面已經儲存了使用者名稱

 

再次訪問登陸頁面時,使用者名稱已經存在了