<%@page import="kr.or.ddit.dao.ProductRepository"%>
<%@page import="kr.or.ddit.vo.ProductVO"%>
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
// 열거형으로 값을 가지고 있음 (약속임), getParameterNames를 사용할 때는 Enumeration 필수.
Enumeration en = request.getParameterNames();
while(en.hasMoreElements()) {
String name = (String)en.nextElement();
String value = request.getParameter(name);
out.print("<h5>" + name + " : " + value + "</h5>");
}
// 파라미터 value의 타입은 String
String productId = request.getParameter("productId");
String pname = request.getParameter("pname");
String unitPrice = request.getParameter("unitPrice");
String description = request.getParameter("description");
String manufacturer = request.getParameter("manufacturer");
String category = request.getParameter("category");
String unitsInStock = request.getParameter("unitsInStock");
String condition = request.getParameter("condition");
String filename = request.getParameter("filename");
String quantity = request.getParameter("quantity");
//unitPrice
double price = 0d;
//unitsInStock
double stock = 0d;
price = Double.parseDouble(unitPrice);
stock = Double.parseDouble(unitsInStock);
ProductVO productVO = new ProductVO();
productVO.setProductId(productId); // P1237
productVO.setPname(pname); // 키보드
productVO.setUnitPrice(price); // 30000
productVO.setDescription(description); // 좋은 키보드
productVO.setManufacturer(manufacturer); // Samsung
productVO.setCategory(category); // 주변기기
productVO.setUnitsInStock(stock); // 4
productVO.setCondition(condition); // Old
productVO.setFilename(productId+".jpg"); // P1237.jpg
out.print("<p>productVO : " + productVO + "</p>");
// 싱글톤 객체로 생성
ProductRepository dao = ProductRepository.getInstance();
dao.addProduct(productVO);
// 목록으로 이동
response.sendRedirect("products.jsp");
%>
6장 참조
https://forest-of-coding.tistory.com/182
[스프링] 6장 쇼핑몰 시스템
사전 준비 테이블 생성 --상품 정보 CREATE TABLE PRODUCT( PRODUCT_ID VARCHAR2(10), PNAME VARCHAR2(90), UNIT_PRICE NUMBER, DESCRIPTION VARCHAR2(3000), MANUFACTURER VARCHAR2(90), CATEGORY VARCHAR2(60), UNITS_IN_STOCK NUMBER, CONDITION VARCHAR2(60)
forest-of-coding.tistory.com
위의 페이지에 이어서 쇼핑몰 시스템을 개발한다.
products.jsp
<%@page import="kr.or.ddit.vo.ProductVO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="kr.or.ddit.dao.ProductRepository"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!-- 페이지 디렉티브 -->
<% //스크립틀릿
//ProductRepository() 생성자
//기본 생성자. 3개의 상품 정보를 설정.
//그런 후 Product 객체 타입의 List인 listOfProducts 변수에 저장
//ProductRepository productDAO = new ProductRepository();
ProductRepository productDAO = ProductRepository.getInstance();
// ProductVO 제네릭 List 타입의 객체로 모든 상품 목록을 할당함
List<ProductVO> productVOList = productDAO.getAllProducts();
//out.print("<p>productVOList : " + productVOList + "</p>");
%>
<!-- java 객체 -> JSTL 변수 -->
<c:set var="productVOList" value="<%=productVOList%>" />
<!DOCTYPE html>
<html>
<head>
<!-- <link rel="stylesheet" -->
<!-- href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> -->
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title></title>
</head>
<body>
<!-- include 액션 태그 -->
<jsp:include page="menu.jsp" />
<div class="jumbotron">
<div class="container">
<h1 class="display-3">상품 목록</h1>
</div>
</div>
<!-- 상품목록 출력 -->
<div class="container">
<div class="row" align="center">
<c:forEach var="productVO" items="${productVOList}" varStatus="stat">
<div class="col-md-4">
<!-- /images/P1234.jpg -->
<img src="/images/${productVO.filename}"
style="width:100%;" alt="${productVO.pname}" title="${productVO.pname}"/>
<h3>${productVO.pname}</h3>
<p>${productVO.description}</p>
<p>${productVO.unitPrice}</p>
<!--
요청URI : product.jsp
요청파라미터 : productId=P1234
요청방식 : get(목록, 검색, 상세)
-->
<p><a href="product.jsp?productId=${productVO.productId}"
class="btn btn-secondary" role="button">상세정보»</a></p>
</div>
</c:forEach>
</div>
</div>
<jsp:include page="footer.jsp" />
</body>
</html>
product.jsp
<%@page import="kr.or.ddit.vo.ProductVO"%>
<%@page import="kr.or.ddit.dao.ProductRepository"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
/*
요청URI : product.jsp
요청파라미터 : productId=P1234
요청방식 : get(목록, 검색, 상세)
*/
// 싱글톤
ProductRepository productDAO =
ProductRepository.getInstance();
String productId = request.getParameter("productId"); // P1234
out.print("<p>"+productId+"</p>"); // P1234
ProductVO productVO = productDAO.getProductById(productId);
out.print("<p>"+productVO+"</p>");
%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title></title>
</head>
<body>
<!-- include 액션 태그 -->
<jsp:include page="menu.jsp" /> <!-- 파라미터가 없기 때문에 이렇게 사용 가능 -->
<!-- --------------------상품상세 시작-------------------- -->
<div class="jumbotron">
<!-- container : 이 안에 내용있다 -->
<div class="container">
<h1 class="display-3">상품 정보</h1>
</div>
</div>
<!-- 내용 -->
<div class="container">
<div class="row">
<div class="col-md-5">
<img src="/images/<%=productVO.getFilename()%>"
style="width:100%;">
</div>
<div class="col-md-6">
<h3><%=productVO.getPname()%></h3>
<p><%=productVO.getDescription()%></p>
<p>
<b>상품 코드 : </b>
<span class="badge bage-danger">
<%=productVO.getProductId()%>
</span>
</p>
<p><b>제조사 : </b><%=productVO.getManufacturer()%></p>
<p><b>분류 : </b><%=productVO.getCategory()%></p>
<p><b>재고 수 : </b><%=productVO.getUnitsInStock()%></p>
<h4><%=productVO.getUnitPrice()%></h4>
<p>
<!-- 폼태그, 폼페이지
action : 요청URI
요청URI : addCart.jsp
요청파라미터 : id=P1234
요청방식 : post
-->
<form name="addForm" action="addCart.jsp?productId=<%=productVO.getProductId()%>"
method="post">
<!-- 폼데이터 -->
<!-- 상품 주문 : 장바구니에 상품을 넣음
addToCart() : 핸들러 함수
-->
<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>
</form>
</div>
</div>
</div>
<jsp:include page="footer.jsp" />
</body>
</html>
ProductRepository.java
package kr.or.ddit.dao;
import java.util.ArrayList;
import java.util.List;
import kr.or.ddit.vo.ProductVO;
public class ProductRepository {
// 싱글톤 패턴(공유, 객체가 1회 생성)
private static ProductRepository instance = new ProductRepository();
public static ProductRepository getInstance() {return instance;}
//상품 목록을 저장할 리스트 작성(전역변수)
//인터페이스 : 팀장
//구현클래스 : 팀원들
private List<ProductVO> listOfProducts = new ArrayList<ProductVO>();
// 기본 생성자, 3개의 상품 정보를 설정
private ProductRepository() {
// 스마트폰
ProductVO phone = new ProductVO("P1234", "iPhone 6s", 800000);
//상품 설명
phone.setDescription("4.7-inch, 1334x750 Renina HD display."
+ "8-megapixel iSight Camera");
//분류
phone.setCategory("Smart Phone");
//제조사
phone.setManufacturer("Apple");
//재고 수
phone.setUnitsInStock(1000);
//신상품 or 중고품 or 재생품
phone.setCondition("New");
//이미지 파일명
phone.setFilename("P1234.jpg");
//-------------------------------스마트폰 등록 끝--------------------------------
//-------------------------------노트북 등록 시작--------------------------------
ProductVO notebook = new ProductVO("P1235", "LG PC 그램", 1500000);
//상품 설명
notebook.setDescription("13.3-inch, IPS LED display, 5rd Generation"
+ "Intel Core processors");
//분류
notebook.setCategory("Notebook");
//제조사
notebook.setManufacturer("LG");
//재고 수
notebook.setUnitsInStock(1000);
//신상품 or 중고품 or 재생품
notebook.setCondition("Refurbished");
//이미지 파일명
notebook.setFilename("P1235.jpg");
//-------------------------------노트북 등록 끝--------------------------------
//-------------------------------태블릿 등록 시작--------------------------------
ProductVO tablet = new ProductVO("P1236", "Galaxy Tab S", 900000);
//상품 설명
tablet.setDescription("212.8*125.6*6.6m, Super AMOLED display, "
+ "Octa-Core processor");
//분류
tablet.setCategory("Tablet");
//제조사
phone.setManufacturer("Samsung");
//재고 수
tablet.setUnitsInStock(1000);
//신상품 or 중고품 or 재생품
tablet.setCondition("Old");
//이미지 파일명
tablet.setFilename("P1236.jpg");
//-------------------------------태블릿 등록 끝--------------------------------
// VO들이 모여서 VO List가 됨
listOfProducts.add(phone);
listOfProducts.add(notebook);
listOfProducts.add(tablet);
}
// SELECT * FROM PRODUCT
// 상품 목록
public List<ProductVO> getAllProducts(){
return listOfProducts;
}
// SELECT * FROM PRODUCT
// WHERE PRODUCT_ID = 'P1234';
// 특정 상품 불러오기(1행 = 1개의 VO = 1개의 상품)
public ProductVO getProductById(String productId) {
ProductVO productById = null;
for(ProductVO productVO : listOfProducts) {
if (productVO.getProductId().equals(productId)) {
productById = productVO;
break;
}
}
return productById;
}
}
등록 화면 추가
products.jsp
<%@page import="kr.or.ddit.vo.ProductVO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="kr.or.ddit.dao.ProductRepository"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!-- 페이지 디렉티브 -->
<% //스크립틀릿
//ProductRepository() 생성자
//기본 생성자. 3개의 상품 정보를 설정.
//그런 후 Product 객체 타입의 List인 listOfProducts 변수에 저장
//ProductRepository productDAO = new ProductRepository();
ProductRepository productDAO = ProductRepository.getInstance();
// ProductVO 제네릭 List 타입의 객체로 모든 상품 목록을 할당함
List<ProductVO> productVOList = productDAO.getAllProducts();
//out.print("<p>productVOList : " + productVOList + "</p>");
%>
<!-- java 객체 -> JSTL 변수 -->
<c:set var="productVOList" value="<%=productVOList%>" />
<!DOCTYPE html>
<html>
<head>
<!-- <link rel="stylesheet" -->
<!-- href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> -->
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title></title>
</head>
<body>
<!-- include 액션 태그 -->
<jsp:include page="menu.jsp" />
<div class="jumbotron">
<div class="container">
<h1 class="display-3">상품 목록</h1>
</div>
</div>
<!-- 상품목록 출력 -->
<div class="container">
<div class="row" align="center">
<c:forEach var="productVO" items="${productVOList}" varStatus="stat">
<div class="col-md-4">
<!-- /images/P1234.jpg -->
<img src="/images/${productVO.filename}"
style="width:100%;" alt="${productVO.pname}" title="${productVO.pname}"/>
<h3>${productVO.pname}</h3>
<p>${productVO.description}</p>
<p>${productVO.unitPrice}</p>
<!--
요청URI : product.jsp
요청파라미터 : productId=P1234
요청방식 : get(목록, 검색, 상세)
-->
<p><a href="product.jsp?productId=${productVO.productId}"
class="btn btn-secondary" role="button">상세정보»</a></p>
</div>
</c:forEach>
</div>
<div class="form-group row">
<div class="col-sm-offset-2 col-sm-10">
<a href="addProduct.jsp" class="btn btn-primary">등록</a>
</div>
</div>
</div>
<jsp:include page="footer.jsp" />
</body>
</html>
addProduct.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title></title>
</head>
<body>
<!-- include 액션 태그 -->
<jsp:include page="menu.jsp" />
<!-- --------------------상품등록 시작-------------------- -->
<div class="jumbotron">
<!-- container : 이 안에 내용있다 -->
<div class="container">
<h1 class="display-3">상품 등록</h1>
</div>
</div>
<!-- 내용 -->
<div class="container">
<!-- 폼태그, 폼페이지 -->
<form name="newProduct" action="processAddProduct.jsp" method="post"
class="form-horizontal">
<div class="form-group row">
<!-- 후보키(N.N, N.D) -> 중 1 속성 선택 -> 기본키(N.N, N.D) -->
<label class="col-sm-2">상품 아이디</label>
<div class="col-sm-3">
<input type="text" id="productId" name="productId"
class="form-controler" placeholder="상품 아이디" required/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">상품 명</label>
<div class="col-sm-3">
<input type="text" id="pname" name="pname"
class="form-controler" placeholder="상품 명" required/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">상품 가격</label>
<div class="col-sm-3">
<input type="number" id="unitPrice" name="unitPrice"
class="form-controler" placeholder="상품 가격" required/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">상품 설명</label>
<div class="col-sm-3">
<input type="text" id="description" name="description"
class="form-controler" placeholder="상품 설명" required/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">제조사</label>
<div class="col-sm-3">
<input type="text" id="manufacturer" name="manufacturer"
class="form-controler" placeholder="제조사"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">분류</label>
<div class="col-sm-3">
<input type="text" id="category" name="category"
class="form-controler" placeholder="분류"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">재고 수</label>
<div class="col-sm-3">
<input type="number" id="unitsInStock" name="unitsInStock"
class="form-controler" placeholder="재고 수"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">제품 상태</label>
<div class="col-sm-5">
<input type="radio" name="condition" value="New" id="condition1"/><label for="condition1">신상품</label>
<input type="radio" name="condition" value="Old" id="condition2"/><label for="condition3">중고</label>
<input type="radio" name="condition" value="Refurbished" id="condition3"/><label for="condition3">재생품</label>
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-primary" value="등록" />
<button type="button" class="btn btn-info"
onclick="javascript:location.href='products.jsp'">목록보기</button>
</div>
</div>
</form>
</div>
<jsp:include page="footer.jsp" />
</body>
</html>
processAddProduct.jsp
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
// 열거형으로 값을 가지고 있음 (약속임), getParameterNames를 사용할 때는 Enumeration 필수.
Enumeration en = request.getParameterNames();
while(en.hasMoreElements()) {
String name = (String)en.nextElement();
String value = request.getParameter(name);
out.print("<h5>" + name + " : " + value + "</h5>");
}
%>
=> 값을 넣고 페이지 이동
<%@page import="kr.or.ddit.dao.ProductRepository"%>
<%@page import="kr.or.ddit.vo.ProductVO"%>
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
// 열거형으로 값을 가지고 있음 (약속임), getParameterNames를 사용할 때는 Enumeration 필수.
Enumeration en = request.getParameterNames();
while(en.hasMoreElements()) {
String name = (String)en.nextElement();
String value = request.getParameter(name);
out.print("<h5>" + name + " : " + value + "</h5>");
}
// 파라미터 value의 타입은 String
String productId = request.getParameter("productId");
String pname = request.getParameter("pname");
String unitPrice = request.getParameter("unitPrice");
String description = request.getParameter("description");
String manufacturer = request.getParameter("manufacturer");
String category = request.getParameter("category");
String unitsInStock = request.getParameter("unitsInStock");
String condition = request.getParameter("condition");
String filename = request.getParameter("filename");
String quantity = request.getParameter("quantity");
//unitPrice
double price = 0d;
//unitsInStock
double stock = 0d;
price = Double.parseDouble(unitPrice);
stock = Double.parseDouble(unitsInStock);
ProductVO productVO = new ProductVO();
productVO.setProductId(productId); // P1237
productVO.setPname(pname); // 키보드
productVO.setUnitPrice(price); // 30000
productVO.setDescription(description); // 좋은 키보드
productVO.setManufacturer(manufacturer); // Samsung
productVO.setCategory(category); // 주변기기
productVO.setUnitsInStock(stock); // 4
productVO.setCondition(condition); // Old
out.print("<p>productVO : " + productVO + "</p>");
// 싱글톤 객체로 생성
ProductRepository dao = ProductRepository.getInstance();
dao.addProduct(productVO);
// 목록으로 이동
response.sendRedirect("products.jsp");
%>
파일 첨부
jquery 사용
addProduct.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<title></title>
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script type="text/javascript">
// 동일 jsp 내에 1개의 달러function
// document 내의 모든 요소들이 로딩된 후에 실행
$(function(){
console.log("개똥이");
// object를 선택(<input type="file" ..)
$("#productImage").on("change", handleImg);
// e : onchange 이벤트
function handleImg(e) {
console.log("파일 선택 이벤트");
//e.target : <input type="file" id="productImage" name="productImage" class="form-control"...
let files = e.target.files; // 파일들
// fileArr = [a.jpg, b.jpg, c.jpg]
let fileArr = Array.prototype.slice.call(files);
// f : 파일(a.jpg)
fileArr.forEach(function(f) {
// 이미지 체킹 (MIME타입)
if(!f.type.match("image.*")) {
alert("이미지만 가능합니다.");
return; // handleImg함수 자체를 종료
}
// 이미지가 맞다면
let reader = new FileReader();
//e : reader가 이미지 객체를 읽는 이벤트
reader.onload = function(e) {
let img_html = "<img src='" + e.target.result + "' style='width:100%' />";
// <p id="pImg"><img src='oewrpasdofiasdo..' ../></p>
// 요소.append : 누적, 요소.html : 새로고침 , 요소.innerHTML : Javascript에서 새로고침
$("#pImg").append(img_html);
}
reader.readAsDataURL(f);
});
}
});
</script>
</head>
<body>
<!-- include 액션 태그 -->
<jsp:include page="menu.jsp" />
<!-- --------------------상품등록 시작-------------------- -->
<div class="jumbotron">
<!-- container : 이 안에 내용있다 -->
<div class="container">
<h1 class="display-3">상품 등록</h1>
</div>
</div>
<!-- 내용 -->
<div class="container">
<!-- 폼태그, 폼페이지 -->
<form name="newProduct" action="processAddProduct.jsp" method="post"
class="form-horizontal">
<div class="form-group row">
<!-- 후보키(N.N, N.D) -> 중 1 속성 선택 -> 기본키(N.N, N.D) -->
<label class="col-sm-2">상품 아이디</label>
<div class="col-sm-3">
<input type="text" id="productId" name="productId"
class="form-controler" placeholder="상품 아이디" required/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">상품 명</label>
<div class="col-sm-3">
<input type="text" id="pname" name="pname"
class="form-controler" placeholder="상품 명" required/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">상품 가격</label>
<div class="col-sm-3">
<input type="number" id="unitPrice" name="unitPrice"
class="form-controler" placeholder="상품 가격" required/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">상품 설명</label>
<div class="col-sm-3">
<input type="text" id="description" name="description"
class="form-controler" placeholder="상품 설명" required/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">제조사</label>
<div class="col-sm-3">
<input type="text" id="manufacturer" name="manufacturer"
class="form-controler" placeholder="제조사"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">분류</label>
<div class="col-sm-3">
<input type="text" id="category" name="category"
class="form-controler" placeholder="분류"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">재고 수</label>
<div class="col-sm-3">
<input type="number" id="unitsInStock" name="unitsInStock"
class="form-controler" placeholder="재고 수"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">제품 상태</label>
<div class="col-sm-5">
<input type="radio" name="condition" value="New" id="condition1"/><label for="condition1">신상품</label>
<input type="radio" name="condition" value="Old" id="condition2"/><label for="condition3">중고</label>
<input type="radio" name="condition" value="Refurbished" id="condition3"/><label for="condition3">재생품</label>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">제품 이미지</label>
<div class="col-sm-5">
<p id="pImg"></p>
<input type="file" id="productImage" name="productImage" class="form-control"
placeholder="제품 이미지" multiple/>
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-primary" value="등록" />
<button type="button" class="btn btn-info"
onclick="javascript:location.href='products.jsp'">목록보기</button>
</div>
</div>
</form>
</div>
<jsp:include page="footer.jsp" />
</body>
</html>
'스프링' 카테고리의 다른 글
[스프링] 11장 파일 업로드 (0) | 2024.04.09 |
---|---|
[스프링] 10.5장 과제 (0) | 2024.04.08 |
[스프링] 8.5장 과제 (0) | 2024.04.01 |
[스프링] 8장 response 객체 (0) | 2024.04.01 |
[스프링] 7장 내장 객체, request 객체 (0) | 2024.04.01 |