session을 이용해 장바구니 만들기
2019. 8. 23. 13:20ㆍ프로그래밍/JSP
1.login.jsp
<%@ 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>
<form method="post" action="setProduct.jsp">
<h2 align="center">로그인</h2>
<hr>
<center>
<input type="text" name="user">
<input type="submit" value="로그인">
</center>
</form>
</body>
</html>
2.setProduct.jsp
<%@ 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>
<%
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("user");
session.setAttribute("user", name);
%>
<% if( name ==""){
%>
<script>
alert("다시 로그인 해주세요");
history.back();
</script>
<% }
%>
<h3 align="center">상품 선택</h3>
<hr>
<h4 align="center">
<%= request.getParameter("user") %> 님 환영합니다~~</h4>
<hr>
<center>
<form method=post action="add.jsp">
<select name="product">
<option value="computer">computer</option>
<option value="phone">phone</option>
<option value="camera">camera</option>
<option value="tablet">tablet</option>
</select>
<input type="submit" value="추가">
<br><br>
<a href="checkOut.jsp" >계산</a>
</form>
</center>
</body>
</html>
3.add.jsp
<%-- import 설정 --%>
<%@ page import="java.util.ArrayList" %>
<%@ 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>
<% request.setCharacterEncoding("UTF-8");
ArrayList<String> list = (ArrayList) session.getAttribute("productList");
String productName= request.getParameter("product");
if (session.getAttribute("productList") == null) {
list = new ArrayList<String>();
}
list.add(productName);
session.setAttribute("productList", list);
%>
<script> alert("<%= productName %> 가 추가!"); history.back(); </script>
</body>
</html>
4.checkOut.jsp
<%@ page import = "java.util.ArrayList" %>
<%@ 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>
<% request.setCharacterEncoding("UTF-8"); %>
<% ArrayList<String> list = (ArrayList)session.getAttribute("productList"); %>
<center>
<h2>결과</h2>
<%= session.getAttribute("user") %>님 상품 목록
<hr>
<% if( list == null){ %>
장바구니에 상품이 없습니다.
<% }else {
for(String i : list){
out.println(i); %> <br>
<% }
} %>
</center>
</body>
</html>
실행화면
'프로그래밍 > JSP' 카테고리의 다른 글
간이계산기(JSP > Servlet ) (0) | 2019.08.21 |
---|