JSP(13. 세션)

min seung moon·2021년 4월 16일
0

JSP

목록 보기
13/13

1. 세션의 개요

01. 세션(session)

  • 클라이언트와 웹 서버 간의 상태를 지속적으로 유지하는 방법
    • 예를 들면 웹 쇼핑몰에서 장바구니나 주문 처리와 같은 회원 전용 페이지의 경우 로그인 인증을 통해 사용 권한을 부여
    • 다른 웹 페이지에 갔다가 되돌아와도 로그인 상태가 유지되므로 회원 전용 페이지를 계속 사용할 수 있음
    • 이렇게 사용자 인증을 통해 특정 페이지를 사용할 수 있도록 권한 상태를 유지하는 것
  • 웹 서버에서만 접근이 가능하므로 보안 유지에 유리하며 데이터를 저장하는데 한계가 없음
  • 오직 웹 서버에 존재하는 객체로 웹 브라우저마다 하나씩 존재하므로 웹 서버의 서비스를 제공받는 사용자를 구분하는 단위가 됨
  • 웹 브라우저를 닫기 전까지 웹 페이지를 이동하더라도 사용자의 정보가 웹 서버에 보관되어 있어 사용자 정보를 잃지 않음

2. 세션 생성

01. 세션 생성

  • session 내장 객체의 setAttribute() 메소드를 사용
  • setAttribute() 메소드를 이용하여 세션의 속성을 설정하면 계속 세션 상태를 유지할 수 있음
  • 만약 동일한 세션의 속성 이름으로 세션을 생성하면 마지막에 설정한 것이 세션 속성 값이 됨
  • 첫 번째 매개변수 name은 세션으로 사용할 세션 속성 이름을 나타내며, 세션에 저장된 특정 값을 찾아오기 위한 키로 사용
  • 두 번째 매개변수 value는 세션의 속성 값
    • 세션 속성 값은 Object 객체 타입만 가능하기 때문에 int, double, char 등의 기본 타입은 사용할 수 없음

예제 01.

  • 세션 생성하기

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="session01_process.jsp" method="POST">
		<p> 아이디 : <input type="text" name="id"></p>
		<p> 비밀번호 : <input type="password" name="passwd"></p>
		<p> <input type="submit" value="전송"></p>
	</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String user_id = request.getParameter("id");
		String user_pw = request.getParameter("passwd");
		
		if(user_id.equals("admin")&&user_pw.equals("1234")) {
			session.setAttribute("userID", user_id);
			session.setAttribute("userPW", user_pw);
			out.print("세션 설정이 성공했습니다<br>");
			out.print(user_id+"님 환영합니다");
		}else {
			out.print("세션 설정이 실패했습니다");
		}
	%>
</body>
</html>

3. 세션 정보

01. 단일 세션 정보 얻기

  • 세션에 저장된 하나의 세션 속성 이름에 대한 속성 값을 얻어오려면 getAttribute() 메소드를 사용
  • getAttribute() 메소드는 반환 유형이 Object 형이므로 반드시 형 변환을 하여 사용해야 함
  • 첫 번째 매개변수 name은 세션에 저장된 세션 속성 이름
    • 해당 속성 이름이 없는 경우 null 반환

예제 02.

  • 세션에 저장된 속성 값 가져와 출력하기
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String user_id = (String) session.getAttribute("userID");
		String user_pw = (String) session.getAttribute("userPW");
		
		out.print("설정된 세션의 속성 값[1] : "+user_id+"<br>");
		out.print("설정된 세션의 속성 값[2] : "+user_pw+"<br>");
	%>
</body>
</html>

02. 다중 세션 정보 얻기

예제 03.

  • 세션에 저장된 모든 세션 속성 이름과 속성 값 가져와 출력하기
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String name;
		int i = 0;
		Enumeration en = session.getAttributeNames();
		
		while(en.hasMoreElements()) {
			name = en.nextElement().toString();
			++i;
			out.print("설정된 세션의 속성명["+i+"] : "+name+"<br>");
			out.print("설정된 세션의 속성값["+i+"] : "+session.getAttribute(name)+"<br>");
		}
	%>
</body>
</html>

4. 세션 삭제

01. 단일 세션 삭제하기

  • 세션에 저장된 하나의 세션 속성 이름을 삭제하려면 removeAttribute() 메소드를 사용

