기록
JSP 상품등록 + 파일업로드 추가5 본문
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!-- 상품정보를 등록하는 페이지 만들기 -->
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css" />
<script type="text/javascript" src="/ckeditor/ckeditor.js"></script>
<title>상품 등록</title>
</head>
<body>
<jsp:include page="menu.jsp"></jsp:include>
<div class="jumbotron">
<div class="container">
<h1 class="display-3">상품등록</h1>
</div>
</div>
<div class="container">
<!-- 폼페이지 시작 -->
<form name="newProduct" id="newProduct" action="processAddProduct.jsp"
class="form-horizontal" method="post" enctype="multipart/form-data">
<!-- 가로방향(행=로우=튜플=레코드) -->
<div class="form-group row">
<label class="col-sm-2">상품코드</label>
<div class="col-sm-3">
<input type="text" name="productId" class="form-control" required/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">상품명</label>
<div class="col-sm-3">
<input type="text" name="pname" class="form-control" required/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">가격</label>
<div class="col-sm-3">
<input type="text" name="unitPrice" class="form-control" required/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">상세정보</label>
<div>
<!-- 세로 : cols, 가로 : rows -->
<textarea class="form-control" cols="100" rows="2" id="description" name="description"></textarea>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">제조사</label>
<div class="col-sm-3">
<input type="text" name="manufacturer" class="form-control"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">분류</label>
<div class="col-sm-3">
<input type="text" name="category" class="form-control"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">재고 수</label>
<div class="col-sm-3">
<input type="number" name="unitsInStock" class="form-control"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">상태</label>
<div class="col-sm-5">
<input type="radio" id="New" name="condition" value="New" checked/>
<label for="new">신규제품</label>
<input type="radio" id="Old" name="condition" value="Old"/>
<label for="old">중고제품</label>
<input type="radio" id="Refurbished" name="condition" value="Refurbished"/>
<label for="Refurbished">재생제품</label>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">이미지</label>
<div class="col-sm-5">
<input type="file" name="productImage" class="form-control">
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-2 col-sm-10">
<!-- <button type="submit" .. </button> -->
<input type="submit" class="btn btn-primary" value="등록"/>
<input type="reset" class="btn btn-danger" value="초기화"/>
<input type="button" class="btn btn-success" value="목록"
onclick="javascript:location.href='products.jsp'" />
</div>
</div>
</form>
<!-- 폼페이지 끝 -->
</div>
<script>
CKEDITOR.replace('description');
</script>
<jsp:include page="footer.jsp"></jsp:include>
</body>
</html>
상품 등록 폼을 추가한다.
<div class="form-group row">
<label class="col-sm-2">이미지</label>
<div class="col-sm-5">
<input type="file" name="productImage" class="form-control">
</div>
</div>
processAddProduct.jsp로 넘긴후,
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page import="kr.or.ddit.dao.ProductRepository"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="org.apache.commons.fileupload.DiskFileUpload"%>
<%@page import="kr.or.ddit.vo.ProductVO"%>
<% //스크립틀릿
request.setCharacterEncoding("UTF-8");
String productId= "";
String pname = "";
String unitPrice = "";
String description ="";
String manufacturer ="";
String category = "";
String unitsInStock= "";
String condition = "";
double price = 0d;
long stock=0L;
String fileName = "";
//파일 업로드 처리하기
//1. (복사할)업로드 될 위치 설정
String path = "D:\\A_TeachingMaterial\\04_MiddelProject\\workspace\\JSPBook\\WebContent\\images";
//2.
DiskFileUpload upload = new DiskFileUpload();
upload.setSizeMax(1000000); //최대크기
upload.setSizeThreshold(4096); //메모리 최대
upload.setRepositoryPath(path); //임시저장
//request내장 객체에 들어있는 폼데이터들을 구문/의미 분석
List items = upload.parseRequest(request);
Iterator params = items.iterator(); //열거형
while(params.hasNext()){
//object(중국집) => FileItem(짜장면)
FileItem item = (FileItem)params.next();
if(item.isFormField()){ //일반요소
//productId=P1238&pname=삼성폴더블폰 일시
//getFieldName 은 productId, pname 을 가져옴
String name = item.getFieldName();
if(name.equals("productId")){
productId= item.getString("utf-8");
}else if(name.equals("pname")){
pname = item.getString("utf-8");
}else if(name.equals("unitPrice")){
unitPrice = item.getString("utf-8");
/* 1) unitPrice는 문자형 데이터 -> 숫자형 변환
double : 실수형(소수자리..) */
//만약 상품가격이 입력이 안되었다면 ...
if(unitPrice.isEmpty()){
price=0d;
}else{ //그게아니면 정수형으로 변경
price=Double.parseDouble(unitPrice);
/* price=Double.valueOf(unitPrice); */
}
}else if(name.equals("description")){ //상세내용
description = item.getString("utf-8");
}else if(name.equals("manufacturer")){
manufacturer = item.getString("utf-8");
}else if(name.equals("category")){
category = item.getString("utf-8");
}else if(name.equals("unitsInStock")){
unitsInStock = item.getString("utf-8");
// 2)unitsInStock(재고수)는 문자형 데이터 -> long(정수형)
if(unitsInStock.isEmpty()){
stock=0L;
}else{
stock = Long.valueOf(unitsInStock);
}
}else if(name.equals("condition")){
condition = item.getString("utf-8");
}
}else{ //파일객체
// <input type="file" name="productImage" class="form-control">
String fileFieldName = item.getFieldName();
//c:_user_sem-pc_fictures_p1234.jpg 사진의 전체 경로를 가져옴 -> getName
fileName=item.getName();
String contentType = item.getContentType(); //images/jped(mine타입)
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
long fileSize = item.getSize();
//설계 : 복사할 위치 및 파일명 결합 연산
File file = new File(path+"/"+fileName);
//복사처리
//원본.복사(대상)
item.write(file);
}
}
%>
<p>productId : <%=productId%> </p>
<p>pname : <%=pname %> </p>
<p>unitPrice : <%=price %> </p>
<p>description : <%=description %> </p>
<p>manufacturer: <%=manufacturer%> </p>
<p>category : <%=category %> </p>
<p>unitsInStock: <%= stock%> </p>
<p>condition : <%= condition%> </p>
<%
ProductRepository dao = ProductRepository.getInstance();
ProductVO productVO = new ProductVO();
productVO.setProductId(productId);
productVO.setPname(pname);
productVO.setUnitPrice(price); //DOUBLE형
productVO.setDescription(description);
productVO.setManufacturer(manufacturer);
productVO.setCategory(category);
productVO.setUnitsInStock(stock); //LONG형
//상품 이미지 처리 --> P1237.jpg -> images폴더에 넣어주면 됨.
productVO.setFilename(fileName);
dao.addProduct(productVO);
//response내장객체의 sendRedirect메소드를 사용하여 상품 목록 페이지로 이동
response.sendRedirect("products.jsp");
%>
<p>productVO : <%= productVO.toString()%></p>
'JSP' 카테고리의 다른 글
JSP 유효성검사 (validation) 2 글자수 유효성 검사 (0) | 2023.01.06 |
---|---|
JSP 유효성검사 (validation) 1 (0) | 2023.01.05 |
JSP 상품 등록 후 자동 새로고침 설정 (0) | 2023.01.05 |
JSP 파일업로드 4 (숙제) (2) | 2023.01.04 |
JSP 파일업로드 3 (0) | 2023.01.04 |
Comments