티스토리 뷰
9.2.3 리소스를 이용한 도서 이미지 출력하기 / 9.2.4 도서 이미지 파일 업로드하기
c가 아닌 rseources 로 위치를 바꿔주었다.
servlet-context.xml
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
books.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="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
<link href="<c:url value="/resources/css/bootstrap.min.css"/>"rel="stylesheet" />
<meta charset="utf-8">
<title>도서 목록</title>
</head>
<body>
<nav class="navbar-expand navbar-dark bg-dark">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="./home">Home</a>
</div>
</div>
</nav>
<div class="jumbotron">
<div class="container">
<h1 class="display-3">도서 목록</h1>
</div>
</div>
<div class="container">
<div class="row" align="center">
<c:forEach items="${bookList}" var="book">
<div class="col-md-4">
<c:choose>
<c:when test="${book.getBookImage() == null }">
<img src="<c:url value="/resources/images/${book.bookId }.png"/>" style="width:60%"/>
</c:when>
<c:otherwise>
<img src="<c:url value='/resources/images/${book.getBookImage().getOriginalFilename()}'/>" style="width: 60%"/>
</c:otherwise>
</c:choose>
<h3>${book.name}</h3>
<p>${book.author}
<br>${book.publisher} | ${book.releaseDate}
<p align=left>${fn:substring(book.description,0,100) }...
<p>${book.unitPrice}원
<p><a href="<c:url value="/books/book?id=${book.bookId}"/>"class="btn btn-secondary" role="button">상세정보 »</a>
</div>
</c:forEach>
</div>
<hr>
<footer>
<p>© BookMarket</p>
</footer>
</div>
</body>
</html>
book.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="<c:url value="/resources/css/bootstrap.min.css"/>"rel="stylesheet" />
<title>도서 상세 정보</title>
</head>
<body>
<nav class="navbar-expand navbar-dark bg-dark">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="./home">Home</a>
</div>
</div>
</nav>
<div class="jumbotron">
<div class="container">
<h1 class="display-3">도서 정보</h1>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4">
<c:choose>
<c:when test="${book.getBookImage()==null }">
<img src="/bookmarket/resources/images/${book.bookId}.png" style="width:100%">
</c:when>
<c:otherwise>
<img src="<c:url value='/resources/images/${book.getBookImage().getOriginalFilename()}'/>" style="width: 100%"/>
</c:otherwise>
</c:choose>
</div>
<div class="col-md-8">
<h3>${book.name}</h3>
<p>${book.description }</p>
<br>
<p><b>도서코드 : </b><span class="badge badge-info">${book.bookId }</span>
<p><b>저자</b> : ${book.author}
<p><b>출판사</b> : ${book.publisher}
<p><b>출판일</b> : ${book.releaseDate}
<p><b>분류</b> : ${book.category}
<p><b>재고수</b> : ${book.unitsInStock}
<h4>${book.unitPrice }원</h4>
<br>
<p><a href="#" class="btn btn-primary">도서주문 »</a>
<a href="<c:url value="/books"/>" class="btn btn-secondary">도서 목록 »</a>
</div>
</div>
<hr>
<footer>
<p>© BookMarket</p>
</footer>
</div>
</body>
</html>
pom.xml
<commons-fileupload-version>1.4</commons-fileupload-version>
<commons-io-version>2.11.0</commons-io-version>
</properties>
<!-- File Upload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload-version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io-version}</version>
</dependency>
servlet-context.xml
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="10240000"/>
</beans:bean>
Book.java
package com.springmvc.domain;
import org.springframework.web.multipart.MultipartFile;
public class Book
{
private String bookId;
private String name;
private int unitPrice;
private String author;
private String description;
private String publisher;
private String category;
private long unitsInStock;
private String releaseDate;
private String condition;
private MultipartFile bookImage;
// 기본 생성자 생성
public Book() {
super();
}
// 일반 생성자
public Book(String bookId, String name, int unitPrice) {
super();
this.bookId = bookId;
this.name = name;
this.unitPrice = unitPrice;
}
//getter setter
public String getBookId() {
return bookId;
}
public void setBookId(String bookId) {
this.bookId = bookId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(int unitPrice) {
this.unitPrice = unitPrice;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public long getUnitsInStock() {
return unitsInStock;
}
public void setUnitsInStock(long unitsInStock) {
this.unitsInStock = unitsInStock;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public MultipartFile getBookImage() {
return bookImage;
}
public void setBookImage(MultipartFile bookImage) {
this.bookImage = bookImage;
}
}
BookController.java
package com.springmvc.controller;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.MatrixVariable;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.springmvc.domain.Book;
import com.springmvc.service.BookService;
@Controller
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@GetMapping
public String requestBookList(Model model) {
List<Book> list = bookService.getAllBookList();
model.addAttribute("bookList",list);
return "books";
}
/*@GetMapping("/all")
public String requestAllBooks(Model model)
{
List<Book> list = bookService.getAllBookList(); // 호출하니까 이동
model.addAttribute("bookList", list);
return "books";
}*/
@GetMapping("/all")
public ModelAndView requestAllBooks(Model model) {
ModelAndView modelAndView = new ModelAndView();
List<Book> list = bookService.getAllBookList();
modelAndView.addObject("bookList", list);
modelAndView.setViewName("books");
return modelAndView;
}
@GetMapping("/{category}")
public String requestBooksByCategory(@PathVariable("category") String bookCategory, Model model) {
List<Book> booksByCategory = bookService.getBookListByCategory(bookCategory);
model.addAttribute("bookList",booksByCategory);
return "books";
}
@GetMapping("/filter/{bookFilter}")
public String requestBooksByFilter(@MatrixVariable(pathVar="bookFilter") Map<String, List<String>> bookFilter, Model model) {
Set<Book> booksByFilter = bookService.getBookListByFilter(bookFilter);
model.addAttribute("bookList",booksByFilter);
return "books";
}
@GetMapping("/book")
public String requestBookById(@RequestParam("id") String bookId, Model model) {
Book bookById = bookService.getBookById(bookId);
model.addAttribute("book",bookById);
return "book";
}
@GetMapping("/add")
public String requestAddBookForm(@ModelAttribute("NewBook") Book book) {
return "addBook";
}
@PostMapping("/add")
public String submitAddNewBook(@ModelAttribute("NewBook") Book book, HttpServletRequest request) {
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);
}
catch(Exception e) {
throw new RuntimeException("도서 이미지 업로드가 실패하였습니다.", e);
}
}
bookService.setNewBook(book);
return "redirect:/books";
}
@ModelAttribute
public void addAttributes(Model model) {
model.addAttribute("addTitle", "신규 도서 등록");
}
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.setAllowedFields("bookId","name","unitPrice","author","description","publisher","category","unitsInStock","totlaPages","releaseDate","condition","bookImage");
}
}
addBook.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>
<meta charset="utf-8">
<link href="<c:url value="/resources/css/bootstrap.min.css"/>"rel="stylesheet" />
<title>도서 등록</title>
</head>
<body>
<nav class="navbar navbar-expand navbar-dark bg-dark">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="./home">Home</a>
</div>
</div>
</nav>
<div class="jumbotron">
<div class="container">
<h1 class="display-3">도서 등록</h1>
</div>
</div>
<div class="container">
<div class="float-right">
<form:form action="${pageContext.request.contextPath }/logout" method="post">
<input type="submit" class="btn btn-sm btn-success" value="Logout" />
</form:form>
</div>
<br><br>
<form:form modelAttribute="NewBook" action="./add?${_csrf.parameterName }=${_csrf.token }" class="form-horizontal" enctype="multipart/form-data">
<fieldset>
<legend>${addTitle }</legend>
<div class="form-group row">
<label class="col-sm-2 control-label">도서ID</label>
<div class="col-sm-3">
<form:input path="bookId" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">도서명</label>
<div class="col-sm-3">
<form:input path="name" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">가격</label>
<div class="col-sm-3">
<form:input path="unitPrice" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">저자</label>
<div class="col-sm-3">
<form:input path="author" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">상세정보</label>
<div class="col-sm-5">
<form:textarea path="description" cols="50" rows="2" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">출판사</label>
<div class="col-sm-3">
<form:input path="publisher" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">분야</label>
<div class="col-sm-3">
<form:input path="category" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">재고수</label>
<div class="col-sm-3">
<form:input path="unitsInStock" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">출판일</label>
<div class="col-sm-3">
<form:input path="releaseDate" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">상태</label>
<div class="col-sm-3">
<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-7">
<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="등록" />
</div>
</div>
</fieldset>
</form:form>
<hr>
<footer>
<p>© BookMarket</p>
</footer>
</div>
</body>
</html>
'코딩 > spring' 카테고리의 다른 글
[16주 2일차] 예외 처리 : 도서 검색 오류에 대한 예외 처리하기 (1) | 2024.01.23 |
---|---|
[16주 2일차] 예외 처리 (0) | 2024.01.23 |
[16주 2일차] 파일 업로드 처리 (1) | 2024.01.23 |
[16주 1일차] 스프링 시큐리티 : 로그인/로그아웃 페이지 만들기 (0) | 2024.01.22 |
[16주 1일차] 스프링 시큐리티 (0) | 2024.01.22 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday