Learn & Record

JSP (쿠키 객체 삭제, 연습문제, 세션 Session, 세션 생성, 세션 액션 페이지, 세션 값 가져와서 출력, 세션 삭제, 세션 모두 삭제, 세션 유효시간 설정, 세션 연습문제) 본문

Dev/JSP

JSP (쿠키 객체 삭제, 연습문제, 세션 Session, 세션 생성, 세션 액션 페이지, 세션 값 가져와서 출력, 세션 삭제, 세션 모두 삭제, 세션 유효시간 설정, 세션 연습문제)

Walker_ 2024. 4. 18. 12:13

1. 쿠키 객체에 저장된 모든 쿠키 삭제하기

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%--
     쿠키 객체에 저장된 모든 쿠키 삭제하기
     1) 쿠키 정보를 얻어오도록 request 내장 객체의 getCookies() 메서드 작성
     2) 얻어온 모든 쿠키를 삭제하도록 Cookie 객체의 setMaxAge() 메서드에 유효기간을 0으로 설정
     3) 웹 페이지 cookie02.jsp로 이동하도록 response 내장 객체의 sendRedirect() 메서드를 작성
     --%>
    <%
        Cookie[] cookies = request.getCookies();

        for (int i = 0; i < cookies.length; i++) {
            cookies[i].setMaxAge(0);
            response.addCookie(cookies[i]);
        }
        response.sendRedirect("07_cookie.jsp");
    %>

</body>
</html>

 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <form action="cookie01_process.jsp" method="post">
      <p>아 이 디 : <input type="text" name="id"></p>
      <p>비밀번호 : <input type="text" name="passwd"></p>
      <p><input type="submit" value="전송"></p>
  </form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <%--
  쿠키 객체에 저장된 모든 쿠키 값 가져와 출력하기
  1) 쿠키 정보를 얻어오도록 request 내장 객체의 getCookies() 메서드 작성
  2) 얻어온 쿠키 정보의 개수를 출력하도록 Cookie 객체의 length를 작성
  3) 얻어온 쿠키 정보에서 쿠키 이름과 값을 하나씩 출력하도록 Cookie 객체의 getName(), getValue() 메서드 작성
  --%>
  <%
    boolean isLogin = false;
    String userId = "";
    Cookie[] cookies = request.getCookies(); // request에서 쿠키를 얻어옴
    out.println("현재 설정된 쿠키의 개수 => " + cookies.length + "<br>");
    out.println("==============================<br>");
    for (int i = 0; i < cookies.length; i++) {
      out.println("설정된 쿠키의 속성 이름 [ " + i + " ] : " + cookies[i].getName() + "<br>");
      out.println("설정된 쿠키의 속성 값 [ " + i + " ] : " + cookies[i].getValue() + "<br>");
      out.println("-------------------------------------<br>");

      if (cookies[i].getName().equals("userId") && cookies[i].getValue() != null) {
          //userId라는 쿠키 이름이 있고 value가 null이 아니면 로그인한 것으로 간주
          isLogin = true;
          userId = cookies[i].getValue();
      }
    }

    if (isLogin) {
      out.print(userId + "님이 로그인 중입니다.");
    } else {
      out.print("로그인 상태가 아닙니다.");
    }
  %>
</body>
</html>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
  <%--
  쿠키 생성하기
  1) 전송된 아이디와 비밀번호가 일치하면, 쿠키 이름 userId, userPw에 값을 설정하도록 Cookie 객체를 생성
  --%>
<body>
  <%
    String userId = request.getParameter("id");
    String userPw = request.getParameter("passwd");

    if (userId.equals("admin") && userPw.equals("1234")) { // 로그인 정보가 맞으면
      Cookie cookidId = new Cookie("userId", userId); // 쿠키 생성. Cookie 클래스를 이용해서 쿠키 객체 생성
      Cookie cookiePw = new Cookie("userPw", userPw);
      response.addCookie(cookidId); // response할 때 쿠키도 같이 보낼 것
      response.addCookie(cookiePw);

      out.println("쿠키 생성이 성공했습니다<br>");
      out.println(userId + "님 환영합니다.");
    } else {
      out.println("쿠키 생성이 실패했습니다.");
    }
  %>

</body>
</html>

 

2. 연습문제

  1) cookie.jsp 파일을 생성합니다.
* input 태그에 text 유형을 이용하여 아이디, 비밀번호 항목을 작성합니다.
* form 태그의 action 속성 값은 cookie_process.jsp 로 작성합니다.

2) cookie_process.jsp 파일을 생성합니다.
* request  내장 객체의 getParameter() 메서드를 이용하여 전송된 요청 파라미터 값을 받습니다.
* 아이디와 비밀번호가 인증되면 아이디 값을 쿠키명 userId 의 쿠키 값으로 설정합니다.
* response 내장 객체의 sendRedirect() 메서드를 이용하여 welcome.jsp 파일로 이동하도록 작성합니다.