예제 04.

  • 세션에 저장된 세션 속성 삭제하기1
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String name;
		int i = 0;
		Enumeration en = session.getAttributeNames();
		
		while(en.hasMoreElements()) {
			name = en.nextElement().toString();
			++i;
			out.print("설정된 세션의 속성명["+i+"] : "+name+"<br>");
			out.print("설정된 세션의 속성값["+i+"] : "+session.getAttribute(name)+"<br>");
		}
	%>
</body>
</html>

예제 05.

  • 세션에 저장된 세션 속성 삭제하기2

<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h4>------세션을 삭제하기 전-----</h4>
	<%
		String name;
		int i = 0;
		Enumeration en = session.getAttributeNames();

		while(en.hasMoreElements()) {
			name = en.nextElement().toString();
			++i;
			out.print("설정된 세션의 속성명["+i+"] : "+name+"<br>");
			out.print("설정된 세션의 속성값["+i+"] : "+session.getAttribute(name)+"<br>");
		}

		session.removeAttribute("userID");
	%>
	<h4>------세션을 삭제한 후-----</h4>
	<%
		en = session.getAttributeNames();
		i = 0;
		
		while(en.hasMoreElements()) {
			name = en.nextElement().toString();
			++i;
			out.print("설정된 세션의 속성명["+i+"] : "+name+"<br>");
			out.print("설정된 세션의 속성값["+i+"] : "+session.getAttribute(name)+"<br>");
		}
	%>
</body>
</html>

02. 다중 세션 삭제하기

  • 세션에 저장된 모든 세션 속성 이름을 삭제하려면 invalidate() 메소드를 사용

예제 06.

  • 세션에 저장된 모든 세션 속성 삭제하기

<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h4>------세션을 삭제하기 전-----</h4>
	<%
		String user_id = (String) session.getAttribute("userID");
		String user_pw = (String) session.getAttribute("userPW");

		out.print("설정된 세션 이름 userID : " + user_id + "<br>");
		out.print("설정된 세션 이름 userPW : " + user_pw + "<br>");

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

5. 세션 유효시간 설정

01. 세션 유효 시간

  • 세션을 유지하기 위한 세션의 일정 시간
  • 웹 브라우저에 마지막 접근한 시간부터 일정 시간 이내에 다시 웹 브라우저에 접근하지 않으면 자동으로 세션이 종료
  • 세션 유효 시간을 설정하기 위해 session 내장 객체의 setMaxInactiveInterval() 메소드를 사용

예제 07.

  • 세션 유효 시간을 가져와 출력하기
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h4>----세션 유효 시간 변경 전----</h4>
	<%
		int time =session.getMaxInactiveInterval()/60;
	
		out.println("세션 유효 시간 : "+time+"분<br>");
	%>
	<h4>----세션 유효 시간 변경 후----</h4>
	<%
		session.setMaxInactiveInterval(60*60);
		time =session.getMaxInactiveInterval()/60;
	
		out.println("세션 유효 시간 : "+time+"분<br>");
	%>
</body>
</html>

예제 08.

  • 세션 아이디와 웹 사이트에서 유지한 시간 출력하기
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String session_id = session.getId();
	
	long last_time = session.getLastAccessedTime();
	
	long start_time = session.getCreationTime();
	
	long used_time = (last_time - start_time) / 60000;
	
	out.println("세션 아이디 : "+session_id+"<br>");
	out.println("요청 시작 시간 : "+start_time+"<br>");
	out.println("요청 마지막 시간 : "+last_time+"<br>");
	out.println("웹 사이트의 경과 시간 : "+used_time+"<br>");
	%>
</body>
</html>

6. 장바구니 페이지 만들기


  • dto/Product.java
package dto;

import java.io.Serializable;

public class Product implements Serializable{
	
	private static final long serialVersionUID = 1L;
	
	private String productId; 		// 상품아이디
	private String pname; 			// 상품명
	private Integer unitPrice;		// 상품가격
	private String description;		// 상품설명
	private String manufacturer;	// 제조사
	private String category;		// 분류
	private long unitInStock;		// 재고수
	private String condition;		// 신상품 or 중고품 or 재생품
	private String filename; 		// 이미지 파일명
	private int quantity; 			// 장바두긴 담은 개수
	
	public Product() {
		super();
	}
	
	public Product(String productId, String pname, Integer unitPrice){
		this.productId = productId;
		this.pname = pname;
		this.unitPrice = unitPrice;
	}

