ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [4주][4일][5~8th] JSP: 세션과 쿠키. session and cookie.
    N스크린하이브리드앱과정/JSP:Model-1 2013. 8. 8. 18:50

    ★ 요약 - 세션과 쿠키

    * 개념

    세션 : 서버측에서 관리되는 정보

    쿠키 : 클라이언트측에서 관리되는 정보

    세션과 쿠키는 서버와 클라이언트의 연결을 유지해주는 것이다.

     

     

    ☆ 실습(1) : 로그인 창 만들고 세션값 생성하기

    * 조건

     - 4개의 파일이 필요하다

       -> "sessionForm.jsp", "sessionPro.jsp", "sessionMain.jsp", "sessionLogout.jsp"

     - 아이디, 비밀번호, 로그인, 로그아웃 버튼을 만든다.

     - 폼아이디 디비아이디 비교하기. 맞으면 통과
       폼비밀번호 디비 비밀번호 비교하기. 맞으면 로그인인증(세션값생성) 이동 sessionMain.jsp

     - 자바스크립트로 코딩하기
        아이디 틀리면 "아이디없음" 경고창 출력 후, 뒤로 이동   

        비밀번호 틀리면 "비밀번호틀림" 경고창 출력 후, 뒤로이동

      

    1. "sessionForm.jsp"

    바디

    <h1>로그인</h1>
    <form action="sessionPro.jsp" method="post">
    <table>
    <tr><td>아이디: <input type="text" name="id"> </td></tr>
    <tr><td>비밀번호: <input type="password" name="pass"></td></tr>
    <tr><td><input type="submit" value="로그인">
    <input type="button" value="로그아웃" onclick="location.href='sessionLogout.jsp'">
    </td></tr>
    </table>


    <%
    String id;
     if(session.getAttribute("id")!=null){
      id=(String)session.getAttribute("id");
      //세션값 있음
     }else{
      id="세션값 없음";//세션값 없음
     }
    %>
    세션값:<%=id %>
    </form>

     

    2. "sessionPro.jsp"

    바디

    <%
    request.setCharacterEncoding("utf-8");
    String id = request.getParameter("id");
    String pass = request.getParameter("pass");

    String dbId = "admin";
    String dbPass = "1234";

    if(id.equals(dbId)){
     if(pass.equals(dbPass)){
      session.setAttribute("id", id);
     }else{
      %><script type="text/javascript">
      alert("비밀번호 틀렷시요");
      history.back();
      </script> <%}
    }else{
     %><script type="text/javascript">
     alert("아이디 틀렸슈");
     history.back();
     </script> <%}
    %>


    <script type="text/javascript">
    alert("세션값 생성");
    location.href("sessionMain.jsp");
    </script>

     

    3. "sessionMain.jsp"

    바디 

    <%
    // 세션값 가져오기 id
    // Object형에서 String으로 형변환
    String id = (String)session.getAttribute("id");
    if(id==null){
     response.sendRedirect("sessionForm.jsp");
    }
    %>
    <h1>sessionMain.jsp페이지</h1>
    <%=id %>님이 로그인 하셨습니다.

     

    4. "sessionLogout.jsp"

    바디 

    <h1>로그아웃 페이지</h1>
    <%
    session.invalidate();
    %>
    <script type="text/javascript">
    alert("로그아웃");
    location.href("sessionForm.jsp");
    </script>

     

    로그인

    2번 파일에서 DB의 아이디와 비밀번호값이 따로 설정되어 있다. 위 그림의 경우 맞지 않은 아이디를 입력했기 때문에...

     

    아이디가 틀렸다고 경고창이 뜨게 된다.

     

    아이디는 맞았으나, 비밀번호를 틀리게 누르면

     

    위 그림처럼 비밀번호가 틀렸다고 뜬다.

     

    자, 이제 아이디와 비밀번호 모두 맞게 입력하고 나면,

    위 그림과 같이 세션값이 생성된다.

     

    메인 페이지에서 로그인 되었다고 문구가 뜨는데,

     

    여기서 세션값을 가져오는 getAttribute()를 이용하여 id가 뜨게 만들어 줄 수 있다.

     

    로그인이 완료되고 다시 폼 창으로 가면, 

    위 그림과 같이 세션이 현재 들어있는지를 표시해 줄 수 있다. 

     

    로그아웃 버튼을 누르면

    경고창이 뜨면서 세션값이 없어지고

     

    세션값이 지워진 상태로 다시 폼으로 돌아가게 된다.

     

     

    ☆ 실습(2) : 쿠키 테스트

     - 파일 3개 필요 : "cookieTest.jsp", "cookieSet.jsp", "cookieDel.jsp"

     - "쿠키값저장", "쿠키값삭제" 버튼 만들기

     - 쿠키의 현재상태를 1번파일에서 표시해주기

     

    (1) "cookieTest.jsp"

    <h1>쿠키 테스트</h1>
    <%
    String name="";
    //쿠키값 가져오기
    Cookie cookies[] = request.getCookies();
    if(cookies!=null){
     for(int i=0; i<cookies.length; i++){
      if(cookies[i].getName().equals("name")){
       name=cookies[i].getValue();
      }
     }
     if(name.equals("")){
      name="쿠키값 없음";
     }
    }else{
     name = "쿠키 다무따 ㅠ_ㅠ";
    }
    %>
    <input type="button" value="쿠키값저장" onclick="location.href='cookieSet.jsp'">
    <input type="button" value="쿠키값삭제" onclick="location.href='cookieDel.jsp'">
    쿠키값:<%=name %>

     

    (2) "cookieSet.jsp"

    <%
    Cookie cookie = new Cookie("name","cookie Test");
    cookie.setMaxAge(30); //2분
    response.addCookie(cookie); //클라이언트 저장
    %>
    <script type="text/javascript">
    alert("쿠키값 생성");
    location.href="cookieTest.jsp";
    </script>

     

    (3) "cookieDel.jsp"

    <%
    Cookie cookie[] = request.getCookies();
    if(cookie!=null){
     for(int i=0; i<cookie.length; i++){
      if(cookie[i].getName().equals("name")){
       cookie[i].setMaxAge(0); //시간 0
       response.addCookie(cookie[i]);
      }
     }
    }
    %>
    <script type="text/javascript">
    alert("쿠키값 삭제");
    location.href="cookieTest.jsp";
    </script>

     

    쿠키값저장 버튼을 누르면 

     

    쿠키값이 생성되면서(30초 동안 유지)

    <%
    Cookie cookie = new Cookie("name","cookie Test");
    cookie.setMaxAge(30); //30초
    response.addCookie(cookie); //클라이언트 저장
    %>

     

    초기화 때 지정한 쿠키값이 들어가게 된다.

     

    쿠키값 삭제를 누르면

     

    쿠키값이 사라지게 된다(배열로 쿠키값을 저장해 시간을 0으로 해줌)

    <%
    Cookie cookie[] = request.getCookies();
    if(cookie!=null){
     for(int i=0; i<cookie.length; i++){
      if(cookie[i].getName().equals("name")){ //쿠키이름이 name일 때만
       cookie[i].setMaxAge(0); //시간 0초
       response.addCookie(cookie[i]); //클라이언트에 저장
      }
     }
    }
    %>

     

     

    ☆ 실습(3) : 한글과 영어페이지를 쿠키값으로 표현하기

    - 파일 2개 필요 : "cookieForm.jsp", "cookiePro.jsp"

     

    (1) "cookieForm.jsp"

    <%
    String name="kor";
    //쿠키값 가져오기
    Cookie cookies[] = request.getCookies();
    if(cookies!=null){
     for(int i=0; i<cookies.length; i++){
      if(cookies[i].getName().equals("lang")){
       name=cookies[i].getValue();
      }
     }
     if(name.equals("")){
      name="쿠키값 없음";
     }
    }
    %>

    <%
    if(name.equals("kor")){
     %><h1>안녕하세요 이것은 쿠키예제입니다.</h1><%
    }else{
     %><h2>Hello, This is Cookie example</h2><%
    }
    %>
    <form action="cookiePro.jsp" method="post">
    <input type="radio" name="lang" value="kor"
    <%if(name.equals("kor")){%>checked<%}%>
    >한국어
    <input type="radio" name="lang" value="eng"
    <%if(name.equals("eng")){
    %>checked<%}%>
    >영어
    <input type="submit" value="쿠키값설정"><br>
    </form>
    쿠키값: <%=name %>

     

    (2) "cookiePro.jsp"

    <%
    String lang = request.getParameter("lang");
    Cookie cookie = new Cookie("lang",lang);
    cookie.setMaxAge(60*60*24);
    response.addCookie(cookie);

    if(lang.equals("kor")){
     out.println("한국어");
    }else{
     out.println("영어");
    }
    %>
    <script type="text/javascript">
    alert("쿠키 생성됨!");
    location.href="cookieForm.jsp";
    </script>

     

     

    영어가 체크된 상태로 쿠키값설정 버튼을 누르면

     

     

    쿠키가 생성되면서 영어라는 문구가 출력된다(내가 체크한 것이 영어라는 뜻)

    <%
    String lang = request.getParameter("lang"); //lang변수로 lang이라는 이름의 라디오버튼값을 받아옴
    Cookie cookie = new Cookie("lang",lang); //lang이라는 이름으로 쿠키 생성
    cookie.setMaxAge(60*60*24); //24시간
    response.addCookie(cookie); //클라이언트에 쿠키값 저장

    if(lang.equals("kor")){ //한국어인지 영어인지 라디오 체크시 출력해줌
     out.println("한국어");
    }else{
     out.println("영어");
    }
    %>

     

    한국어를 체크하고 쿠키값설정을 누르면

     

    역시 한국어가 출력되면서 쿠키가 생성된다.

     

    또, 페이지가 돌아가면서 h1태그에 한국어가 뜨는 것을 볼 수 있다.

    오늘 너무 멘붕이었다고!! ㅠ_ㅠ.......내 머리 버퍼링 걸림...

     

Designed by Tistory.