3) welcome.jsp 파일을 생성합니다.
* 이 페이지는 로그인이 된 사용자만 접근 가능한 페이지입니다.
* 설정된 쿠키명 userId 가 없으면 response 내장 객체의 sendRedirect() 메서드를 이용하여 cookie.jsp 파일로 이동합니다.
* 설정된 쿠키명 userId 가 있으면 안내 메시지를 출력합니다. 예) admin님 반갑습니다.
* 로그아웃을 할 사용자를 위해 <로그아웃>을 클릭하면 설정된 쿠키을 해제하도록 작성합니다.
링크는 cookie_out.jsp로 합니다.

4) cookie_out.jsp 파일을 생성합니다.
* 설정된 모든 쿠키명을 해제하도록 작성합니다.
* response 내장 객체의 sendRedirect() 메서드를 이용하여 cookie.jsp 파일로 이동하도록 작성합니다.

 

 1) cookie.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <form action="cookie_process.jsp" method="post">
    <p>아 이 디 : <input type="text" name="id"></p>
    <p>비밀번호 : <input type="text" name="passwd"></p>
    <p><input type="submit" value="전송"></p>
  </form>
</body>
</html>

 

 2) cookie_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <%
    String userId = request.getParameter("id");
    String userPw = request.getParameter("passwd");

    if (userId.equals("admin") && userPw.equals("1234")) {
      Cookie cookieId = new Cookie("userId", userId);
      Cookie cookiePw = new Cookie("userPw", userPw);
      response.addCookie(cookieId);
      response.addCookie(cookiePw);

      out.println("쿠키 생성이 성공했습니다<br>");
      out.println(userId + "님 환영합니다.");
      response.sendRedirect("welcome.jsp");
    }
    else {
      out.println("쿠키 생성이 실패했습니다.");
    }
  %>

</body>
</html>

 

 3) welcome.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    boolean isLogin = false;
    String userId = "";
    Cookie[] cookies = request.getCookies(); // request에서 쿠키를 얻어옴
    out.println("현재 설정된 쿠키의 개수 => " + cookies.length + "<br>");
    out.println("============================<br>");
    for (int i = 0; i < cookies.length; i++) {
        out.println("설정된 쿠키의 속성 이름 [ " + i + " ] : " + cookies[i].getName() + "<br>");
        out.println("설정된 쿠키의 속성 값 [ " + i + " ] : " + cookies[i].getValue() + "<br>");
        out.println("---------------------------<br>");

        if (cookies[i].getName().equals("userId") && cookies[i].getValue() != null) {
            // userId라는 쿠키 이름이 있고 value가 null이 아니면 로그인 한 것으로 간주
            isLogin = true;
            userId = cookies[i].getValue();
        }
    }

    if (isLogin) {
        out.print(userId + "님 반갑습니다.");
    } else {
        response.sendRedirect("cookie.jsp");
    }
%>

<a href="cookie_out.jsp">로그아웃</a>
</body>
</html>

 

 4) cookie_out.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <%
    Cookie[] cookies = request.getCookies();

    for (int i = 0; i < cookies.length; i++) {
      cookies[i].setMaxAge(0);
      response.addCookie(cookies[i]);
    }
    response.sendRedirect("cookie.jsp");
  %>
</body>
</html>

 

3. 세션 Session

 - 클라이언트와 웹 서버 간의 상태를 지속적으로 유지하는 방법

 

 - 1) 세션생성

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <form action="session01_process.jsp" method="post">
    <p>아 이 디 : <input type="text" name="id"></p>
    <p>비밀번호 : <input type="text" name="passwd"></p>
    <p><input type="submit" value="전송"></p>
  </form>
</body>
</html>

 

 - 2) 세션 액션 페이지

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--
 세션 설정하기
 1) 전송된 아이디 비번이 일치하면 세션 속성 이름 userID, userPW에 값을 설정하도록
 session 내장 객체의 setAttribute() 메서드 작성
 2) 일치하지 않으면 실패 메시지를 출력
 --%>
<%
    String userId = request.getParameter("id");
    String userPw = request.getParameter("passwd");

    if (userId.equals("admin") && userPw.equals("1234")) {
        session.setAttribute("userId", userId);
        session.setAttribute("userPw", userPw);
        out.println("세션 설정이 성공했습니다.<br>");
        out.println(userId + "님 환영합니다.");
        // 쿠키와는 다르게 response 객체에 세션을 담는 과정은 없음 -> 서버에 저장하기 때문에.
    } else {
        out.println("세션 설정이 실패했습니다.");
    }
%>

</body>
</html>

 

- 3) 세션 값 가져와서 출력하기

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <%--
   세션에 저장된 속성 값 가져와 출력하기
   1) 세션에 저장된 세션 속성 이름 userID, userPW의 속성 값을 가져오도록
   session 내장 객체의 getAttribute() 메서드를 작성
   --%>
  <%
    String userId = (String) session.getAttribute("userId");
    String userPw = (String) session.getAttribute("userPw");

    out.println("설정된 세션의 속성 값 [1] : " + userId + "<br>");
    out.println("설정된 세션의 속성 값 [2] : " + userPw);
  %>

