JSP 세션

별의개발자커비·2023년 5월 13일
0

JSP

목록 보기
14/31
post-thumbnail

0. 세션

  • 클라이언트와 웹의 연결을 유지하는 것
  • 로그인 했다가 한참 지나면 로그아웃 되는 것 = 세션이 만료돼서
  • 세션은 웹 서버에만 존재하고 클라이언트에는 존재하지 않음
  • 클라이언트가 접속했을 때 세션을 만들어주는 것

1. 로그인

  • 폼 페이지
  • 세션 저장 페이지

01. session01.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>session01</title>
</head>
<body>
	<form action="process_session01.jsp" method="post">
		<p> 아이디: <input type="text" name="id">
		<p> 비밀번호: <input type="password" name="psw">
		<p> a <input type="text" name="a">
		<p> b: <input type="text" name="b">
		<p> c: <input type="text" name="c">
		<p> <input type="submit" value="전송">
	</form>
</body>
</html>

02. process_session01.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>process_session01</title>
</head>
<body>
<%
	String id = request.getParameter("id");
	String psw = request.getParameter("psw");
	if(id.equals("admin") && psw.equals("1234")){
		session.setAttribute("userId", id);
		session.setAttribute("userPsw", psw);
		
		session.setAttribute("a", 0);
		session.setAttribute("b", 1);
		session.setAttribute("c", 2);
		
		out.print("세션 설정 성공");
	} else{
		out.print("세션 생성 실패");
	}
%>
</body>
</html>
  • session.setAttribute("userId", id);

03. session02.jsp

<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<% 
	String id =  (String) session.getAttribute("userId");
	String psw = (String) session.getAttribute("userPsw");
%>

	<p> 세션에 설정된 id: <%= id %>
	<p> 세션에 설정된 psw: <%= psw %>
	
<%
// 세션에 설정된 정보 다 가져오기 -- 이거 생각날 수 있게 복습!
	Enumeration et =  session.getAttributeNames();
	while(et.hasMoreElements()){
		String name = et.nextElement().toString();
		out.print(session.getAttribute(name));
		out.print("<br>");
	}
%>
</body>
</html>
  • String id = (String) session.getAttribute("userId");
  • 정보 다가져오기 Enumeration et = session.getAttributeNames();
Enumeration et =  session.getAttributeNames();
	while(et.hasMoreElements()){
		String name = et.nextElement().toString();
		out.print(session.getAttribute(name));
		out.print("<br>");
	}

04. session03.jsp (세션 삭제)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>session03 세션삭제</title>
</head>
<body>
<%
	session.removeAttribute("a"); // 세션명중에 a라는 세션을 삭제한다
	// session.invalidate();	// 전부삭제
	session.setMaxInactiveInterval(60*60);	// 시간이 지나면 세션 삭제 (초)
	out.print(session.getMaxInactiveInterval()); 
%>
</body>
</html>```

### 01.
```java
코드를 입력하세요
  • session.removeAttribute("a"); // 세션명중에 a라는 세션을 삭제한다
  • session.invalidate(); // 전부삭제
  • session.setMaxInactiveInterval(60*60); // 시간이 지나면 세션 삭제 (초)
    -session.getMaxInactiveInterval() // 세션 설정된 시간이 얼마인지

2. 장바구니 수정 ver 1

01. Product.java

package dao;

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;		// 신품, 중고품, 재생품
	private String filename;		// 이미지 파일명
	private int quantity ; 			// 장바구니에 담은 개수
	
	public Product() {}
	
	public Product(String productId, String pname, Integer unitPrice, String description, String manufacturer,
			String category, long unitInStock, String condition, String filename) {
		super();
		this.productId = productId;
		this.pname = pname;
		this.unitPrice = unitPrice;
		this.description = description;
		this.manufacturer = manufacturer;
		this.category = category;
		this.unitInStock = unitInStock;
		this.condition = condition;
		this.filename = filename;

	}
	
	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

	public String getFilename() {
		return filename;
	}

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

	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 getSerialversionuid() {
		return serialVersionUID;
	}
	
}
  • private int quantity ; // 장바구니에 담은 개수
  • getter, setter 추가

02. product.jsp

