코딩기록 저장소 🐕/JSP

jsp session 로그인 장바구니 cookie

kimkongmom 2023. 9. 18. 09:04

 

 

 

 

로그인 로그아웃 

 

 

▶ html.file

JSP와 서블릿을 사용하여 간단한 로그인 및 로그아웃 기능을 구현하는 예제

HTML과 JSTL(Tomcat에서 제공하는 JavaServer Pages Standard Tag Library)을 사용하여 구현되었습니다.

${sessionScope.id}를 통해 세션에 저장된 사용자 ID를 출력합니다.

 

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script>
  // <body> 태그를 모두 읽은 뒤 function(){}을 실행한다.
  $(function(){
    $('#btn_logout').click(function(){
      location.href = "${contextPath}/logout";
    })
  })
  
</script>
</head>
</head>
<body>
 
<%-- 로그인   상태 --%>
<c:if test="${sessionScope.id == null}">
  <div>
    <form method="post" action="${contextPath}/login">
     <div>
      <label for="id">아이디</label>
      <input type="text" name="id" id="id">
     </div>
     <div>
      <label for="pw">비밀번호</label>
      <input type="password" name="pw" id="pw">
     </div> 
     <div>
      <button type="submit">로그인</button>
     </div>
    </form>
  </div>
</c:if>
 
<%-- 로그인  상태 --%>
<c:if test="${sessionScope.id != null}">
  <div>${sessionScope.id}님 환영합니다.</div>
  <div><button type="button" id="btn_logout">로그아웃</button></div>
</c:if>
</body>
</html>
cs

 

▶ Login.servlet

/login 경로로 요청을 받습니다.

폼에서 입력받은 아이디(id)와 비밀번호(pw)를 비교하여 로그인 성공 여부를 확인합니다.
로그인이 성공하면 세션(HttpSession)에 사용자 ID를 저장하고, 세션의 유효시간을 설정합니다. 

이 예제에서는 10분 동안 세션을 유지하도록 설정되어 있습니다.
로그인 성공 또는 실패 여부에 상관없이 로그인 화면으로 다시 이동합니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
      // 요청 인코딩
      request.setCharacterEncoding("UTF-8");
      
      // 요청 파라밑
      String id = request.getParameter("id");
      String pw = request.getParameter("pw");
      
      // 로그인 성고 규칙 : id와 pw가 동일하면 로그인 성공으로 가정하고 풀이
      if(id.equals(pw)) {
        // 로그인 처리 : session에 id를 저장해 두기
        HttpSession session = request.getSession();
        session.setAttribute("id", id);
        session.setMaxInactiveInterval(60 * 10); // 10분간 세션 유지
      }
      
      // 로그인 화면으로 되돌아가기
      response.sendRedirect(request.getContextPath() + "/ex06_session/login.jsp");
    }
cs

 

 

▶ Logout.servlet

/logout 경로로 요청을 받습니다.
세션(HttpSession)을 초기화하여 사용자를 로그아웃 상태로 만듭니다.

로그인화면으로 다시 이동합니다.

 

1
2
3
4
5
6
7
8
9
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
      // 로그아웃 : session 초기화
      HttpSession session = request.getSession();
      session.invalidate();
      
      // 로그인 화면으로 돌아가기
      response.sendRedirect(request.getContextPath() + "/ex06_session/login.jsp");
    }
cs

 

 

 

장바구니 (장바구니 기능을 구현한 예제)

 

 

▶ mainhtml.jsp 쇼핑목록

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<div>
  <form method="get" action="${contextPath}/addToCart">
    <h4>쇼핑목록</h4>
    <div>
      <select name="item">
        <option>진라면</option>
        <option>신라면</option>
        <option>삼양라면</option>
      </select>
      <input type="text" name="ea" placeholder="구매개수">
    </div>
    <div>
      <button type="submit">장바구니추가</button>
    </div>
  </form>
</div>
cs

 

 

▶ carthtml.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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script>
  //<body> 태그를 모두 읽은 뒤 function(){}을 실행한다.
  $(function(){
    $('#btn_shop').click(function(){
      location.href = '${contextPath}/ex06_session/main.jsp';
    })
    $('#btn_clear_cart').click(function(){
      if(confirm('장바구니를 비울까요?')){
        location.href = '${contextPath}/clearCart';
      } else {
        alert('장바구니 비우기를 취소했습니다.');
      }
    })
  })
</script>
</head>
<body>
 
<c:if test="${empty sessionScope.cart}">
  <div>장바구니가 비었습니다</div>
</c:if>
 
<c:if test="${not empty sessionScope.cart}">
  <c:forEach var="elem" items="${sessionScope.cart}">
    <div>${elem.item} ${elem.ea}</div>
  </c:forEach>
</c:if>
 
<div>
  <button type="button" id="btn_shop">계속쇼핑하기</button>
  <button type="button" id="btn_clear_cart">장바구니비우기</button>
</div>
 
</body>
</html>
cs

 

 

▶ AddToCart.servlet

