addProduct.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="kr.or.ddit.vo.ProductVO"%>
<%@ page import="java.util.ArrayList"%>
<%@ page import="kr.or.ddit.dao.ProductRepository"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/bootstrap.min.css">
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script type="text/javascript" src="/js/validation2.js"></script>
<title>상품 등록</title>
<script type="text/javascript">
//document내 모든 요소 로딩 후 실행
$(function(){
$("input[name='productImage']").on("change",hangleImg);
});
function hangleImg(e){
let files = e.target.files;
let fileArr = Array.prototype.slice.call(files);
fileArr.forEach(function(f){
if(!f.type.match("image.*")){
alert("이미지 확장자만 가능합니다.");
return;
}
//통과 시
let reader = new FileReader();
reader.onload = function(e){
let img_html = "<img src='"+e.target.result+"'style='width:100%' />";
$("#divImg").html(img_html);
}
reader.readAsDataURL(f);
})
}
</script>
</head>
<body>
<!--
value="en" => bundle.message_en.properties를 사용
value="ko" => bundle.message_ko.properties를 사용
bundle.message.properties
우리의 지역locale은 ko임
-->
<fmt:setLocale value="ko"/>
<!--
bundle : src>bundle
message : message.properties 파일의 명
message_en.properties
message(_ko).properties
-->
<fmt:bundle basename="bundle.message">
<%@ include file="menu.jsp"%>
<!-- /// 상품 목록 시작 /// -->
<div class="jumbotron">
<div class="container">
<h1 class="display-3"><fmt:message key="title" /> </h1>
</div>
</div>
<div class="container">
<!--
요청URI : processAddProduct.jsp
요청파라미터 : request{productId=P1237,pname=노트북 울트라,unitPrice=1200000,
description=노트북 울트라는 좋다,manufacturer=Samsung,
category=notebook,unitsInStock=1000,condition=New,
productImage=파일객체}
요청방식 : post
-->
<form name="newProduct" action="processAddProduct.jsp"
class="form-horizontal" method="post"
enctype="multipart/form-data">
<div class="form-group row">
<label class="col-sm-2"><fmt:message key="productId" /> </label>
<div class="col-sm-3" style="width:25%;">
<input type="text" name="productId" class="form-control"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2"><fmt:message key="pname"/></label>
<div class="col-sm-3" style="width:25%;">
<input type="text" name="pname" class="form-control"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2"><fmt:message key="unitPrice"/></label>
<div class="col-sm-3" style="width:25%;">
<input type="number" name="unitPrice" class="form-control"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2"><fmt:message key="description"/></label>
<div class="col-sm-5" style="width:41%;">
<textarea cols="50" rows="2" name="description" class="form-control"></textarea>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2"><fmt:message key="manufacturer"/></label>
<div class="col-sm-3" style="width:25%;">
<input type="text" name="manufacturer" class="form-control"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2"><fmt:message key="category"/></label>
<div class="col-sm-3" style="width:25%;">
<input type="text" name="category" class="form-control"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2"><fmt:message key="unitsInStock"/></label>
<div class="col-sm-3" style="width:25%;">
<input type="number" name="unitsInStock" class="form-control"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2"><fmt:message key="condition"/></label>
<div class="col-sm-5" style="width:41%;">
<input type="radio" id="condition1" name="condition" value="new"/>
<label for ="condition1"><fmt:message key="condition_New"/></label>
<input type="radio" id="condition2" name="condition" value="old"/>
<label for ="condition2"><fmt:message key="condition_Old"/></label>
<input type="radio" id="condition3" name="condition" value="refurbished"/>
<label for ="condition3"><fmt:message key="condition_Refurbished"/></label>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2"><fmt:message key="productImage"/></label>
<div class="col-sm-5" style="width:41%;">
<input type="file" name="productImage" class="form-control" />
</div>
<div class="col-sm-5" style="width:41%;" id="divImg">
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-2 col-sm-10">
<!-- CheckAddProduct() : 핸들러 함수 -->
<input type="button" class="btn btn-primary" value="<fmt:message key='button'/>"
onclick="CheckAddProduct()" />
</div>
</div>
<hr />
</form>
</div>
<!-- /// 상품 목록 끝 /// -->
<%@ include file="footer.jsp"%>
</fmt:bundle>
</body>
</html>
[상품 데이터 접근 클래스 만들기]
processAddProduct.jsp
<%@page import="java.io.File"%>
<%@page import="java.util.UUID"%>
<%@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.dao.ProductRepository"%>
<%@page import="kr.or.ddit.vo.ProductVO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="java.util.Enumeration"%>
<!--
요청URI : processAddProduct.jsp
요청파라미터 : request{productId=P1237,pname=노트북 울트라,unitPrice=1200000,
description=노트북 울트라는 좋다,manufacturer=Samsung,
category=notebook,unitsInStock=1000,condition=New,
productImage=파일객체}
요청방식 : post
-->
<%
request.setCharacterEncoding("UTF-8");
//윈도우 경로 : 역슬러시 두 개
String path = "D:\\A_TeachingMaterial\\jsp\\workspace\\JSPBook\\WebContent\\images";
//commons-fileupload.jar 안에 해당 클래스가 있음
DiskFileUpload upload = new DiskFileUpload();
//업로드 할 파일의 최대 크기
upload.setSizeMax(5000000); //5Mbyte
//메모리에 저장할 최대 크기
upload.setSizeThreshold(5*4096);//5 * 1024 * 1024 => 5Mbyte
//업로드할 파일을 임시로 저장할 경로(폴더가 없으면 자동으로 폴더생성)
upload.setRepositoryPath(path);
/*요청파라미터 : request{productId=P1237,pname=노트북 울트라,unitPrice=1200000,
description=노트북 울트라는 좋다,manufacturer=Samsung,
category=notebook,unitsInStock=1000,condition=New,
productImage=파일객체}
*/
//parse : 구문분석(오류체크), 의미분석, 변환
List items = upload.parseRequest(request);
//요청 파라미터들을 Iterator(열거) 클래스로 변환
Iterator params = items.iterator();
ProductVO productVO = new ProductVO();
//요청 파라미터가 없어질때까지 반복(1회 반복)
while(params.hasNext()){//돌다리도 두드려본 후 돌이 있으면
//FileItem : 1) 일반 데이터(text, radio, checkbox..) (0)
// 2) 파일(file) (1)
FileItem item = (FileItem)params.next(); //그 돌을 밟고 건너자
/*요청파라미터 : request{productId=P1237,pname=노트북 울트라,unitPrice=1200000,
description=노트북 울트라는 좋다,manufacturer=Samsung,
category=notebook,unitsInStock=1000,condition=New,
productImage=파일객체}
*/
//isFormField() -> true(일반데이터(text, radio, checkbox,..))
if(item.isFormField()){
//{memMail=test@test.com,password=java,remember-me=on}
String name = item.getFieldName(); //memMail, password, remember-me
String value = item.getString("UTF-8"); //test@test.com, java, on
out.print(name + "=" + value + "<br />");
if(name.equals("productId")){
productVO.setProductId(value);
}else if(name.equals("pname")){
productVO.setPname(value);
}else if(name.equals("unitPrice")){
productVO.setUnitPrice(Long.valueOf(value));
}else if(name.equals("description")){
productVO.setDescription(value);
}else if(name.equals("manufacturer")){
productVO.setManufacturer(value);
}else if(name.equals("category")){
productVO.setCategory(value);
}else if(name.equals("unitsInStock")){
productVO.setUnitsInStock(Long.valueOf(value));
}else if(name.equals("condition")){
productVO.setCondition(value);
}//end if
}else{// false(파일(input type="file"))
//요청파라미터 : {uploadFile=파일객체} => item
String fileFieldName = item.getFieldName();//productImage
String fileName = item.getName();//업로드 될 파일 명. 송찬중.jpg
//이미지파일이라면 MIME TYPE : image/jpeg
String contentType = item.getContentType();
long fileSize = item.getSize(); //파일의 크기
//만약 fileName => C:\\Users\\SEM\\Pictures\\scj.jpg
// -> scj.jpg
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
//파일명 중복 방지 시작 /////
//java.util.UUID => 랜덤값 생성
UUID uuid = UUID.randomUUID();
//원래의 파일 이름과 구분하기 위해 _를 붙임(asdfsdfa_송찬중.jpg)
fileName = uuid.toString() + "_" + fileName;
//파일명 중복 방지 끝 /////
productVO.setFilename(fileName);
//계획. c:\\upload\\faslsdafj_scj.jpg로 복사해야 함
File file = new File(path + "\\" + fileName);
//복사 실행
//파일객체.write(계획)
item.write(file);
out.print("================<br />");
out.print("요청 파라미터 이름 : " + fileFieldName + "<br />");
out.print("저장 파일 이름 : " + fileName + "<br />");
out.print("파일 콘텐츠 유형 : " + contentType + "<br />");
out.print("파일 크기 : " + fileSize + "<br />");
}
}//end while
out.print("productVO : " + productVO);
//싱글톤 객체로 생성
// ProductRepository dao = ProductRepository.getInstance();
//새로운 상품 등록
// dao.addProduct(productVO);
//목록으로 이동(redirect : url)
// response.sendRedirect("/products.jsp");
%>
결과