티스토리 뷰

Chapter17. 데이터베이스 연동 : 도서 목록 CRUD 처리하기

 

 

17.4 데이터 삽입, 수정, 삭제

 

 

17.4.2 CRUD 메서드를 사용하여 신규 도서 삽입하기

 

 

BookRepositoryImpl.java

@Override
	public void setNewBook(Book book) {
		String SQL = "INSERT INTO book (b_bookId, b_name, b_unitPrice, b_author, b_description, b_publisher, b_category, b_unitsInStock, b_releaseDate, b_condition, b_fileName)" + "VALUES(?,?,?,?,?,?,?,?,?,?,?)";
		
		template.update(SQL, book.getBookId(), book.getName(), book.getUnitPrice(), book.getAuthor(), book.getDescription(), book.getPublisher(), book.getCategory(), book.getUnitsInStock(), book.getReleaseDate(), book.getCondition(), book.getFileName());
		
	}

 

 

 

BookController.java

	@PostMapping("/add")
	public String submitAddNewBook(@Valid @ModelAttribute("NewBook") Book book, BindingResult result, HttpServletRequest request) {
		
		if(result.hasErrors()) {
			return "addBook";
		}
		
		MultipartFile bookImage = book.getBookImage();
		
		String save = request.getSession().getServletContext().getRealPath("/resources/images");
		String saveName = bookImage.getOriginalFilename();
		File saveFile = new File(save, saveName);
		
		if (bookImage != null && !bookImage.isEmpty()) {
			try {
				bookImage.transferTo(saveFile);
				book.setFileName(saveName);
			}
			catch(Exception e) {
				throw new RuntimeException("도서 이미지 업로드가 실패하였습니다.", e);
			}
		}
		bookService.setNewBook(book);
		return "redirect:/books";
	}

 

 

 

addBook.jsp

	<div class="container">		
		<div class="float-right" style="padding-right:30px">
			<a href="?language=ko">Korean</a>|<a href="?language=en">English</a>
		</div>
		
		<br><br>
		<form:form modelAttribute="NewBook" action="./add?${_csrf.parameterName }=${_csrf.token }" class="form-horizontal" enctype="multipart/form-data">
		<fieldset>
		   <%-- <legend>${addTitle}</legend> --%>
		<legend><spring:message code="addBook.form.subtitle.label" /></legend>

 

 

pom.xml

<properties>
      <security.version>5.6.3</security.version>
</properties>      

<!-- Spring Security -->   
        <dependency>
             <groupId>org.springframework.security</groupId>
             <artifactId>spring-security-web</artifactId>
             <version>${security.version}</version>
        </dependency>
        <dependency>
             <groupId>org.springframework.security</groupId>
             <artifactId>spring-security-config</artifactId>
             <version>${security.version}</version>
        </dependency>
        
        <dependency>
          <groupId>org.springframework.security</groupId>
          <artifactId>spring-security-taglibs</artifactId>
          <version>${security.version}</version>
       </dependency>

 

 

 

menu.jsp

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

        <li class="nav-item">
            <sec:authorize access="!isAuthenticated()">
                <form:form action="${pageContext.request.contextPath }/logout" method="post">
                <input type="submit" class="btn btn-success" value="Logout" />
                </form:form>
            </sec:authorize>
        </li>

        <li class="nav-item">
            <sec:authorize access="!isAuthenticated()">
                <a class="nav-link" href="<c:url value="/login"/>">Login</a>
            </sec:authorize>
        </li>
    </ul>

 

 

 

 

 

 

 

 

 


17.4.3 CRUD 메서드를 사용하여 도서 정보 수정하기

 

 

 

BookRepository.java

public interface BookRepository {
.....
	void setUpdateBook(Book book);
}

 

 

 

