[쉽게 배우는 JSP 웹 프로그래밍] 13장 정리, 연습문제

세션은 클라이언트와 웹 서버 간의 상태를 지속적으로 유지하는 방법으로, 세션 생성은 session 내장 객체의 setAttribute() 메소드를 사용하며, 세션 삭제는 session 내장 객체의 removeAttribute() 또는 invalidate() 메소드를 사용한다. 세션 정보를 얻기 위해 getAttribute() 또는 getAttributeNames() 메소드를 사용하며, 세션 유효 시간을 설정하려면 setMaxInactiveInterval() 메소드를 사용한다. 이러한 세션의 개념과 사용법을 이해하고 적용하는 연습문제를 통해 실습하였다.
Feb 29, 2024
[쉽게 배우는 JSP 웹 프로그래밍] 13장 정리, 연습문제

세션 생성, 삭제

session01.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Session</title> </head> <body> <form action="session01_process.jsp" method="post"> <p> 아이디: <input type="text" name="id"> <p> 비밀번호: <input type="text" name="passwd"> <p> <input type="submit" value="전송"> </form> </body> </html>

session01_process.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Session</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.println("세션 설정이 성공했습니다<br>"); out.println(user_id+"님 환영합니다"); }else{ out.println("세션 설정이 실패했습니다"); } %> </body> </html>
 

핵심 키워드

  • 세션은 클라이언트와 웹 서버 간의 상태를 지속적으로 유지하는 방법을 말한다.
  • 세션을 사용하려면 먼저 세션을 생성해야 한다.
    • 세션 생성은 session 내장 객체의 setAttribute() 메소드를 사용한다.
  • 생성된 세션을 더 유지할 필요가 없으면 세션을 삭제한다.
    • 세션 삭제는 session 내장 객체의 removeAttribute() 또는 invalidate() 메소드를 사용하여 삭제한다.
 

세션 정보

session02.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Session</title> </head> <body> <% String user_id = (String) session.getAttribute("userID"); String user_pw = (String) session.getAttribute("userPW"); out.println("설정된 세션의 속성 값 [1] : " + user_id + "<br>"); out.println("설정된 세션의 속성 값 [2] : " + user_pw); %> </body> </html>

session03.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="java.util.Enumeration"%> <html> <head> <title>Session</title> </head> <body> <% String name; String value; Enumeration en = session.getAttributeNames(); int i = 0; while (en.hasMoreElements()) { i++; name = en.nextElement().toString(); value = session.getAttribute(name).toString(); out.println("설정된 세션의 속성 이름 [" + i + "] : " + name + "<br>"); out.println("설정된 세션의 속성 값 [" + i + "] : " + value + "<br>"); } %> </body> </html>
 

핵심 키워드

  • 생성된 세션의 정보를 얻어오려면 session 내장 객체의 getAttribute() 또는 getAttributeNames() 메소드를 사용한다.
 

세션 유효 시간 설정

session07.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="java.util.Enumeration"%> <html> <head> <title>Session</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>

session08.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="java.util.Enumeration"%> <html> <head> <title>Session</title> </head> <body> <% String sessin_id = session.getId(); long last_time = session.getLastAccessedTime(); long start_time = session.getCreationTime(); long used_time = (last_time - start_time) / 6000; out.println("세션 아이디 : " + sessin_id + "<br>"); out.println("요청 시작 시간 : " + start_time + "<br>"); out.println("요청 마지막 시간 : " + last_time + "<br>"); out.println("웹 사이트의 경과 시간 : " + used_time + "<br>"); %> </body> </html>
 

핵심 키워드

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

연습문제

practice01.jsp

01 세션은 클라이언트와 웹 서버 간의 상태를 지속적으로 유지하는 방법을 말한다. 세션은 웹 서버에서만 접근이 가능하므로 보안 유지에 유리하며 데이터를 저장하는 데 한계가 없다. 세션은 오직 웹 서버에 존재하는 객체로 웹 브라우저마다 하나씩 존재하므로 웹 서버의 서비스를 제공받는 사용자를 구분하는 단위가 된다. 02 세션 생성은 session 내장 객체의 setAttribute() 메소드를 사용한다. 세션에 저장된 하나의 속성 이름을 삭제하려면 removeAttribute() 메소드를 사용한다. 세션에 저장된 모든 세션 속성 이름을 삭제하려면 invalidate() 메소드를 사용한다. 03 세션에 저장된 하나의 세션 속성 이름에 대한 속성 값을 얻어오려면 getAttribute() 메소드를 사용한다. 세션에 저장된 여러 개의 세션 속성 이름에 대한 속성 값을 얻어오려면 getAttributeNames() 메소드를 사용한다.

