관리 메뉴

거니의 velog

231103_JSP 과제 4 본문

대덕인재개발원_웹기반 애플리케이션

231103_JSP 과제 4

Unlimited00 2023. 11. 3. 17:39

[p. 211-213]




[form01.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>
		<link rel="stylesheet" href="/resources/css/bootstrap.min.css" />
	</head>
	<body>
		<form class="container" action="form01_process.jsp" method="post">
			<label for="id">이름 : </label>
			<input class="form-control" type="text" id="id" name="id" /><br />
			<label for="address">주소 : </label>
			<input class="form-control" type="text" id="address" name="address" /><br />
			<label for="id">이메일 : </label>
			<input class="form-control" type="text" id="email" name="email" /><br />
			<button class="btn btn-primary" type="submit">전송</button>
		</form>
	</body>
</html>

[form01_process.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 id = request.getParameter("id");
			String address = request.getParameter("address");
			String email = request.getParameter("email");
			
			StringBuffer sb = new StringBuffer(); // 객체 sb 생성
			sb.append("아이디 : " + id + "<br />");
			sb.append("주소 : " + address + "<br />");
			sb.append("이메일 : " + email + "<br />");
			out.println(sb);
		%>
	</body>
</html>

- http://localhost/ch06/form01.jsp


[form02.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>
		<link rel="stylesheet" href="/resources/css/bootstrap.min.css" />
	</head>
	<body>
		<form class="container" action="form02_process.jsp" method="post">
			<label for="id">이름 : </label>
			<input class="form-control" type="text" id="id" name="id" /><br />
			<label for="address">주소 : </label>
			<input class="form-control" type="text" id="address" name="address" /><br />
			<label for="id">이메일 : </label>
			<input class="form-control" type="text" id="email" name="email" /><br />
			<button class="btn btn-primary" type="submit">전송</button>
		</form>
	</body>
</html>

[form02_process.jsp]

<%@page import="java.util.Enumeration"%>
<%@ 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");
		
			Enumeration paramNames = request.getParameterNames();
			
			String id = "";
			String address = "";
			String email = "";
			
			if (paramNames != null) {
				while(paramNames.hasMoreElements()) {
					String name = (String) paramNames.nextElement();
					if(name.equals("id")) {
						id = request.getParameter(name);
					}else if(name.equals("address")) {
						address = request.getParameter(name);
					}else if(name.equals("email")) {
						email = request.getParameter(name);
					}
				}
			}
			
			StringBuffer sb = new StringBuffer(); // 객체 sb 생성
			sb.append("아이디 : " + id + "<br />");
			sb.append("주소 : " + address + "<br />");
			sb.append("이메일 : " + email + "<br />");
			out.println(sb);
		%>
	</body>
</html>

- http://localhost/ch06/form02.jsp


[form03.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>
		<link rel="stylesheet" href="/resources/css/bootstrap.min.css" />
	</head>
	<body>
		<form class="container" action="form03_process.jsp" method="post">
			<label for="fruit1">오렌지 </label>
			<input id="fruit1" name="fruit" type="checkbox" value="orange" />
			<label for="fruit2">사과 </label>
			<input id="fruit2" name="fruit" type="checkbox" value="apple" />
			<label for="fruit3">바나나 </label>
			<input id="fruit3" name="fruit" type="checkbox" value="banana" />
			&nbsp;
			<button class="btn btn-primary btn-sm" type="submit">전송</button>
		</form>
	</body>
</html>

[form03_process.jsp]

<%@page import="java.util.Enumeration"%>
<%@ 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[] fruits = request.getParameterValues("fruit"); // 모든 선택된 과일을 배열로 가져옴
	
			String orange = "";
			String apple = "";
			String banana = "";
	
			if (fruits != null) {
			    for (String value : fruits) {
			        if (value.equals("orange")) {
			            orange = value;
			        } else if (value.equals("apple")) {
			            apple = value;
			        } else if (value.equals("banana")) {
			            banana = value;
			        }
			    }
			}
	
			StringBuffer sb = new StringBuffer();
			sb.append("<h3>선택한 과일</h3>");
			sb.append(orange + "<br />");
			sb.append(apple + "<br />");
			sb.append(banana + "<br />");
			out.println(sb);
		%>
	</body>
</html>

-http://localhost/ch06/form03.jsp


[addBook.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>도서 등록</title>
		<%@ include file="headSet.jsp" %>
	</head>
	<body>
		<%@ include file="menu.jsp" %>
		<div class="jumbotron">
			<div class="container">
				<h1 class="display-4">도서 정보</h1>
			</div>
		</div>
		<div class="container">
			<form id="addBookForm" name="addBookForm" class="form-horizontal" action="processAddBook.jsp" method="post">
				<div class="form-group row">
					<label for="bookId" class="col-sm-3">도서코드</label>
					<div class="col-sm-9">
						<input type="text" name="bookId" id="bookId" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="name" class="col-sm-3">도서명</label>
					<div class="col-sm-9">
						<input type="text" name="name" id="name" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="unitPrice" class="col-sm-3">가격</label>
					<div class="col-sm-9">
						<input type="text" name="unitPrice" id="unitPrice" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="author" class="col-sm-3">저자</label>
					<div class="col-sm-9">
						<input type="text" name="author" id="author" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="publisher" class="col-sm-3">출판사</label>
					<div class="col-sm-9">
						<input type="text" name="publisher" id="publisher" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="releaseDate" class="col-sm-3">출판일</label>
					<div class="col-sm-9">
						<input type="date" name="releaseDate" id="releaseDate" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="totalPages" class="col-sm-3">총 페이지 수</label>
					<div class="col-sm-9">
						<input type="text" name="totalPages" id="totalPages" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="description" class="col-sm-3">상세 정보</label>
					<div class="col-sm-9">
						<textarea name="description" id="description" class="form-control" style="height: 200px;" wrap="soft"></textarea>
					</div>
				</div>
				<div class="form-group row">
					<label for="category" class="col-sm-3">분류</label>
					<div class="col-sm-9">
						<input type="text" name="category" id="category" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="unitsInStock" class="col-sm-3">재고수</label>
					<div class="col-sm-9">
						<input type="text" name="unitsInStock" id="unitsInStock" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="unitsInStock" class="col-sm-3">상품 상태</label>
					<div class="col-sm-9">
						<input id="condition1" name="condition" type="radio" value="신규도서" />
						<label for="condition1">신규도서</label>
						<input id="condition2" name="condition" type="radio" value="중고도서" />
						<label for="condition2">중고도서</label>
						<input id="condition3" name="condition" type="radio" value="E-Book" />
						<label for="condition3">E-Book</label>
					</div>
				</div>
				<div class="form-group row">
					<div class="col-sm-offset-2 col-sm-12">
						<button id="addBookBtn" class="btn btn-primary" type="button">책 등록</button>
					</div>
				</div>
			</form>
		</div>
		<%@ include file="footer.jsp" %>
	</body>
	<script>
		$(function(){
			var addBookBtn = $("#addBookBtn");
			var addBookForm = $("#addBookForm");
			
			addBookBtn.on("click", function(){
				var bookId = $("#bookId").val();
				var name = $("#name").val();
				var unitPrice = $("#unitPrice").val();
				var author = $("#author").val();
				var publisher = $("#publisher").val();
				var releaseDate = $("#releaseDate").val();
				var totalPages = $("#totalPages").val();
				var description = $("#description").val();
				var category = $("#category").val();
				var unitsInStock = $("#unitsInStock").val();
				var condition = $("input[name='condition']:checked").val();
				
 				if(!bookId) {
					alert("도서코드를 입력해 주세요.");
					$("#bookId").focus();
					return false;
				}
				if(!name) {
					alert("도서명을 입력해 주세요.");
					$("#name").focus();
					return false;
				}
				if(!unitPrice) {
					alert("가격을 입력해 주세요.");
					$("#unitPrice").focus();
					return false;
				}
				if(!author) {
					alert("저자를 입력해 주세요.");
					$("#author").focus();
					return false;
				}
				if(!publisher) {
					alert("출판사를 입력해 주세요.");
					$("#publisher").focus();
					return false;
				}
				if(!releaseDate) {
					alert("출판일을 입력해 주세요.");
					$("#releaseDate").focus();
					return false;
				}
				if(!totalPages) {
					alert("총 페이지 수를 입력해 주세요.");
					$("#totalPages").focus();
					return false;
				}
				if(!description) {
					alert("상세 정보를 입력해 주세요.");
					$("#description").focus();
					return false;
				}
				if(!category) {
					alert("분류를 입력해 주세요.");
					$("#category").focus();
					return false;
				}
				if(!unitsInStock) {
					alert("재고수를 입력해 주세요.");
					$("#unitsInStock").focus();
					return false;
				}
				if(!condition) {
					alert("상품 상태를 체크해 주세요.");
					return false;
				}
				
				addBookForm.submit();
			});
		});
	</script>
</html>

[processAddBook.jsp]

<%@page import="vo.Book"%>
<%@page import="dao.BookRepository"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	request.setCharacterEncoding("utf-8");

	String bookId = request.getParameter("bookId");
	String name = request.getParameter("name");
	String unitPrice = request.getParameter("unitPrice");
	String author = request.getParameter("author");
	String publisher = request.getParameter("publisher");
	String releaseDate = request.getParameter("releaseDate");
	String totalPages = request.getParameter("totalPages");
	String description = request.getParameter("description");
	String category = request.getParameter("category");
	String unitsInStock = request.getParameter("unitsInStock");
	String condition = request.getParameter("condition");
	
 	// 가격을 문자에서 숫자로 변경
	Integer price = 0;
	if(!unitPrice.isEmpty()){
		price = Integer.valueOf(unitPrice);
	}
	
	// 재고수를 문자에서 숫자로 변경
	long stock = 0L;
	if(!unitsInStock.isEmpty()){
		stock = Long.valueOf(unitsInStock);
	}
	
	// 총페이지수를 문자에서 숫자로 변경
	long pages = 0L;
	if(!totalPages.isEmpty()){
		pages = Long.valueOf(totalPages);
	}
	
	BookRepository dao = BookRepository.getInstance();
	
	Book book = new Book();
	
	book.setBookId(bookId);
	book.setName(name);
	book.setUnitPrice(price);
	book.setAuthor(author);
	book.setPublisher(publisher);
	book.setReleaseDate(releaseDate);
	book.setTotalPages(pages);
	book.setDescription(description);
	book.setCategory(category);
	book.setUnitsInStock(stock);
	book.setCondition(condition);
	
	dao.addBook(book);
	
	System.out.println(book);
	
	response.sendRedirect("books.jsp");
%>

- http://localhost/addBook.jsp


[p. 249-252]



[fileupload01.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>
		<link rel="stylesheet" href="/resources/css/bootstrap.min.css" />
	</head>
	<body>
		<form name="newImg" action="fileupload01_process.jsp" class="container" method="post" enctype="multipart/form-data">
			<div class="form-group row">
			    <label for="fileuploadtest" class="col-sm-2">파일</label>
			    <div class="col-sm-6">
			        <input type="file" id="fileuptest" name="fileuptest" class="form-control">
			    </div>
			</div>
			<div class="form-group row">
				<div class="col-sm-offset-2 col-sm-12">
					<button class="btn btn-primary" type="submit">파일 올리기</button>
				</div>
			</div>
		</form>
	</body>
</html>

[fileupload01_process.jsp]

<%@page import="java.io.*"%>
<%@page import="java.util.*"%>
<%@page import="com.oreilly.servlet.*"%>
<%@page import="com.oreilly.servlet.multipart.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	MultipartRequest multi = new MultipartRequest(request, "C:\\upload", 5 * 1024 * 1024, "utf-8", new DefaultFileRenamePolicy());

	Enumeration files = multi.getFileNames();
	
	while(files.hasMoreElements()) {
		String name = (String) files.nextElement();
		String filename = multi.getFilesystemName(name);
		String original = multi.getOriginalFileName(name);
		String type = multi.getContentType(name);
		File file = multi.getFile(name);
		
		out.println("요청 파라미터 이름 : " + name + "<br />");
		out.println("실제 파일 이름 : " + original + "<br />");
		out.println("저장 파일 이름 : " + filename + "<br />");
		out.println("파일 콘텐츠 유형 : " + type + "<br />");
		
		if(file != null) {
			out.println("파일 크기 : " + file.length());
			out.println("<br />");
		}
	}
%>

- http://localhost/ch07/fileupload01.jsp

중복되는 파일 이름으로 중복되지 않게끔 자동으로 관리해 준다.


* 3, 4번은 동일한 문제이므로 4번 기준으로 문제를 풀도록 한다.

[fileupload02.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>
		<link rel="stylesheet" href="/resources/css/bootstrap.min.css" />
	</head>
	<body>
		<form name="newImg" action="fileupload02_process.jsp" class="container" method="post" enctype="multipart/form-data">
			<div class="form-group row">
			    <label for="fileuploadtest" class="col-sm-2">파일</label>
			    <div class="col-sm-6">
			        <input type="file" id="fileuptest" name="fileuptest" class="form-control">
			    </div>
			</div>
			<div class="form-group row">
				<div class="col-sm-offset-2 col-sm-12">
					<button class="btn btn-primary" type="submit">파일 올리기</button>
				</div>
			</div>
		</form>
	</body>
</html>

[fileupload02_process.jsp]

<%@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="java.io.File"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	request.setCharacterEncoding("utf-8");

	String fileUploadPath = "C:\\upload";
	
	File file = new File(fileUploadPath);
	if(!file.exists()) { // 설정한 경로에 폴더가 없으면
		file.mkdirs(); // 폴더를 만들어주세요.
	}
	
	DiskFileUpload upload = new DiskFileUpload();
	upload.setSizeMax(5 * 1024 * 1024);
	upload.setSizeThreshold(4 * 1024 * 1024);
	upload.setRepositoryPath(fileUploadPath);
	
	List items = upload.parseRequest(request);
	Iterator params = items.iterator();
	
	int maxSize = 4 * 1024 * 1024;
	while(params.hasNext()) {
		FileItem fileItem = (FileItem) params.next();
		
		if(!fileItem.isFormField()) { // 파일 데이터일 때
			String fileFieldName = fileItem.getFieldName(); // 요청 파라미터의 이름
			String fileName = fileItem.getName(); // 파일명
			String contentType = fileItem.getContentType(); // 파일 컨텐츠타입(MimeType)
			long fileSize = fileItem.getSize(); // 파일크기
			
			File newFile = new File(fileUploadPath + "/" + fileName);
			
			// 최대크기를 넘어버림(최대사이즈보다 큰 파일이 업로드됨)
			if(maxSize < fileSize) {
				out.println("파일 크기를 초과하였습니다!<br />");
			}else {
				fileItem.write(newFile); // 파일 복사
			}
			
			out.println("요청 파라미터 이름 : " + fileFieldName + "<br />");
			out.println("저장 파일 이름 : " + fileName + "<br />");
			out.println("파일 컨텐츠 타입 : " + contentType + "<br />");
			out.println("파일 크기 : " + fileSize + "<br />");
		}
	}
%>

- http://localhost/ch07/fileupload02.jsp


[books.jsp]

<%@page import="vo.Book"%>
<%@page import="java.util.ArrayList"%>
<%@page import="dao.BookRepository"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
	<head>
		<meta charset="UTF-8" />
		<title>도서 목록</title>
		<%@ include file="headSet.jsp" %>
	</head>
	<body>
		<%@ include file="menu.jsp" %>
		<div class="jumbotron">
			<div class="container">
				<h1 class="display-4">도서 목록</h1>
			</div>
		</div>
	      
		<div class="container">	
			<% 
				BookRepository dao = BookRepository.getInstance();
				ArrayList<Book> listOfBook = dao.getAllBooks();
			%>
			
			<c:set var="bookList" value="<%= listOfBook %>"></c:set>
			
			<c:forEach var="book" items="${bookList}">
				<div class="row">
					<div class="col-md-2" align="center">	
						<img style="width: 100%;" src="${pageContext.request.contextPath }/resources/images/${book.getFilename()}" width="60%" />
					</div>
					<div class="col-md-8">	
						<h5 ><b>[${book.getCategory()}] ${book.getName()}</b></h5>
						<p style="padding-top: 10px">${book.getDescription()}</p> 
						<p>${book.getAuthor()} | ${book.getPublisher()} | ${book.getUnitPrice()} 원</p>
					</div>	
					<div class="col-md-2"  style="padding-top: 60px">						    			 
						<a href="./book.jsp?id=${book.getBookId()}" class="btn btn-secondary" role="button"> 상세정보 &raquo; </a>				
					</div>
				</div>
				<hr />
			</c:forEach>
			
		</div>	
		<%@ include file="footer.jsp" %>
	</body>
</html>

[book.jsp]

<%@page import="vo.Book"%>
<%@page import="dao.BookRepository"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>도서 정보</title>
		<%@ include file="headSet.jsp" %>
	</head>
	<body>
		<%@ include file="menu.jsp" %>
		<div class="jumbotron">
			<div class="container">
				<h1 class="display-4">도서 정보</h1>
			</div>
		</div>
		<div class="container">
			<% 
				String id = request.getParameter("id");
				BookRepository dao = BookRepository.getInstance();
				Book book = dao.getBookById(id);
			%>
			
			<c:set var="book" value="<%= book %>"></c:set>
			
			<div class="row">
				<div class="col-md-4">
					<img src="${pageContext.request.contextPath }/resources/images/${book.getFilename()}" style="width: 100%" />
				</div>
				<div class="col-md-8">
					<h4><b>[${book.getCategory()}] ${book.getName()}</b></h4>
					<p>${book.getDescription()}</p>
					<p><b>도서코드 : </b><span class="badge badge-danger">${book.getBookId()}</span></p>
					<p><b>출판사</b> : ${book.getPublisher()}</p>			
					<p><b>저자</b> : ${book.getAuthor()}</p>			
					<p><b>재고수</b> : ${book.getUnitsInStock()}</p>
					<p><b>총 페이지수</b> : ${book.getTotalPages()}</p>
					<p><b>출판일</b> : ${book.getReleaseDate()}</p>
					<h4>가격 : ${book.getUnitPrice()}</h4>
					<form name="addForm" action="./addCart.jsp" method="get">
						<input type="hidden" value="" name="id"/>
						<a href="#" class="btn btn-info" onclick="addToCart()"> 도서주문&raquo;</a> 
						<a href="./cart.jsp" class="btn btn-warning"> 장바구니&raquo;</a> 
						<a href="./books.jsp" class="btn btn-secondary">도서목록 &raquo;</a>
					</form>
				</div>
			</div>
			<hr>
		</div>
		<%@ include file="footer.jsp" %>
	</body>
</html>

- http://localhost/books.jsp


[addBook.jsp]

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>도서 등록</title>
		<%@ include file="headSet.jsp" %>
	</head>
	<body>
		<%@ include file="menu.jsp" %>
		<div class="jumbotron">
			<div class="container">
				<h1 class="display-4">도서 정보</h1>
			</div>
		</div>
		<div class="container">
			<form id="addBookForm" name="addBookForm" class="form-horizontal" action="processAddBook.jsp" method="post" enctype="multipart/form-data">
				<div class="form-group row">
					<label for="bookId" class="col-sm-3">도서코드</label>
					<div class="col-sm-9">
						<input type="text" name="bookId" id="bookId" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="name" class="col-sm-3">도서명</label>
					<div class="col-sm-9">
						<input type="text" name="name" id="name" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="unitPrice" class="col-sm-3">가격</label>
					<div class="col-sm-9">
						<input type="text" name="unitPrice" id="unitPrice" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="author" class="col-sm-3">저자</label>
					<div class="col-sm-9">
						<input type="text" name="author" id="author" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="publisher" class="col-sm-3">출판사</label>
					<div class="col-sm-9">
						<input type="text" name="publisher" id="publisher" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="releaseDate" class="col-sm-3">출판일</label>
					<div class="col-sm-9">
						<input type="date" name="releaseDate" id="releaseDate" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="totalPages" class="col-sm-3">총 페이지 수</label>
					<div class="col-sm-9">
						<input type="text" name="totalPages" id="totalPages" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="description" class="col-sm-3">상세 정보</label>
					<div class="col-sm-9">
						<textarea name="description" id="description" class="form-control" style="height: 200px;" wrap="soft"></textarea>
					</div>
				</div>
				<div class="form-group row">
					<label for="category" class="col-sm-3">분류</label>
					<div class="col-sm-9">
						<input type="text" name="category" id="category" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="unitsInStock" class="col-sm-3">재고수</label>
					<div class="col-sm-9">
						<input type="text" name="unitsInStock" id="unitsInStock" class="form-control" >
					</div>
				</div>
				<div class="form-group row">
					<label for="unitsInStock" class="col-sm-3">상품 상태</label>
					<div class="col-sm-9">
						<input id="condition1" name="condition" type="radio" value="신규도서" />
						<label for="condition1">신규도서</label>
						<input id="condition2" name="condition" type="radio" value="중고도서" />
						<label for="condition2">중고도서</label>
						<input id="condition3" name="condition" type="radio" value="E-Book" />
						<label for="condition3">E-Book</label>
					</div>
				</div>
				<div class="form-group row">
				    <label class="col-sm-3">이미지</label>
				    <div class="col-sm-9">
				        <input type="file" name="bookImage" class="form-control">
				    </div>
				</div>
				<div class="form-group row">
					<div class="col-sm-offset-2 col-sm-12">
						<button id="addBookBtn" class="btn btn-primary" type="button">책 등록</button>
					</div>
				</div>
			</form>
		</div>
		<%@ include file="footer.jsp" %>
	</body>
	<script>
		$(function(){
			var addBookBtn = $("#addBookBtn");
			var addBookForm = $("#addBookForm");
			
			addBookBtn.on("click", function(){
				var bookId = $("#bookId").val();
				var name = $("#name").val();
				var unitPrice = $("#unitPrice").val();
				var author = $("#author").val();
				var publisher = $("#publisher").val();
				var releaseDate = $("#releaseDate").val();
				var totalPages = $("#totalPages").val();
				var description = $("#description").val();
				var category = $("#category").val();
				var unitsInStock = $("#unitsInStock").val();
				var condition = $("input[name='condition']:checked").val();
				
 				if(!bookId) {
					alert("도서코드를 입력해 주세요.");
					$("#bookId").focus();
					return false;
				}
				if(!name) {
					alert("도서명을 입력해 주세요.");
					$("#name").focus();
					return false;
				}
				if(!unitPrice) {
					alert("가격을 입력해 주세요.");
					$("#unitPrice").focus();
					return false;
				}
				if(!author) {
					alert("저자를 입력해 주세요.");
					$("#author").focus();
					return false;
				}
				if(!publisher) {
					alert("출판사를 입력해 주세요.");
					$("#publisher").focus();
					return false;
				}
				if(!releaseDate) {
					alert("출판일을 입력해 주세요.");
					$("#releaseDate").focus();
					return false;
				}
				if(!totalPages) {
					alert("총 페이지 수를 입력해 주세요.");
					$("#totalPages").focus();
					return false;
				}
				if(!description) {
					alert("상세 정보를 입력해 주세요.");
					$("#description").focus();
					return false;
				}
				if(!category) {
					alert("분류를 입력해 주세요.");
					$("#category").focus();
					return false;
				}
				if(!unitsInStock) {
					alert("재고수를 입력해 주세요.");
					$("#unitsInStock").focus();
					return false;
				}
				if(!condition) {
					alert("상품 상태를 체크해 주세요.");
					return false;
				}
				
				addBookForm.submit();
			});
		});
	</script>
</html>

[processAddBook.jsp]

<%@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="java.io.File"%>
<%@page import="vo.Book"%>
<%@page import="dao.BookRepository"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	request.setCharacterEncoding("utf-8");

	String realFolder = request.getServletContext().getRealPath("/resources/images");
	String encType = "UTF-8";
	
	int maxSize = 5 * 1024 * 1024;
	
	File folder = new File(realFolder);
	if(!folder.exists()) {
		folder.mkdirs();
	}
	
	DiskFileUpload upload = new DiskFileUpload();
	upload.setSizeMax(1000000);
	upload.setSizeThreshold(maxSize);
	upload.setRepositoryPath(realFolder);
	
	List items = upload.parseRequest(request);
	Iterator params = items.iterator();

	// 데이터를 저장하기 위한 변수 설정
	String bookId = "";
	String name = "";
	String unitPrice = "";
	String author = "";
	String publisher = "";
	String releaseDate = "";
	String totalPages = "";
	String description = "";
	String category = "";
	String unitsInStock = "";
	String condition = "";
	String fileName = "";
	
	while(params.hasNext()) {
		FileItem item = (FileItem) params.next();
		
		if(item.isFormField()) { // 일반 데이터 일 때
			String fieldName = item.getFieldName();
		
			// 일반적인 input 요소로 넘어온 name(key)을 이용하여 값을 할당
			if(fieldName.equals("bookId")) {
				bookId = item.getString(encType);
			}else if(fieldName.equals("name")) {
				name = item.getString(encType);
			}else if(fieldName.equals("unitPrice")) {
				unitPrice = item.getString(encType);
			}else if(fieldName.equals("author")) {
				author = item.getString(encType);
			}else if(fieldName.equals("publisher")) {
				publisher = item.getString(encType);
			}else if(fieldName.equals("releaseDate")) {
				releaseDate = item.getString(encType);
			}else if(fieldName.equals("totalPages")) {
				totalPages = item.getString(encType);
			}else if(fieldName.equals("description")) {
				description = item.getString(encType);
			}else if(fieldName.equals("category")) {
				category = item.getString(encType);
			}else if(fieldName.equals("unitsInStock")) {
				unitsInStock = item.getString(encType);
			}else if(fieldName.equals("condition")) {
				condition = item.getString(encType);
			}
			
		}else { // 파일 데이터 일 때
			
			String fileFieldName = item.getFieldName(); // 요청 파라미터 이름
			fileName = item.getName(); // 저장 파일의 이름
			String contentType = item.getContentType(); // 파일 컨텐츠 타입
			long fileSize = item.getSize(); // 파일 크기 정보
			File saveFile = new File(realFolder + "/" + fileName);
			item.write(saveFile); // 파일 복사
			
		}
	}
	
 	// 가격을 문자에서 숫자로 변경
	Integer price = 0;
	if(!unitPrice.isEmpty()){
		price = Integer.valueOf(unitPrice);
	}
	
	// 재고수를 문자에서 숫자로 변경
	long stock = 0L;
	if(!unitsInStock.isEmpty()){
		stock = Long.valueOf(unitsInStock);
	}
	
	// 총페이지수를 문자에서 숫자로 변경
	long pages = 0L;
	if(!totalPages.isEmpty()){
		pages = Long.valueOf(totalPages);
	}
	
	BookRepository dao = BookRepository.getInstance();
	
	Book book = new Book();
	
	book.setBookId(bookId);
	book.setName(name);
	book.setUnitPrice(price);
	book.setAuthor(author);
	book.setPublisher(publisher);
	book.setReleaseDate(releaseDate);
	book.setTotalPages(pages);
	book.setDescription(description);
	book.setCategory(category);
	book.setUnitsInStock(stock);
	book.setCondition(condition);
	book.setFilename(fileName);
	
	dao.addBook(book);
	
	response.sendRedirect("books.jsp");
%>

- http://localhost/addBook.jsp

'대덕인재개발원_웹기반 애플리케이션' 카테고리의 다른 글

231107_JSP 개론 9  (0) 2023.11.07
231106_JSP 개론 8  (0) 2023.11.06
231103_JSP 개론 7  (0) 2023.11.03
231102_JSP 개론 6  (0) 2023.11.02
231101_JSP 과제 3  (0) 2023.11.01