YONG-MIN

[jQuery/Javascript] ID 기억하기 기능 구현

개발언어/Javascript 2017. 11. 26. 01:32

jQuery/Javascript를 이용해서 아이디를 Cookie에 저장하고 이를 활용하기 위한 기능을 구현합니다.


Login을 수행했을때 Rembember(체크박스) 여부에 따라 쿠키에 저장하고, 삭제(강제만료)시키는 기능을 구현합니다.


1. JSP Form

1
2
3
4
5
6
7
8
9
10
11
<form class="login-form" action="<c:url value='/login.do'/>" method="post">
    <h3 class="form-title font-green">Sign In</h3>         
    <input class="form-control form-control-solid placeholder-no-fix" type="text" autocomplete="off" placeholder="ID" name="user_id">
    <br>
    <input class="form-control form-control-solid placeholder-no-fix" type="password" autocomplete="off" placeholder="PASSWORD" name="user_pwd">
    <br>
    <button type="submit" class="btn green uppercase">Login</button>
    <br>
    <input type="checkbox" name="remember" value="1">Remember
    <br>
</form>

2. jQuery Scrirpt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<script>
    $(document).ready(function()
    {
        var userId = getCookie("cookieUserId");
        $("input[name='user_id']").val(userId);
         
        if($("input[name='user_id']").val() != ""){ // Cookie에 만료되지 않은 아이디가 있어 입력됬으면 체크박스가 체크되도록 표시
            $("input[name='remember']").attr("checked", true);
        }
         
        $("button[type='submit']", $('.login-form')).click(function(){ // Login Form을 Submit할 경우,
            if($("input[name='remember']").is(":checked")){ // ID 기억하기 체크시 쿠키에 저장
                var userId = $("input[name='user_id']").val();
                setCookie("cookieUserId", userId, 7); // 7일동안 쿠키 보관
            } else {
                deleteCookie("cookieUserId");
            }
        });            
    })
 
    function setCookie(cookieName, value, exdays){
        var exdate = new Date();
        exdate.setDate(exdate.getDate()+exdays);
        var cookieValue = escape(value)+((exdays==null)? "": "; expires="+exdate.toGMTString());
        document.cookie = cookieName+"="+cookieValue;
    }
    function deleteCookie(cookieName){
        var expireDate = new Date();
        expireDate.setDate(expireDate.getDate()-1);
        document.cookie = cookieName+"= "+"; expires="+expireDate.toGMTString();
    }
    function getCookie(cookieName){
        cookieName = cookieName + '=';
        var cookieData = document.cookie;
        var start = cookieData.indexOf(cookieName);
        var cookieValue = '';
        if(start != -1){
            start += cookieName.length;
            var end = cookieData.indexOf(';', start);
            if(end == -1) end = cookieData.length;
            cookieValue = cookieData.substring(start, end);
        }
        return unescape(cookieValue);
         
    }
</script>