BookRepositoryImpl.java

	@Override
	public void setUpdateBook(Book book) {
		if(book.getFileName() != null) {
			String SQL = "UPDATE Book SET b_name = ?, b_unitPrice = ?, b_author = ?, b_description = ?, b_publisher = ?, b_category = ?, b_unitsInStock = ?, b_releaseDate = ?, b_condition = ?, b_fileName = ? where b_bookId = ?";
			template.update(SQL, book.getName(), book.getUnitPrice(), book.getAuthor(), book.getDescription(), book.getPublisher(), book.getCategory(), book.getUnitsInStock(), book.getReleaseDate(), book.getCondition(), book.getFileName(), book.getBookId());
		}
		else if (book.getFileName() == null) {
			String SQL = "UPDATE Book SET b_name = ?, b_unitPrice = ?, b_author = ?, b_description = ?, b_publisher = ?, b_category = ?, b_unitsInStock = ?, b_releaseDate = ?, b_condition = ? where b_bookId = ?";
			template.update(SQL, book.getName(), book.getUnitPrice(), book.getAuthor(), book.getDescription(), book.getPublisher(), book.getCategory(), book.getUnitsInStock(), book.getReleaseDate(), book.getCondition(), book.getBookId());
		}
		
	}

 

 

 

 

BookService.java

public interface BookService {
	...
	void setUpdateBook(Book book);

}

 

 

BookServiceImpl.java

	@Override
	public void setUpdateBook(Book book) {
		bookRepository.setUpdateBook(book);
		
	}

 

 

 

BookController.java

	@GetMapping("/update")
	public String getUpdateBookForm(@ModelAttribute("updateBook") Book book, @RequestParam("id") String bookId, Model model) {
		Book bookById = bookService.getBookById(bookId);
		model.addAttribute("book", bookById);
		return "updateForm";
	}
	
	@PostMapping("/update")
	public String submitUpdateBookForm(@ModelAttribute("updateBook") Book book, HttpServletRequest request) {
		MultipartFile bookImage = book.getBookImage();
		String rootDirectory = request.getSession().getServletContext().getRealPath("/resources/images");
		
		if(bookImage != null && !bookImage.isEmpty()) {
			
			try {
				String fname = bookImage.getOriginalFilename();
				bookImage.transferTo(new File(rootDirectory+fname));
				book.setFileName(fname);
			}  catch (IOException e) {
				throw new RuntimeException("Book Image saving failed", e);
			}
		}
		bookService.setUpdateBook(book);
		return "redirect:/books";
	}

 

 

 

 

book.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<sec:authorize access="isAuthenticated()">
    <a href="<c:url value='/books/update?id=${book.bookId }'/>" class="btn btn-success">수정&raquo;</a>
</sec:authorize>

 

 

