用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>
    <%//獲取用戶名和密碼cookie,判斷cookie是否爲空,爲空的情況就是第一次登錄,跳到登錄頁面,不爲空就直接跳轉到登陸後的頁面。
        String name=null;
        String password=null;
        Cookie[] cookies=request.getCookies();
        if(cookies!=null){
            for(Cookie cookie:cookies){
                if(cookie.getName().equals("username")){
                    name=cookie.getValue();
                }
                if(cookie.getName().equals("pwd")){
                    password=cookie.getValue();
                }
            }
            if(name!=null&&password!=null){
                response.sendRedirect("LoginServlet?username="+name+"&pwd="+password);
            }
        }

    %>
    <h1>歡迎來到動物園</h1>
    <form action="<%=request.getContextPath()%>/LoginServlet" method="get">
        <p>請輸入口令:<input type="text" name="username"></p>
        <p>請輸入密碼:<input type="password" name="pwd"></p>
         <p><input type="checkbox" name="box" value="ck">自動登錄</p>
        <p><input type="submit" value="歡迎進入"></p>
    </form>
</body>
</html>

下面是servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        接收請求參數的值
        String username=request.getParameter("username");
        String password=request.getParameter("pwd");
                if(username.equals("yyy")&&password.equals("123")) {
                    //如果沒有選中自動登錄,則要輸入賬號登錄,否則就會執行cookie,實現自動登錄
                    if(request.getParameter("box")==null) {
                        request.getRequestDispatcher("SearchAllServlet").forward(request, response);
                    }else {

                    Cookie name=new Cookie("username", username);
                    Cookie pwd=new Cookie("pwd", password);
                    response.addCookie(name);
                    response.addCookie(pwd);
                    name.setMaxAge(60*60);
                    pwd.setMaxAge(60*60);
                    request.getRequestDispatcher("SearchAllServlet").forward(request, response);
                }
                }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章