<%@page import="dao.Product"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상세 정보</title>
</head>
<link
	href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
	rel="stylesheet"
	integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
	crossorigin="anonymous">
</head>
<jsp:useBean id="productDAO" class="dao.ProductRepository"
	scope="session"></jsp:useBean>

<%
	String id = request.getParameter("id");
	Product p = productDAO.getProductById(id);
%>	
<body>
	<jsp:include page="./menu.jsp"></jsp:include>
	<div class="container">
		<h1 class="display-3">상품 정보</h1>
	</div>
	
	<div class="container">
		<div class="row">
			<div class="col-md-5">
				<img alt="" src="../resources/images/<%=p.getFilename()%>" 
				style="width:100%" >
			</div>
			
			<div class="col-md-6">
				<p>상품명 :<%=p.getPname() %>
				<p>설명 :<%=p.getDescription() %>
				<p>상품코드 :<%=p.getProductId() %>
				<p>제조사 :<%=p.getManufacturer() %>
				<p>분류 :<%=p.getCategory() %>
				<p>재고 수 :<%=p.getUnitInStock() %>
				<p><h4><%=p.getUnitPrice() %></h4>
				<form name="addForm" action="./addCart.jsp" method="post" >
					<input type="hidden" name="id" value="<%=p.getProductId()%>">
				</form>
<script type="text/javascript">
 	const $addForm = document.addForm;
 	addToCart = () => {
	if(confirm("상품을 추가하겠습니까?")){
		$addForm.submit();
	} 
}
</script>
				
				<p>
					<a href="#" class="btn btn-info" onclick="addToCart()">상품 주문</a>
					<a href="./cart.jsp" class="btn btn-warning">장바구니</a>
					<a href="./products.jsp" class="btn btn-secondary">상품 목록</a>
			</div>
		</div>	
	</div>



	<jsp:include page="./footer.jsp"></jsp:include>
</body>
</html>
  • 이런 때 버튼을 a href로 쓰는 것 신기!!
  • input type = "hidden"
        <input type="hidden" name="id" value="<%=p.getProductId()%>">    
    : 이렇게 하면 이 페이지는 폼페이지가 아니지만 넘겨받는 페이지에서 이 페이지의 아이디 값을 알 수 있겠구나!
  • confirm();
    https://ko.javascript.info/alert-prompt-confirm

03. addCart.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>addCart</title>
</head>
<body>
<%
	String productId =  request.getParameter("id");
	out.print(productId);
%>
</body>
</html>
  • return 까먹지 말기!

3. 장바구니 수정 ver 2

01. addCart.jsp

<%@page import="java.util.ArrayList"%>
<%@page import="dao.Product"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>addCart</title>
</head>
<jsp:useBean id="productDAO" class="dao.ProductRepository" scope="session"></jsp:useBean>
<body>
<%
	// 추가하고자하는 상품 아이디를 가져와서
	String id =  request.getParameter("id");
	// 아이디가 있는지 검사
	if(id == null || id.trim().equals("")){ 	// id값을 못받은 경우 목록으로 돌아오게 (주소에만 입력한 경우 등)
		response.sendRedirect("products.jsp");
		return;
	}
	// 아이디에 해당하는 상품을 선택
	Product p = productDAO.getProductById(id);
	
	// 이건 무슨상황? 일단 예외처리
	if(p== null){
		response.sendRedirect("products.jsp");
		return;
	}
	
	// session에 선택된 상품 정보를 넣는다.
	List<Product> lists = (List<Product>) session.getAttribute("cartlist"); // 오브젝트라 타입캐스팅
		// session에 리스트가 없으면 생성하고
	if(lists == null){	
		lists = new ArrayList<Product>();
	} 
		// session에 리스트가 있으면 추가
	p.setQuantity(p.getQuantity()+1);
	lists.add(p);
	session.setAttribute("cartlist",lists );
	
	response.sendRedirect("product.jsp?id=" + id );

%>
</body>
</html>
  • session.setAttribute("cartlist", lists);
    이렇게 list를 세션으로 set해 저장할 수도 있구나!
  • response.sendRedirect("product.jsp?id="+id );
    ? response 쓸 때는 ./도 안쓰네?

02. cart.jsp

profile
비전공자 독학러. 일단 쌔린다. 개발 공부👊

0개의 댓글