728x90
반응형
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%-- src/main/webapp/ch06/session.jsp --%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>session을 이용한 장바구니 예제</title>
</head>
<body>
<h3>상품 선택</h3>
<form action="sessionAdd.jsp" method="post">
<select name="product">
<option>사과</option><option>배</option><option>감</option>
<option>자몽</option><option>귤</option><option>딸기</option>
</select>
<input type="submit" value="장바구니 추가">
</form>
<a href="sessionView.jsp">장바구니보기</a>
</body>
</html>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%-- src/main/webapp/ch06/sessionAdd.jsp --%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>장바구니 추가</title>
</head>
<body>
<% request.setCharacterEncoding("UTF-8"); //POST 방식인 경우 한글 인코딩
//request.getParameter("product") : product 이름의 파라미터 값 리턴
String product = request.getParameter("product");
//getAttribute("cart") : cart 이름 속성의 속성값 조회
List<String> cart=(List<String>)session.getAttribute("cart");
if(cart == null) { //cart라는 이름의 속성이 없는 경우
cart = new ArrayList<String>();
//session.setAttribute("cart", cart) : 속성 등록 (속성명, 속성값)
session.setAttribute("cart", cart);
}
cart.add(product); //ex)사과, 귤
%>
<script>
alert("<%=product%>이(가) 장바구니에 추가되었습니다.")
history.go(-1); //앞 페이지로 이동. session1.jsp 페이지로 이동.
</script>
</body>
</html>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%-- src/main/webapp/ch06/sessionView.jsp --%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>장바구니 보기</title>
</head>
<body>
<%
List<String> cart=(List<String>)session.getAttribute("cart");
if(cart == null || cart.size() == 0) {
%> <h3>장바구니에 상품이 없습니다.</h3>
<% } else { //cart 속성의 요소가 존재 %>
<h3>장바구니 상품</h3>
<% for(String p : cart) { %>
<h4><%=p %></h4>
<% }
}
//removeAttribute("cart") : cart 속성을 제거.
session.removeAttribute("cart");
%>
</body>
</html>
728x90
반응형