요청 파라미터를 읽어와서 선택한 상품 (item)과 수량 (ea)을 추출합니다.
이 정보를 맵 형태로 저장하고, 이 맵을 세션에 저장합니다. 이를 통해 장바구니의 상태를 유지합니다.

 

 

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
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    // 요청 인코딩
    request.setCharacterEncoding("UTF-8");
    
    // 요청 파라미터
    String item = request.getParameter("item");
    int ea = Integer.parseInt(request.getParameter("ea"));
    
    // item + ea -> Map
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("item", item);
    map.put("ea", ea);
    
    // 장바구니 처리 방법 : session에 cart 속성을 저장하고 cart에 [item + ea -> Map] 저장하기
    HttpSession session = request.getSession();
    List<Map<String, Object>> cart = (List<Map<String, Object>>)session.getAttribute("cart");
    if(cart == null) {
      cart = new ArrayList<Map<String,Object>>();
      session.setAttribute("cart", cart);
    }
    
    // cart에 Map 저장하기
    cart.add(map);
    
    // 응답 타입과 인코딩
    response.setContentType("text/html; charset=UTF-8");
    
    // 응답 출력 스트림
    PrintWriter out = response.getWriter();
    
    // 응답하기
    out.println("<script>");
    out.println("if(confirm('" + item + "을 장바구니에 담았습니다. 장바구니로 가려면 \"확인\" 계속 쇼핑하려면 \"취소\" 버튼을 누르세요')){");
    out.println("location.href='" + request.getContextPath() + "/ex06_session/cart.jsp'");
    out.println("}else{");
    out.println("location.href='" + request.getContextPath() + "/ex06_session/main.jsp'");
    out.println("}");
    out.println("</script>");
    out.flush();
    out.close();
    
  }
cs

 

 

 

▶ ClearCart.servlet

세션에서 "cart" 속성을 제거하여 장바구니를 비웁니다.
사용자를 메인 화면으로 리디렉션하여 비워진 장바구니 상태를 보여줍니다.

 

 

1
2
3
4
5
6
7
8
9
10
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
    // 장바구니 비우기 : session에 저장된 cart 지우기
    HttpSession session = request.getSession();
    session.removeAttribute("cart");
    
    // main 화면으로 되돌아가기
    response.sendRedirect(request.getContextPath() + "/ex06_session/main.jsp");
    
  }
cs

 

 

 

 

 

 

Cookie

 

 

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
</head>
<body>
 
  <%
    String remember_me = "";  // 쿠키 remember_me가 없으면  문자열("")을 사용하기 위해서 초기화를 진행함
    Cookie[] cookies = request.getCookies();
    if(cookies != null){
      for(int i = 0; i < cookies.length; i++){
        if(cookies[i].getName().equals("remember_me")){
          remember_me = cookies[i].getValue();
          break;
        }
      }
    }
    pageContext.setAttribute("remember_me", remember_me);
  %>
 
  <div>
    <form method="post" action="${contextPath}/rememberMe">
      <div>
        <label for="id">아이디</label>
        <input type="text" name="id" id="id">
      </div>
      <div>
        <label for="pw">비밀번호</label>
        <input type="password" name="pw" id="pw">
      </div>
      <div>
        <button type="submit">로그인</button>
      </div>
      <div>
        <input type="checkbox" id="remember_me" name="remember_me">
        <label for="remember_me">아이디 기억</label>
      </div>
    </form>
  </div>
  <script>
    if('${remember_me}' !== ''){
      $('#id').val('${remember_me}');
      $('#remember_me').prop('checked'true);
    }
  </script>
 
</body>
</html>
cs

 

 

 

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
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
    // 요청 인코딩
    request.setCharacterEncoding("UTF-8");
    
    // 요청 파라미터 (id, remember_me)
    String id = request.getParameter("id");                    // 입력 상자의 입력이 없으면 빈 문자열("")
    String remember_me = request.getParameter("remember_me");  // checkbox의 체크가 없으면 null
    
    // 아이디 기억하기 체크했다면 쿠키에 id를 저장한다.
    Cookie cookie = null;
    if(remember_me != null) {  // if(remember_me.equals("on")){ 과 동일함
      cookie = new Cookie("remember_me", id);
      cookie.setMaxAge(60 * 60 * 24 * 15);  // 15일간 쿠키 유지
    } else {
      cookie = new Cookie("remember_me""");
      cookie.setMaxAge(0);                  // 쿠키 삭제를 위해 0초간 쿠키 유지
    }
    
    // 쿠키는 클라이언트에게 전달한다. (쿠키는 클라이언트가 저장한다.)
    response.addCookie(cookie);
    
    // main 화면으로 돌아가기
    response.sendRedirect(request.getContextPath() + "/ex07_cookie/main.jsp");
    
  }
cs

 

 

 

 

 

 

'코딩기록 저장소 🐕 > JSP' 카테고리의 다른 글

mvc pattern2  (0) 2023.09.19
mvc pattern  (0) 2023.09.18
JSP jstl  (0) 2023.09.15
JSP Lombok  (0) 2023.09.15
JSP 내장객체  (0) 2023.09.14