	public String getProductId() {
		return productId;
	}

	public void setProductId(String productId) {
		this.productId = productId;
	}

	public String getPname() {
		return pname;
	}

	public void setPname(String pname) {
		this.pname = pname;
	}

	public Integer getUnitPrice() {
		return unitPrice;
	}

	public void setUnitPrice(Integer unitPrice) {
		this.unitPrice = unitPrice;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getManufacturer() {
		return manufacturer;
	}

	public void setManufacturer(String manufacturer) {
		this.manufacturer = manufacturer;
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public long getUnitInStock() {
		return unitInStock;
	}

	public void setUnitInStock(long unitInStock) {
		this.unitInStock = unitInStock;
	}

	public String getCondition() {
		return condition;
	}

	public void setCondition(String condition) {
		this.condition = condition;
	}

	public static long getSerialcersionuid() {
		return serialVersionUID;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}
	
	
}
  • product.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="dto.Product"%>
<%@ page import="dao.ProductRepository"%>
<%@ page errorPage="exceptionNoProductId.jsp" %>
<jsp:useBean id="productDAO" class="dao.ProductRepository"
	scope="session" />
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>상품 상세 정보</title>
<style>
.content .row {
	padding: 30px 0;
	display : flex;
}
.content .row div {
	padding : 10px;
}

.content h3, .content p, .content h4 {
	margin: 25px 0;
}

.content h3 {
	margin-bottom: 5px;
}

.content .description {
	margin-top: 5px;
}

.content .badge {
	background-color: #f00;
	color: #fff;
	border-radius: 5px;
}
</style>
<script type="text/javascript">
	function addToCart() {
		if(confirm("상품을 장바구니에 추가하시겠습니까?")) {
			document.addForm.submit();
		} else {
			document.addForm.reset();
		}
	}
</script>
</head>
<body>
	<jsp:include page="header.jsp" />
	<div class="main">
		<div class="banner">
			<div class="container">
				<h1>상품 정보</h1>
			</div>
		</div>

		<%
			String id = request.getParameter("id");
			ProductRepository dao = ProductRepository.getInstance();
			Product product = dao.getProductById(id);
		%>
		<div class="content">
			<div class="container">
				<div class="row">
					<div>
						<img alt="상품 사진" style="width:100%"
							src="c:/upload/<%=product.getFilename()%>">
					</div>
					<div>
						<h3><%=product.getPname()%></h3>
						<p class="description"><%=product.getDescription()%></p>
						<p>
							<b>상품 코드 : </b><span class="badge"><%=product.getProductId()%></span>
						<p>
							<b>제조사</b> :
							<%=product.getManufacturer()%></p>
						<p>
							<b>분류</b> :
							<%=product.getCategory()%></p>
						<p>
							<b>재고 수</b> :
							<%=product.getUnitInStock() %>
						</p>
						<h4>
							<%=product.getUnitPrice()%>원
						</h4>
						<p>
							<form name="addForm" action="./addCart.jsp?id=<%=product.getProductId()%>" method="post">
								<a href="#" class="btn btn-secondary" onclick="addToCart()">상품 주문 &raquo;</a>
								<a href="./cart.jsp" class="btn">장바구니&raquo;</a>
								<a href="./products.jsp" class="btn">상품 목록 &raquo;</a>
							</form>
						
						</p>
					</div>
				</div>
				<hr>
			</div>
		</div>
	</div>
	<jsp:include page="footer.jsp" />
</body>
</html>
  • addCart.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="java.util.ArrayList"%>
<%@ page import="dto.Product"%>
<%@ page import="dao.ProductRepository"%>

<%
	String id = request.getParameter("id");
	if (id == null || id.trim().equals("")) {
		response.sendRedirect("products.jsp");
		return;
	}
	
	ProductRepository dao = ProductRepository.getInstance();
	
	Product product = dao.getProductById(id);
	if(product == null) {
		response.sendRedirect("exceptionNoProductId.jsp");
	}
	
	ArrayList<Product> goodsList = dao.getAllProducts();
	Product goods = new Product();
	for (int i = 0; i < goodsList.size(); i++) {
		goods = goodsList.get(i);
		if(goods.getProductId().equals(id)){
			break;
		}
	}
	
	ArrayList<Product> list = (ArrayList<Product>)session.getAttribute("cartlist");
	if(list == null) {
		list = new ArrayList<Product>();
		session.setAttribute("cartlist", list);
	}
	
	int cnt = 0;
	Product goodsQnt = new Product();
	for(int i = 0; i < list.size(); i++) {
		goodsQnt = list.get(i);
		if (goodsQnt.getProductId().equals(id)) {
			cnt++;
			int orderQuantity = goodsQnt.getQuantity()+1;
			goodsQnt.setQuantity(orderQuantity);
		}
	}
	
	if(cnt == 0) {
		goods.setQuantity(1);
		list.add(goods);
	}
	
	response.sendRedirect("product.jsp?id="+id);
%>
  • cart.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.ArrayList" %>
<%@ page import="dto.Product" %>
<%@ page import="dao.ProductRepository" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%
	String cartId = session.getId();
%>
<title>장바구니</title>
<style>
	.main .banner .container h1 {
		font-size : 8vw;
	}
	.btn-group {
		height: 100px;
		line-height: 100px;
	}
	.product-table {
		border-collapse: collapse;
		width: 100%;
	}
	.product-table td, th {
		border-top : 1px solid black;
		text-align: center;
		height: 50px;
	}
</style>
</head>
<body>
	<jsp:include page="header.jsp" />
	
	<div class="main">
		<div class="banner">
			<div class="container">
				<h1>장바구니</h1>
			</div>
		</div>

		<div class="content">
			<div class="container">
				<div class="row">
					<table width="100%">
						<tr class="btn-group">
							<td align="left"><a href="./deleteCart.jsp?cartId=<%=cartId %>" class="btn btn-danger" >삭제하기</a></td>
							<td align="right"><a href="#" class="btn btn-success" >주문하기</a></td>
						</tr>
					</table>
				</div>
				
				<div style="padding-top: 50px">
					<table class="product-table">
						<tr>
							<th>상품</th>
							<th>가격</th>
							<th>수량</th>
							<th>소계</th>
							<th>비고</th>
						</tr>
						<%
							int sum = 0;
							ArrayList<Product> cartList = (ArrayList<Product>)session.getAttribute("cartlist");
							if(cartList == null)
								cartList = new ArrayList<Product>();
							for(int i = 0; i < cartList.size(); i++) { // 상품 리스트 하나씩 출력하기
								Product product = cartList.get(i);
								int total = product.getUnitPrice() * product.getQuantity();
								sum = sum+total;
						%>
						<tr>
							<td><%=product.getProductId() %> - <%=product.getPname() %></td>
							<td><%=product.getUnitPrice() %></td>
							<td><%=product.getQuantity() %></td>
							<td><%=total %></td>
							<td><a href="./removeCart.jsp?id=<%=product.getProductId() %>" class="btn">삭제</a></td>
						</tr>
						<%
							}
						%>
						<tr>
							<th></th>
							<th></th>
							<th>총액</th>
							<th><%=sum %></th>
							<th></th>
						</tr>
					</table>
				</div>
				<div class="btn-group">
						<a href="./products.jsp" class="btn">&laquo; 쇼핑 계속하기</a>
					</div>
				<hr>
			</div>
		</div>
	</div>
	
	<jsp:include page="footer.jsp" />
</body>
</html>
  • removeCart.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.ArrayList" %>
<%@ page import="dto.Product" %>
<%@ page import="dao.ProductRepository" %>
<%
	String id = request.getParameter("id");
	if (id == null || id.trim().equals("")) {
		response.sendRedirect("products.jsp");
		return;
	}
	
	ProductRepository dao = ProductRepository.getInstance();
	
	Product product = dao.getProductById(id);
	if(product == null) {
		response.sendRedirect("exceptionNoProductId.jsp");
	}
	
	ArrayList<Product> cartList = (ArrayList<Product>)session.getAttribute("cartlist");
	Product goodsQnt = new Product();
	for(int i = 0; i< cartList.size(); i++) {
		goodsQnt = cartList.get(i);
		if(goodsQnt.getProductId().equals(id)) {
			cartList.remove(goodsQnt);
		}
	}
	
	response.sendRedirect("cart.jsp");
%>
  • deleteCart.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="dto.Product" %>
<%@ page import="dao.ProductRepository" %>

<%
	String id = request.getParameter("cartId");
	if(id == null || id.trim().equals("")) {
		response.sendRedirect("cart.jsp");
		return;
	}
	
	session.invalidate();
	
	response.sendRedirect("cart.jsp");
%>
profile
아직까지는 코린이!

0개의 댓글