티스토리 뷰
파일 업로드 처리
파일 업로드
파일 업로드
1.pom.xml파일에 의존 라이브러리 등록하기
2.servlet-context.xml 파일에 시큐리티 필터 등록하기
파일 업로드를 위한 웹 페이지
MultipartFile을 사용한 파일 업로드
MultipartFile 인터페이스
파일 업로드 유형
1.@RequestParam 이용하기
2.MultipartHttpServletRequest 인터페이스 사용하기
3.@ModelAttribute 이용하기
리소스를 이용한 도서 이미지 출력하기.
servlet-context.xml
<resources mapping="/resources/**" location="/resources"/>
books.jsp
<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>
book.jsp
<c:choose>
<c:when test="${book.getBookImage()==null }">
<img src="<c:url value="/resources/images/${book.getBookId() }.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>
도서 이미지 파일 업로드하기
pom.xml
<properties>
<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
private MultipartFile bookImage;
public MultipartFile getBookImage() {
return bookImage;
}
public void setBookImage(MultipartFile bookImage) {
this.bookImage = bookImage;
}
BookController.java
// @PostMapping("/add")
// public String submitAddNewBook(@ModelAttribute("NewBook") Book book)
// {
// bookService.setNewBook(book);
// return "redirect:/books";
// }
// chap9 fileupload
@PostMapping("/add")
public String submitAddNewBook(@ModelAttribute("NewBook") Book book, HttpServletRequest request)
{
MultipartFile bookImage = book.getBookImage();
String saveName = bookImage.getOriginalFilename();
String save = request.getSession().getServletContext().getRealPath("/resources/images");
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";
}
@InitBinder
public void initBinder(WebDataBinder binder)
{
binder.setAllowedFields("bookId", "name", "unitPrice", "author",
"decription", "publisher", "category", "unitsInStock",
"totalPages", "releaseDate", "condition", "bookImage");//bookImage추가
}
addBook.jsp
<form:form modelAttribute="NewBook"
action="./add?${_csrf.parameterName}=${_csrf.token}" class="form-horizontal"
enctype="multipart/form-data">
....
<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-contorl" />
</div>
</div>
예외 처리
예외 처리
예외처리
예외 처리 방법의 종류
@ResponseStatus를 이용한 HTTP 상태 코드 기반 예외 처리
HTTP 상태 코드
@ResponseStatus를 이용한 예외 처리
@ResponseStatus를 이용한 예외 처리
CategoryException.java
package com.springmvc.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@SuppressWarnings("serial")
@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="요청한 도서 분야를 찾을 수 없습니다.")
public class CategoryException extends RuntimeException {
}
BookController.java
@GetMapping("/{category}")
public String requestBookByCategory(@PathVariable("category") String bookCategory, Model model)
{
List<Book> booksByCategory = bookService.getBookListByCategory(bookCategory);
//if문 추가
if(booksByCategory == null || booksByCategory.isEmpty())
{
throw new CategoryException();
}
model.addAttribute("bookList", booksByCategory);
return "books";
}
@ExceptionHandler를 이용한 컨트롤러 기반 예외 처리
@ExceptionHandler를 이용한 예외 처리
@ExceptionHandler를 이용한 예외 처리하기
BookIdException.java
package com.springmvc.exception;
@SuppressWarnings("serial")
public class BookIdException extends RuntimeException
{
private String bookId;
public BookIdException(String bookId)
{
this.bookId = bookId;
}
public String getBookId()
{
return bookId;
}
}
BookRepositoryImpl.java
public Book getBookById(String bookId) {
// TODO Auto-generated method stub
Book bookInfo = null;
for(int i = 0; i<listOfBooks.size(); i++)
{
Book book = listOfBooks.get(i);
if(book != null && book.getBookId() != null && book.getBookId().equals(bookId))
{
bookInfo = book;
break;
}
}
// 예외 처리 추가
if(bookInfo == null)
throw new BookIdException(bookId);
return bookInfo;
}
BookController.java
@ExceptionHandler(value= {BookIdException.class})
public ModelAndView handleError(HttpServletRequest req, BookIdException exception)
{
ModelAndView mav = new ModelAndView();
mav.addObject("invalidBookId", exception.getBookId());
mav.addObject("exception", exception);
mav.addObject("url", req.getRequestURL() + "?" + req.getQueryString());
mav.setViewName("errorBook");
return mav;
}
errorBook.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>
<link href="<c:url value="/resources/css/bootstrap.min.css"/>" rel="stylesheet">
<meta charset="UTF-8">
<title>Insert title here</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">
<h2 class="alert alert-danger">해당 도서가 존재하지 않습니다.<br>
도서ID : ${invalidBookId}
</h2>
</div>
</div>
<div class="container">
<p>${url}</p>
<p>${exception}</p>
</div>
<div class="container">
<p>
<a href="<c:url value='/books'/>" class="btn btn-secondary">도서목록 »</a>
</p>
</div>
</body>
</html>
@ControllerAdvice를 이용한 전역 예외 처리
전역 예외 처리를 위한 @ControllerAdvice
@ControllerAdvice를 이용하여 예외 처리하기
CommonException.java
package com.springmvc.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice
public class CommonException {
@ExceptionHandler(RuntimeException.class)
private ModelAndView handleErrorCommon(Exception e)
{
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", e);
modelAndView.setViewName("errorCommon");
return modelAndView;
}
}
errorCommon.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>
<link href="<c:url value="/resources/css/bootstrap.min.css"/>" rel="stylesheet">
<meta charset="UTF-8">
<title>Insert title here</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="alert alert-danger">요청한 도서가 존재하지 않습니다.</h1>
</div>
</div>
<div class="container">
<p>${exception }</p>
</div>
<div class="container">
<p>
<a href="<c:url value="/books" />"class="btn btn-secondary"> 도서목록 »</a>
</div>
</body>
</html>
'정리 노트 > Spring' 카테고리의 다른 글
Spring Chapter11~Chapter12 [16-3] (0) | 2024.01.25 |
---|---|
Spring Chapter11 [16-3] (0) | 2024.01.24 |
Spring Chapter8 [16-1] (0) | 2024.01.22 |
Spring Chapter7 [15-5] (0) | 2024.01.19 |
Spring Chapter5~Chapter6 [15-4] (0) | 2024.01.18 |