updateForm.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>    
<!DOCTYPE html>
<html>
<head>
<link href="<c:url value='/resources/css/bootstrap.min.css'/>"rel='stylesheet' />
<meta charset="utf-8">
<title>도서 상세 정보</title>
</head>
<body>
<div class="container">
	<div class="col-md-4">
		<img src="<c:url value='/resources/images/${book.fileName }'></c:url>" alt="image" style="width:100%"/>
	</div>
	<div class="col-md-7">
		<form:form modelAttribute="updateBook" action="./update?${_csrf.parameterName }=${_csrf.token }" class="form-horizontal" enctype="multipart/form-data">
			<fieldset>
				<div class="form-group row">
					<label class="col-sm-2 control-label">도서 ID</label>
					<div class="col-sm-6" style="paddin-top:10px">
						<form:input id="bookId" path="bookId" type="hidden" class="form-control" value="${book.bookId }" />
						<span class="badge badge-info">${book.bookId }</span>
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-2 control-label">도서명</label>
					<div class="col-sm-6">
						<form:input path="name" class="form-control" value="${book.name }" />
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-2 control-label">가격</label>
					<div class="col-sm-6">
						<form:input path="unitPrice" class="form-control" value="${book.unitPrice }" />
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-2 control-label">저자</label>
					<div class="col-sm-6">
						<form:input path="author" class="form-control" value="${book.author }" />
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-2 control-label">상세정보</label>
					<div class="col-sm-10">
						<form:input path="description" col="50" rows="2" class="form-control" value="${book.description }" />
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-2 control-label">출판사</label>
					<div class="col-sm-6">
						<form:input path="publisher" class="form-control" value="${book.publisher }" />
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-2 control-label">분류</label>
					<div class="col-sm-6">
						<form:input path="category" class="form-control" value="${book.category }" />
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-2 control-label">재고수</label>
					<div class="col-sm-6">
						<form:input path="unitsInStock" class="form-control" value="${book.unitsInStock }" />
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-2 control-label">출판일</label>
					<div class="col-sm-6">
						<form:input path="releaseDate" class="form-control" value="${book.releaseDate }" />
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-2 control-label">상태</label>
					<div class="col-sm-6">
						<form:radiobutton path="condition" value="New"/>New
						<form:radiobutton path="condition" value="Old"/>Old
						<form:radiobutton path="condition" value="E-Book"/>E-Book
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-2 control-label">이미지</label>
					<div class="col-sm-10">
						<form:input path="bookImage" type="file" class="form-control" />
					</div>
				</div>
				<div class="form-group row">
					<div class="col-sm-offset-2 col-sm-10">
						<input type="submit" class="btn btn-primary" value="수정" />
						<a href="<c:url value="/books"/>" class="btn btn-primary">취소</a>
					</div>
				</div>
			</fieldset>
		</form:form>
	</div>
</div>
</body>
</html>

 

 

 

tiles.xml

   <definition name="updateForm" extends="base-Template">
   		<put-attribute name="title" value="Book"/>
   		<put-attribute name="heading" value="도서수정"/>
   		<put-attribute name="subheading" value="Book Editing"/>
   		<put-attribute name="content" value="/WEB-INF/views/updateForm.jsp"/>
   </definition>

 

 

 

 

 

 

 

 


17.4.4 CRUD 메서드를 사용하여 도서 삭제하기

 

 

 

BookRepository.java

public interface BookRepository {
	...
	void setDeleteBook(String bookId);
}

 

 

BookRepositoryImpl.java

	@Override
	public void setDeleteBook(String bookId) {
		String SQL = "DELETE from book where b_bookId=?";
		this.template.update(SQL, bookId);
		
	}

 

 

 

BookService.java

public interface BookRepository {
	...
	void setDeleteBook(String bookId);
}

 

 

BookServiceImpl.java

	@Override
	public void setDeleteBook(String bookId) {
		bookRepository.setDeleteBook(bookId);
		
	}

 

 

 

BookController.java

	@RequestMapping(value="/delete")
	public String getDeleteBookForm(Model model, @RequestParam("id") String bookId) {
		bookService.setDeleteBook(bookId);
		return "redirect:/books";
	}

 

 

controllers.js

function deleteConfirm(id){
	if(confirm("삭제합니다!!") == true) location.href="./delete?id="+id;
	else return;
}

 

 

book.jsp

<form:form name="addForm" method="put">
   <p><a href="javascript:addToCart('../cart/add/${book.bookId}')" class="btn btn-primary">도서주문 &raquo;</a>
   <a href="<c:url value="/cart"/>"class="btn btn-warning">장바구니 &raquo;</a>
   <a href="<c:url value="/books"/>"class="btn btn-secondary">도서 목록 &raquo;</a>
   <sec:authorize access="isAuthenticated()">
        <a href="<c:url value='/books/update?id=${book.bookId }'/>" class="btn btn-success">수정&raquo;</a>
        <a href="<c:url value="javascript:deleteConfirm('${book.bookId }')" />" class="btn btn-danger">삭제 &raquo;</a>
   </sec:authorize>
</form:form>

 

 

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday