본문 바로가기

(Before)BitSchool

2014/06/30 AjaxLogin

반응형

Ajax를 이용한 로그인을 만들어 보자.



ajaxForm.jsp


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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
    <%@ page import="kr.co.bit.simplesite.vo.UserInfo" %>
<!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=EUC-KR">
<title>Login Page</title>
<script type="text/javascript">
    function getXMLHttpRequest() {
        if (window.ActiveXObject) {
            try {
                return new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e2) {
                    return null;
                }
            }
        } else if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else {
            return null;
        }
    } 
 
    var xmlHttpRequest = getXMLHttpRequest();
 
    function responseAjax() {
        if (xmlHttpRequest.readyState == 4) {
            if (xmlHttpRequest.status == 200) {
                var sendButtonElement = document.getElementById("send_button");
                sendButtonElement.removeAttribute("disabled");
                var spinnerElement = document.getElementById("spinner");
                spinnerElement.setAttribute("style", "display:none");
 
                //{"isLogin",true} or {"isLgoin",false}
                
                eval("var jsonObj = " + xmlHttpRequest.responseText);
 
                if(jsonObj.isLogin == true){
                    var loginForm = document.getElementById("loginForm");
                    loginForm.setAttribute("style", "display:none");
                    
                    var title = document.getElementById("title");
                    title.innerHTML = "로그인에 성공하였습니다.";
                }else{
                    alert("로그인에 실패하였습니다!");
                }            
            }
        }
    }
 
    
    function sendRequest() {
        var sendButtonElement = document.getElementById("send_button");
        sendButtonElement.setAttribute("disabled", true);
        var spinnerElement = document.getElementById("spinner");
        spinnerElement.setAttribute("style", "display:inline");
 
        var userId = document.getElementById("userId").value;
        var password = document.getElementById("password").value;
        
        var url = "<%=request.getContextPath()%>/login/ajaxLogin.do?userId=" + userId + "&password=" + password;
 
        /* var echoMessage = document.getElementById("echo_message").value;
        
        url += "?data=" + encodeURIComponent(echoMessage); */
        
        //validation check....생략함.
 
        xmlHttpRequest.open("GET", url, true);
        xmlHttpRequest.onreadystatechange = responseAjax;
        xmlHttpRequest.send(null);
    }
    
    
</script>
</head>
<body>
<%
    UserInfo userInfo = (UserInfo)session.getAttribute("UserInfo");
    if(userInfo==null){
%>
    <h1 id="title">비트 시스템 로그인 </h1>
    <form id="loginForm">
        <table cellspacing="5" border="0">
            <tr>
                <td align="right">아이디</td>
                <td><input type="text" id="userId" /></td>
            </tr>
            <tr>
                <td align="right">비밀번호</td>
                <td><input type="password" id="password" /></td>
            </tr> 
            
            <tr>
                <td align="right" colspan="2">
                <input id="send_button" type="button" value="로그인" onClick="sendRequest()"/>
                <img id="spinner" src="<%=request.getContextPath()%>/images/ajaxSpinner.gif" 
                    width="15px" height="15px" style="display:none"/>
                </td>
            </tr>
        </table>
    </form>
    
    <p><a href="<%=request.getContextPath() %>/user/form.do">회원가입</a></p>
<%
}else{
%>
    <h1><%=userInfo.getName() %>님 로그인 하셨습니다.</h1>
    <p><a href="<%=request.getContextPath() %>/login/logout.do">로그아웃</a></p>
<%} %>       
</body>
</html>

 



LoginController.java


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
public ModelAndView loginUsingAjax(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
 
        String userId = request.getParameter("userId");
        String password = request.getParameter("password");
        
        JSONObject jsonObject = new JSONObject();
        
        UserInfo userInfo = userInfoDAO.selectByUserId(userId);
        if(userInfo!= null && userInfo.getPassword().equals(password)){
            HttpSession session = request.getSession(true);
            session.setAttribute("UserInfo",userInfo);    
            jsonObject.put("isLogin", true);
        }else{
            jsonObject.put("isLogin", false);
        }
        
        try{
            Thread.sleep(2000);
        }catch(InterruptedException e){
            ;
        }
            
        
            PrintWriter out = response.getWriter();
            out.println(jsonObject.toString());
            
            return null;
    }
    


LoginController.java에 메소드를 추가한다.




simplesite-servlet.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                
                <prop key="/login/form.do">loginController</prop>
                <prop key="/login/ajaxForm.do">loginController</prop>   <!-- ajax -->
                <prop key="/login/login.do">loginController</prop>
                <prop key="/login/ajaxLogin.do">loginController</prop> <!-- ajax -->
                <prop key="/login/logout.do">loginController</prop>
                <prop key="/user/form.do">userController</prop>
                <prop key="/user/add.do">userController</prop>
                <prop key="/user/modify.do">userController</prop>
                <prop key="/user/delete.do">userController</prop>
                <prop key="/user/list.do">userController</prop>
                <prop key="/user/search.do">userController</prop>
            </props>
        </property>
    </bean>


1
2
3
4
5
6
7
8
9
10
11
12
<bean id="loginControllerMethodNameResolver"
        class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
        <property name="mappings">
            <props>
                <prop key="/login/form.do">form</prop>
                <prop key="/login/ajaxForm.do">ajaxForm</prop>   <!-- ajax -->
                <prop key="/login/login.do">login</prop>
                <prop key="/login/ajaxLogin.do">loginUsingAjax</prop> <!-- ajax -->
                <prop key="/login/logout.do">logout</prop>
            </props>
        </property>    
    </bean>


urlmapping에 추가를 해준다.




결과값은 그전과 똑같은 결과값을 볼 수 있고, 로그인버튼을 누르면 spinner이미지가 동작한다.









반응형

'(Before)BitSchool' 카테고리의 다른 글

2014/07/03 UML  (0) 2014.07.03
2014/07/02 iBatis  (0) 2014.07.02
2014/06/27 SimpleSite - login,logout  (0) 2014.06.27
2014/06/25 AOP  (0) 2014.06.25
2014/06/23 Spring Framework  (0) 2014.06.23