새소식

인기 검색어

풀스택개발자_대학교 정규과정/JSP_Example

session으로 장바구니 기능 구현

  • -

 

Login.jsp : 사용자의 id를 입력

setProduct.jsp : 상품 추가

add.jsp : 상품을 세션에 추가한다

checkOut.jsp : 선택한 상품들의 리스트를 보여준다

 

Login.jsp

 

더보기

 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<link rel="stylesheet" href="/css/cartCss.css" type="text/css">
<% session.invalidate();%>
<body>
<H1>로그인</H1>
<Hr>
<DIV>
    <form method="post" action="setProduct.jsp">
        <input type="text" name="userId" required autofocus>
        <button type="submit">로그인</button>
    </form>
</DIV>
</body>
</html>

setProduct.jsp

더보기

session에 parameter로 넘어온 값을 삽입한다

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<link rel="stylesheet" href="/css/cartCss.css" type="text/css">
<body>
<%
    request.setCharacterEncoding("utf-8");
    String userId = request.getParameter("userId");
    if (userId != null) {
        session.setAttribute("userId", userId);
    } else {
        if (session.getAttribute("userId") == null) {
            out.println("<script> alert('세션이 해제되어 다시 설정합니다.'); location.href = './Login.jsp'; </script>");
        }
    }

%>
<H1>상품선택</H1>
<Hr>
<p><%= session.getAttribute("userId")%>님이 로그인 한 상태입니다.</p>
<a href="Login.jsp">로그아웃</a>
<Hr>
<DIV>
    <form method="post" action="add.jsp">
        <select name="product">
            <option value="사과">사과</option>
            <option value="귤">귤</option>
            <option value="포토">포토</option>
            <option value="복숭아">복숭아</option>
            <option value="망고">망고</option>
        </select>
        <button type="submit">추가</button>
    </form>
    <a href="checkOut.jsp">계산</a>
</DIV>
</body>
</html>

add.jsp

더보기

arrays.indexof 메서드를 사용함으로써 count배열과 list의 항목의 순서를 같게 매칭한다

<%@ page import="java.util.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<%
    request.setCharacterEncoding("utf-8");
    String item = request.getParameter("product");
    HashMap<String, Integer> cartMap = (HashMap<String, Integer>) session.getAttribute("cartMap");
    if (cartMap == null) {//장바구니가 존재하지 않을 경우
        cartMap = new HashMap<>();
        cartMap.put(item, 1);
    } else {//session에 장바구니 리스트가 존재할 경우
        if (cartMap.containsKey(item)) {
            cartMap.put(item, cartMap.get(item) + 1);
        } else {
            cartMap.put(item, 1);
        }
    }
    session.setAttribute("cartMap", cartMap);
    out.println("<script> alert('Success!!'); location.href = './setProduct.jsp'; </script>");
%>
<link rel="stylesheet" href="/css/cartCss.css" type="text/css">
<body>
</body>
</html>

checkOut.jsp

더보기
<%@ page import="java.util.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<%
    request.setCharacterEncoding("utf-8");
    HashMap<String, Integer> cartMap = null;
    String rItem = request.getParameter("rItem");
    String removeItem = request.getParameter("removeItem");

    if (session.getAttribute("userId") == null) {
        out.println("<script> alert('세션이 해제되어 다시 설정합니다.'); location.href = './Login.jsp'; </script>");
    } else {
        cartMap = (HashMap<String, Integer>) session.getAttribute("cartMap");
    }

    if (removeItem != null) {//삭제 요청으로 파라메터를 전달받을시
        cartMap.remove(removeItem);
    }
    if (rItem != null) {//수량 수정 요청으로 파라메터를 전달받을시
        cartMap.put(rItem, Integer.parseInt(request.getParameter("tcount")));
    }
%>
<link rel="stylesheet" href="/css/cartCss.css" type="text/css">
<body>
<H1>계산</H1>
<h2>선택한 상품 목록</h2>
<Hr>
<%
    if (cartMap != null)
        for (Map.Entry<String, Integer> entry : cartMap.entrySet()) {
%>
<h2><%=entry.getKey()%> * <%=entry.getValue()%> <a href="#" onclick="prompttest('<%=entry.getKey()%>')">수정</a>&nbsp;<a
        href="?removeItem=<%=entry.getKey()%>">삭제</a>
</h2>
<%}%>
<a href="./setProduct.jsp">목록으로 돌아가기</a>
</body>
<script>
    function prompttest(item) {
        location.href = "checkOut.jsp?rItem=" + item + "&&tcount=" + prompt("수량을 입력하시오.");
    }
</script>
</html>

cartCss.css

더보기
*{
    box-sizing: border-box;
    text-align: center;
}
a{
    text-decoration-line: none; /* 링크의 밑줄 제거 */
    color:inherit; /* 링크의 색상 제거 */
}

web.xml

더보기

web.xml에 해당 코드를 작성하면 클라이언트가 1분동안 요청이 없으면 세션 제거합니다

    <session-config>
        <session-timeout>1</session-timeout>
    </session-config>
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.