organize/스프링

스프링 웹 프로젝트 6

001cloudid 2025. 1. 4. 13:23
728x90

파일업로드 처리

  • Servlet 3.0 이후(Tomcat 7.0)에는 기본적으로 업로드 되는 파일을 처리할 수 있는 기능이 추가
  • 별로 commos-fileupload 라이브러리를 사용
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>

※ 라이브러리를 다운로드 할 때는 가능하면 서버는 중지시킨 후 실시

 

파일 업로드를 위한 servlet-context.xml

  • multipartResolver라는 이름으로 스프링 빈 설정
	<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<beans:property name="defaultEncoding" value="utf-8"></beans:property>
		<beans:property name="maxUploadSize" value="104857560"></beans:property> <!-- 1024*1024*2bytes 2MB -->
		<beans:property name="uploadTempDir" value="file:/C:/upload/tmp"></beans:property>
		<beans:property name="maxInMemorySize" value="10485756"></beans:property>
	</beans:bean>

디렉토리 생성

경로 : C:\upload\tmp

 

파일 업로드를 위한 HTML

  • form 태그 내 enctype="multipart"

SampleController

	@GetMapping("/exUpload") // 화면을 보는 것 기본 Get방식, 작업을 하는 것은 Post방식
	public void exUpload() {
		log.info("SampleController exUplad() log info"); // log → 작업이 어디까지 실행되었는지 확인하기 위해서
	}

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>exUpload</title>
</head>
<body>
	<h1>파일 업로드를 위한 HTML</h1>
	<form action="/sample/exUploadPost" method="post"
		enctype="multiPart/form-data">
		<div>
			<input type="file" name="files">
		</div>
		<div>
			<input type="file" name="files">
		</div>
		<div>
			<input type="file" name="files">
		</div>
		<div>
			<input type="file" name="files">
		</div>
		<div>
			<input type="file" name="files">
		</div>
		<div>
			<input type="submit">
		</div>
	</form>
</body>
</html>

SampleController

	@PostMapping("/exUploadPost")
	public void exUploadPost(ArrayList<MultipartFile> files) {
		files.forEach(file ->{
			log.info("=====================");
			log.info("name : " + file.getOriginalFilename());
			log.info("size : " + file.getSize());
			log.info("type : " + file.getContentType());
		});
	}

 

컨트롤러의 예외 처리(Exception)

  • @ExceptionHandler와 @ControllerAdvice를 이용한 처리 → 서버
  • @ResponseEntity를 이용하는 예외 메시지 구성 → 클라이언트 데이터 전송

 

@ControllerAdvice(스프링 빈으로 등록)

  • 예외처리와 원래의 컨트롤러가 혼합된 형태의 클래스가 작성되는 방식
  • @ExceptionHandler는 해당 메서드가 () 들어가는 예외 타입을 처리한다는 것을 의미
package org.zerock.exception;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import lombok.extern.log4j.Log4j;

@ControllerAdvice
@Log4j
public class CommonExceptionAdvice {
	
	@ExceptionHandler(Exception.class)
	public String except(Exception exception, Model model) {
		log.error("Exception : " + exception.getMessage());
		model.addAttribute("exception",exception);
		log.error("model : " + model);
		return "error_page";
	}

}

servlet-context.xml

	<context:component-scan base-package="org.zerock.exception" />
<%@ 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>error_page</title>
</head>
<body>
	<h1>error_page</h1>
	<h4>
		<c:out value="${exception.getMessage()}"></c:out>
	</h4>

	<ul>
		<c:forEach items="${exception.getStackTrace()}" var="stack">
			<li><c:out value="${stack}"></c:out></li>
		</c:forEach>
	</ul>
</body>
</html>

 

age값을 숫자가 아닌 값을 준다면

 

728x90

'organize > 스프링' 카테고리의 다른 글

스프링 웹 프로젝트 8  (0) 2025.01.06
스프링 웹 프로젝트 7  (0) 2025.01.05
스프링 웹 프로젝트 5  (0) 2024.12.31
스프링 웹 프로젝트 4  (0) 2024.12.30
스프링 웹 프로젝트 3  (0) 2024.12.29