2008년 8월 12일 화요일

JSP, AJAX, Prototype, JSON, XML을 이용한 로그인 처리..


JSP, AJAX, Prototype, JSON을 이용한 로그인 처리.. 라고 타이틀은 지었지만,

이름 만큼 대단한 예제는 아니다.. 다만, 위의 언어들을 이용해서 만든 Refresh 없는 로그인 처리이다.

방식은 로그인 체크가 필요한 버튼이나 어떠한 행위가 이루어 질때, checkLogin() 을 호출.

loginCheck.jsp 를 불러온다. loginCheck.jsp 에는 JSON 타입으로, 세션체크를 하여, 로그인 여부를 판별한다.

checkLogin() -> loginCheck.jsp (세션 체크 후 JSON 생성) -> resultProc() 에서 처리

위와 같은 방식이 가능한 것은 브라우져의 세션은 현재 띄우고 있는 브라우져의 부모나 자식창에 세션이 상속되기

때문에 기존에 iFrame 으로 작업을 했으나, 새로고침을 해야 하는 번거로움이 있었다. 그러나 이방식은

새로고침이 필요없다.

우선, 로그인 처리를 할 페이지를 만들어 준다.

로그인 체크를 위핸 javascript 메소드를 만들어 준다. 이때, prototype.js 가 include 되어있어야 한다.


main.html
    [code]
    function checkLogin()
    {
    var url = './loginCheck.jsp?timeStamp=' + new Date().getTime();

     var myAjax = new Ajax.Request(
         url,
        {
           onComplete: resultProc,
           onException: onException
        });
     }

    function resultProc(req) {

        //JSON 방식
        var result = eval("(" + req.responseText + ")");
      
        if( result.data.result == 1 ){
            alert("로그인 되어있음");
           
        } else {
            goLogin();
       
        }
}
[/code]


loginCheck.jsp (JSON)
[code]
<%@ page contentType="text/plain; charset=euc-kr" %>
<%
String MEMBER_ID = "";
String result = "2";

if( session.getAttribute("MEMBER_ID")!=null ){
    MEMBER_ID = session.getAttribute("MEMBER_ID").toString();
    result = "1";
}

%>

{
   data: {
        result: '<%=result %>',
        memberid: '<%=MEMBER_ID %>'
       
    }
}
[/code]





위 방식을 xml 을 로드해서 처리 하려면 아래와 같이 바꾸면 된다.




main.html
[code]
    function resultProc(req) {
        var xmlDoc = req.responseXML;
        var result = xmlDoc.getElementsByTagName("result")[0].firstChild.nodeValue;
        console( result );
    }
[/code]


loginCheck.jsp (XML)
[code]
<?xml version="1.0" encoding="utf-8" ?>
<%@ page contentType="text/xml; charset=utf-8" %>
<%
String MEMBER_ID = "";
String result = "2";

if( session.getAttribute("MEMBER_ID")!=null ){
    MEMBER_ID = session.getAttribute("MEMBER_ID").toString();
    result = "1";
}

%>

<node>
    <result><%=result %></result>
</node>
[/code]


JSP로 XML를 파싱할떄 주의!! 꼭 위의 빨간 색 부분의 contentType 를 지정해 주어야 제대로 인식한다..

이것때문에 30분간 뻘짓.. -_-;



댓글 없음:

댓글 쓰기