본문 바로가기
IT

[쉽게 배우는 JSP 웹프로그래밍] 13장 연습문제 및 솔루션 총정리

by nutrient 2021. 10. 23.
728x90
728x170

1. 세션이란 무엇인가?

세션은 클라이언트와 웹 서버 간의 상태를 지속적으로 유지하는 방법이다. 세션은 웹 서버에서만 접근이 가능하기 때문에 보안에 유리하며, 브라우저마다 하나씩 존재하여 사용자를 구분하는 단위가 된다.


2. JSP 페이지에 세션을 설정하는 메소드, 설정된 세션을 삭제하는 메소드는 무엇인가?

세션을 설정하는 메소드는 setAttribute(String name, Object value)

세션을 삭제하는 메소드는 removeAttribute(String name)


3. 설정된 세션 정보를 얻어오는 메소드에 대해 간단히 설명하시오.

세션 정보 하나에 저장된 속성 값을 얻어오려면 getAttribute(String name) 메소드를 사용하고

여러 개의 세션 속성 이름에 대한 속성 값을 얻어오려면 getAttributeNames() 메소드를 사용한다.


4. 세션을 이용하여 다음 조건에 맞게 JSP 애플리케이션을 만들고 실행 결과를 확인하시오.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Session</title>
</head>
<body>

<form action="session_process.jsp" method="post">
<p> 아이디 : <input type="text" name="id"> 
<p> 비밀번호 : <input type="text" name="passwd">
<input type="submit" value="전송">

</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Session</title>
</head>
<body>

<%
String id = request.getParameter("id");
String pw = request.getParameter("passwd");

if(id.equals("admin") && pw.equals("admin1234")){
	session.setAttribute("userID", id);
	response.sendRedirect("welcome.jsp");
}else{
	out.println("세션 연결에 실패했습니다.");
}
%>

</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Session</title>
</head>
<body>

<%
session.invalidate();
response.sendRedirect("session.jsp");
%>

</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Session</title>
</head>
<body>

<%
String userid = (String)session.getAttribute("userID");

if(userid == null){
	response.sendRedirect("session_out.jsp");
}
%>

<h3><%=userid %>님 반갑습니다.</h3>
<a href="session_out.jsp">로그아웃</a>

</body>
</html>

 

5. 다음 조건에 맞게 도서 웹 쇼핑몰을 위한 웹 애플리케이션을 만들고 실행 결과를 확인하시오.

private int quantity;

public int getQuantity(){
    return quantity;
}
public void setQuantity(int quantity){
    this.quantity = quantity;
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="dto.Product" %>
<%@ page import="dao.ProductRepository" %>
<%@ page errorPage="exceptionNoBookId.jsp" %>
<jsp:useBean id="productDAO" class="dao.ProductRepository" scope="session"/>

<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" href="./resources/css/bootstrap.min.css"/>
<link rel="stylesheet" 
	href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<title>Insert title here</title>
</head>

<script type="text/javascript">
	function addToCart(){
		if(confirm("상품을 장바구니에 추가하시겠습니까?")){
			document.addForm.submit();
		}else{
			document.addForm.reset();
		}
	}
</script>

<body>

	<%@ include file="menu.jsp" %>
	<div class="jumbotron">
		<div class="container">
			<h1 class="display-3">도서 목록</h1>
		</div>
	</div>
	<% 	String id = request.getParameter("id");
		ProductRepository dao = ProductRepository.getInstance();
		Product product = dao.getProductById(id);
	%>
	
	<div class="container">
	<div class="row">
	<div>
		<img src="C:\\Users\\Dynamic Web Project\\WebContent\\resources\\images\\<%=product.getFilename()%>" style="width:20%">
	</div>
		<div class="col-md-12">
			<h3><%=product.getPname()%></h3>
			<p><%=product.getDescription() %>
			<p><b>도서 코드 : </b><span class="badge badge-danger"></span>
				<%=product.getProductId() %>
			<p><b>출판사</b> : <%=product.getPublisher() %>
			<p><b>저자 </b> : <%=product.getAuthor() %>			
			<p><b>재고 수</b> : <%=product.getUnitsInStock() %>
			<p><b>총 페이지 수</b> : <%=product.getTotalPages() %>
			<p><b>출판일</b> : <%=product.getReleaseDate() %>
			<h4><%=product.getUnitPrice() %></h4>
			<p>
			<form name="addForm" action="./addCart.jsp?id=<%=product.getProductId() %>" method="post">
				<a href="#" class="btn btn-info" onclick="addToCart()">상품주문&raquo;</a>
				<a href="./cart.jsp" class="btn btn-warning">장바구니&raquo;</a>
				<a href="./products.jsp" class="btn btn-secondary">상품 목록&raquo;</a>
			</form>
		</div>
	</div>
	</div>
	<%@ include file="footer.jsp" %>

</body>
</html>
<%@ page contentType="text/html; charset=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("exceptionNoBookId.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("carlist");
if(list == null){
	list = new ArrayList<Product>();
	session.setAttribute("carlist", 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);

%>
<%@ 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>


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<%
String cartId = session.getId();
%>
<meta charset="UTF-8">
<title>장바구니</title>
</head>
<body>

<%@ include file="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="./shippingInfo.jspcartId=<%=cartId %>" 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<Product> cartList = (ArrayList<Product>)session.getAttribute("carlist");
			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 += 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="badge badge-danger"> 삭제</a></td>
				
			</tr>
			<%
			}
			%>
			<tr>
				<th></th>
				<th></th>
				<th>총액</th>
				<th><%=sum %></th>
				<th></th>
			</tr>
		</table>
	</div>
	<hr>
</div>
<%@ include file="footer.jsp" %>

</body>
</html>

 

<%@ page contentType="text/html; charset=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("exceptionNoBookId.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");
%>
<%@ page contentType="text/html; charset=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");

%>
 

[쉽게 배우는 JSP 웹프로그래밍] 12장 연습문제 및 솔루션 총정리

1. 필터란 무엇인가? 필터는 클라이언트와 서버 사이에서 request와 response 객체를 먼저 받아 공통적으로 필요한 부분을 처리하는 것을 말한다. 2. Filter 인터페이스에 있는 메소드의 종류와 

tistorysolution.tistory.com

 

 

 

728x90
그리드형

댓글