practice04.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Session</title> </head> <body> <form action="practice04_process.jsp" method="post"> <p> 아이디: <input type="text" name="id"> <p> 비밀번호: <input type="text" name="passwd"> <p> <input type="submit" value="전송"> </form> </body> </html>

practice04_process.jsp

<%@ page contentType="text/html; charset=utf-8"%> <html> <head> <title>Session</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); response.sendRedirect("practice04_welcome.jsp"); }else{ response.sendRedirect("practice04.jsp"); } %> </body> </html>

practice04_welcome.jsp

<%@ page contentType="text/html; charset=utf-8"%> <% String userid = (String) session.getAttribute("userID"); if (userid == null) { response.sendRedirect("practice04_session_out.jsp"); } %> <h3><%=userid%>님 반갑습니다. </h3> <a href="practice04_session_out.jsp">로그아웃</a>

practice04_session_out.jsp

<%@ page contentType="text/html; charset=utf-8"%> <% session.invalidate(); response.sendRedirect("practice04.jsp"); %>

practice05

Book.java

package dto; import java.io.Serializable; public class Book implements Serializable { private static final long serialVersionUID = -8581217587295757890L; private String bookId; private String name; private Integer unitPrice; private String author; private String description; private String publisher; private String category; private long unitsInStock; private long totalPages; private String releaseDate; private String condition; private String filename; private int quantity; public Book() { super(); } public Book(String bookId, String name, Integer unitPrice) { super(); this.bookId = bookId; this.name = name; this.unitPrice = unitPrice; } public String getBookId() { return bookId; } public void setBookId(String bookId) { this.bookId = bookId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getUnitPrice() { return unitPrice; } public void setUnitPrice(Integer unitPrice) { this.unitPrice = unitPrice; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public long getUnitsInStock() { return unitsInStock; } public void setUnitsInStock(long unitsInStock) { this.unitsInStock = unitsInStock; } public long getTotalPages() { return totalPages; } public void setTotalPages(long totalPages) { this.totalPages = totalPages; } public String getReleaseDate() { return releaseDate; } public void setReleaseDate(String releaseDate) { this.releaseDate = releaseDate; } public String getCondition() { return condition; } public void setCondition(String condition) { this.condition = condition; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } }

product.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="dto.Book"%> <%@ page import="dao.BookRepository"%> <%@ page errorPage="exceptionNoBookId.jsp" %> <html> <head> <link rel="stylesheet" href="./resources/css/bootstrap.min.css" /> <title>도서 정보</title> </head> <body> <jsp:include page="menu.jsp" /> <div class="jumbotron"> <div class="container"> <h1 class="display-3">도서 정보</h1> </div> </div> <% String id = request.getParameter("id"); BookRepository dao = BookRepository.getInstance(); Book book = dao.getBookById(id); %> <div class="container"> <div class="row"> <div class="col-md-5"> <img src="/upload/<%=book.getFilename()%>" style="width: 100%"> </div> <div class="col-md-6"> <h3><%=book.getName()%></h3> <p><%=book.getDescription()%> <p> <b>도서 코드 : </b><span class="badge badge-danger"> <%=book.getBookId()%></span> <p> <b>출판사</b> : <%=book.getPublisher()%> <p> <b>저자</b> : <%=book.getAuthor()%> <p> <b>재고 수</b> : <%=book.getUnitsInStock()%> <p> <b>총 페이지 수</b> : <%=book.getTotalPages()%> <p> <b>출판일</b> : <%=book.getReleaseDate()%> <h4><%=book.getUnitPrice()%>원 </h4> <p> <form name="addForm" action="./addCart.jsp?id=<%=book.getBookId()%>" method="post"> <a href="#" class="btn btn-info" onclick="addToCart()"> 도서 주문 &raquo;</a> <a href="./cart.jsp" class="btn btn-warning"> 장바구니 &raquo;</a> <a href="./books.jsp" class="btn btn-secondary">도서 목록 &raquo;</a> </form> </div> </div> <hr> </div> <jsp:include page="footer.jsp" /> <script> function addToCart() { if (confirm("상품을 장바구니에 추가하시겠습니까?")) { document.addForm.submit(); } else { document.addForm.reset(); } } </script> </body> </html>

addCart.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="java.util.ArrayList"%> <%@ page import="dto.Book"%> <%@ page import="dao.BookRepository"%> <% String id = request.getParameter("id"); if (id == null || id.trim().equals("")) { response.sendRedirect("products.jsp"); return; } BookRepository dao = BookRepository.getInstance(); Book book = dao.getBookById(id); if (book == null) { response.sendRedirect("exceptionNoProductId.jsp"); } ArrayList<Book> goodsList = dao.getAllBooks(); Book goods = new Book(); for (int i = 0; i < goodsList.size(); i++) { goods = goodsList.get(i); if (goods.getBookId().equals(id)) { break; } } ArrayList<Book> list = (ArrayList<Book>) session.getAttribute("cartlist"); if (list == null) { list = new ArrayList<Book>(); session.setAttribute("cartlist", list); } int cnt = 0; Book goodsQnt = new Book(); for (int i = 0; i < list.size(); i++) { goodsQnt = list.get(i); if (goodsQnt.getBookId().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 contentType="text/html; charset=utf-8"%> <%@ page import="java.util.ArrayList"%> <%@ page import="dto.Book"%> <%@ page import="dao.BookRepository"%> <html> <head> <link rel="stylesheet" href="./resources/css/bootstrap.min.css" /> <% String cartId = session.getId(); %> <title>장바구니</title> </head> <body> <jsp:include page="menu.jsp" /> <div class="jumbotron"> <div class="container"> <h1 class="display-3">장바구니</h1> </div> </div> <div class="container"> <div class="row"> <table width="100%"> <tr> <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="table table-hover"> <tr> <th>상품</th> <th>가격</th> <th>수량</th> <th>소계</th> <th>비고</th> </tr> <% int sum = 0; ArrayList<Book> cartList = (ArrayList<Book>) session.getAttribute("cartlist"); if (cartList == null) cartList = new ArrayList<Book>(); for (int i = 0; i < cartList.size(); i++) { // 상품리스트 하나씩 출력하기 Book book = cartList.get(i); int total = book.getUnitPrice() * book.getQuantity(); sum = sum + total; %> <tr> <td><%=book.getBookId()%> - <%=book.getName()%></td> <td><%=book.getUnitPrice()%></td> <td><%=book.getQuantity()%></td> <td><%=total%></td> <td><a href="./removeCart.jsp?id=<%=book.getBookId()%>" class="badge badge-danger">삭제</a></td> </tr> <% } %> <tr> <th></th> <th></th> <th>총액</th> <th><%=sum%></th> <th></th> </tr> </table> <a href="./books.jsp" class="btn btn-secondary"> &laquo; 쇼핑 계속하기</a> </div> <hr> </div> <jsp:include page="footer.jsp" /> </body> </html>

removeCart.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="java.util.ArrayList"%> <%@ page import="dto.Book"%> <%@ page import="dao.BookRepository"%> <% String id = request.getParameter("id"); if (id == null || id.trim().equals("")) { response.sendRedirect("products.jsp"); return; } BookRepository dao = BookRepository.getInstance(); Book product = dao.getBookById(id); if (product == null) { response.sendRedirect("exceptionNoBookId.jsp"); } ArrayList<Book> cartList = (ArrayList<Book>) session.getAttribute("cartlist"); Book goodsQnt = new Book(); for (int i = 0; i < cartList.size(); i++) { goodsQnt = cartList.get(i); if (goodsQnt.getBookId().equals(id)) { cartList.remove(goodsQnt); } } response.sendRedirect("cart.jsp"); %>

deleteCart.jsp

<%@ page contentType="text/html; charset=utf-8"%> <%@ page import="dto.Book"%> <%@ page import="dao.BookRepository"%> <% String id = request.getParameter("cartId"); if (id == null || id.trim().equals("")) { response.sendRedirect("cart.jsp"); return; } session.invalidate(); response.sendRedirect("cart.jsp"); %>
 

결론

해당 코드를 작성하면서 세션의 개념, 세션을 생성하는 방법, 세션 정보를 가져오는 방법, 세션을 삭제하는 방법, 세션 유효 시간을 설정하는 방법을 익힐 수 있었다.
Share article

More articles

See more posts
RSSPowered by inblog