</body>
</html>

 

 - 4) 세션 삭제

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <p><h4>------ 세션을 삭제하기 전 -----</h4>
  <%--
   세션에 저장된 세션 속성 삭제하기.
   1) 세션에 저장된 세션 속성 이름 userID를 삭제하도록 session 내장 객체의 removeAttribute() 메서드를 작성
   --%>
  <%
      String userId = (String) session.getAttribute("userId");
      String userPw = (String) session.getAttribute("userPw");
      out.println("설정된 세션 userId : " + userId + "<br>");
      out.println("설정된 세션 userPw : " + userPw + "<br>");

      session.removeAttribute("userId");
  %>
  <p><h4>------ 세션을 삭제한 후 ------</h4>
  <%
    userId = (String) session.getAttribute("userId");
    userPw = (String) session.getAttribute("userPw");
    out.println("설정된 세션 userId : " + userId + "<br>");
    out.println("설정된 세션 userPw : " + userPw + "<br>");
  %>
</body>
</html>

 

 - 5) 세션 모두 삭제

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <%--
   세션에 저장된 모든 세션 속성 삭제하기.
   1) 요청에 포함된 클라이언트의 세션이 유효하면 유효한 메시지를 출력하고,
   그렇지 않으면 유효하지 않은 메시지를 출력하도록 작성
   2) 세션에 저장된 모든 세션 속성을 삭제하도록 session 내장 객체의 invalidate() 메서드를 작성
   --%>
  <%
    String userId = (String) session.getAttribute("userId");
    String userPw = (String) session.getAttribute("userPw");

    out.println("설정된 세션 이름 userId : " + userId + "<br>");
    out.println("설정된 세션 값 userPw : " + userPw + "<br>");

    // request.isRequestdSessionIdValid() : request에 포함된 sessionId가 유효한지 검사. 반환형은 boolean.
    if (request.isRequestedSessionIdValid() == true) {
      out.print("세션이 유효합니다.");
    } else {
      out.print("세션이 유효하지 않습니다.");
    }

    session.invalidate();
  %>
<p><h4>----- 세션을 삭제한 후 ------</h4></p>
<%
  if(request.isRequestedSessionIdValid() == true) {
    out.print("세션이 유효합니다.");
  } else {
    out.print("세션이 유효하지 않습니다.");
  }
%>
</body>
</html>

 

4. 세션 유효시간 설정

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <%--
  세션 아이디와 웹 사이트에서 유지한 시간 출력하기.
  1) 고유한 세션 내장 객체의 아이디를 가져오도록 session 내장 객체의 getId() 메서드를 작성.
  2) 세션에 마지막으로 접근한 시간을 가져오도록 session 내장 객체의 getLastAccessedTime() 메서드를 작성.
  3) 세션이 생성된 시간을 가져오도록 session 내장 객체의 getCreationTime() 메서드를 작성.
  4) 웹 사이트에 머문 시간을 계산하도록 작성.
  --%>
  <%
    String sessinId = session.getId();
    // 세션에 마지막으로 접근한 시간
    long lastTime = session.getLastAccessedTime();  // 단위가 1/1,000초
    // 세션이 생성된 시간
    long startTime = session.getCreationTime();  // 단위가 1/1,000초

    long usedTime = (lastTime - startTime) / 1000;

    out.println("세션 아이디 : " + sessinId + "<br>");
    out.println("요청 시작 시간  : " + startTime + "<br>");
    out.println("요청 마지막 시간  : " +  lastTime + "<br>");
    out.println("웹 사이트에서 경과 시간  : " + usedTime + "초<br>");
  %>
</body>
</html>

 

5. 세션 연습문제

 

 - 1) session.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <form action="session_process.jsp" method="post">
    <p>아 이 디 : <input type="text" name="id">
    <p>비밀번호 : <input type="text" name="passwd">
    <p><input type="submit" value="로그인 "></p>
  </form>
</body>
</html>

 

 - 2) session_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <%
    String userId = request.getParameter("id");
    String userPw = request.getParameter("passwd");

    if (userId.equals("admin") && userPw.equals("1234")) {
      session.setAttribute("userId", userId);
      session.setAttribute("userPw", userPw);
      out.println("세션 설정이 성공했습니다.<br>");
      out.println(userId + "님 환영합니다.");
      // 쿠키와는 다르게 response 객체에 세션을 담는 과정은 없음 -> 서버에 저장하기 때문에.
      response.sendRedirect("welcome.jsp");

    } else {
      out.println("세션 설정이 실패했습니다.");
    }

  %>
</body>
</html>

 

 - 3) welcome.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <%
    String userId = (String) session.getAttribute("userId");
    String userPw = (String) session.getAttribute("userPw");

    if (userId == null) {
      response.sendRedirect("session.jsp");
    } else {
      out.println(userId + "님 반갑습니다.");
    }
  %>
<a href="session_out.jsp">로그아웃</a>
</body>
</html>

 

- 4) session_out.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <%
    session.invalidate();
    response.sendRedirect("session.jsp");
  %>
</body>
</html>

 

 


공부 과정을 정리한 것이라 내용이 부족할 수 있습니다.

부족한 내용은 추가 자료들로 보충해주시면 좋을 것 같습니다.

읽어주셔서 감사합니다 :)