250x250
Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
Tags
- Open Source
- IntelliJ
- JavaScript
- SpringBoot
- oracle
- Source
- Thymeleaf
- Spring Boot
- jpa
- Tomcat
- 오픈소스
- Python
- Exception
- STS
- error
- spring
- JDBC
- maven
- AJAX
- Docker
- MSSQL
- myBatis
- ubuntu
- Core Java
- MySQL
- 문서
- Eclipse
- PostgreSQL
- git
- 설정
Archives
- Today
- Total
헤르메스 LIFE
[Spring] 개발환경 구축 - File Download 본문
728x90
Spring 개발환경을 갑자기 구축하려고 하다보니, 막막합니다.
하나 하나 구축해 보겠습니다
개발환경
Spring 4.3.30.RELEASE
MAVEN 3.8.4
Logback 1.2.9
commons-fileupload 1.4
commons-io 2.6
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SimpleSpring4</groupId>
<artifactId>SimpleSpring4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>SimpleSpring4</name>
<description>Simple Spring4</description>
<properties>
<springframework.version>4.3.30.RELEASE</springframework.version>
<org.slf4j-version>1.7.30</org.slf4j-version><!-- 1.7.26 -->
<ch.qos.logback-version>1.2.9</ch.qos.logback-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<!-- Bridge -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.25</version>
</dependency>
<!-- logback -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${ch.qos.logback-version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId><!-- logback을 slf4j-api에서 사용함을 의미 -->
</exclusion>
</exclusions>
<scope>runtime</scope><!-- runtime 시 사용함 -->
</dependency>
<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3</version>
</dependency>
<!-- For user input validation
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
-->
<!-- commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
</plugin>
</plugins>
</build>
</project>
DispatcherServlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<mvc:annotation-driven />
<!-- 빈 설정을 어노테이션 기반으로 하겠다는 설정태그 -->
<context:component-scan base-package="simple">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- CSS, JS, 이미지 등의 자원은 거의 변하지 않기 때문에, 웹 브라우저에 캐시를 하면
네트워크 사용량, 서버 사용량, 웹 브라우저의 반응 속도 등을 개선할 수 있다. -->
<mvc:resources mapping="/static/**" location="/static/" />
<mvc:resources location="/resources/**" mapping="/resources/"></mvc:resources>
<!--
Mulitipart Resolver
maxUploadSize는 최대 업로드 가능한 파일의 바이트 크기
maxInMemorySize는 디스크에 임시 파일을 생성하기 전 메모리에 보관할 수 있는 최대 바이트 크기
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<property name="maxUploadSize" value="104857600" /> <!-- 10M -->
<property name="maxInMemorySize" value="1048576" /> <!-- 1M -->
</bean>
<bean id="uploadPath" class="java.lang.String">
<constructor-arg value="C:/project/upload/"></constructor-arg>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!-- Encoding 설정 -->
<property name="defaultEncoding" value="UTF-8"/>
<!-- Reload Cache 설정 -->
<property name="cacheSeconds" value="5"/>
<!-- basenames 설정: 아래처럼 하면 WEB-INF 밑의 message 폴더 아래의 labels로 시작하는 모든 Property-->
<property name="basenames">
<list>
<value>/WEB-INF/messages/message</value>
<value>classpath:/messages/message</value>
</list>
</property>
</bean>
<!-- MessageSource를 사용하기 위한 Accessor 설정 -->
<bean id="messageSourceAccessor" class="org.springframework.context.support.MessageSourceAccessor">
<constructor-arg ref="messageSource"/>
</bean>
<!-- Default Location 설정 -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="ko"></property>
</bean>
<!--
mvc:default-servlet-handler
요청 경로와 일치하는 컨트롤러를 찾는다.
컨트롤러가 존재하지 않으면, 디폴트 서블릿 핸들러에 전달한다.
DispatcherSerlvet이 처리하지 못한 요청을 DefaultSerlvet에게 넘겨주는 역할을 하는 핸들러
*.css와 같은 컨트롤러에 매핑되어 있지 않은 URL 요청은 최종적으로 Default Servlet에 전달되어 처리하는 역할
web.xml 파일의 dispatcher 가 / 의 경우 설정한다.
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
-->
<mvc:default-servlet-handler />
<!-- beanNameResolver는 우선순위를 0으로 해서 ViewPage를 찾을 때 우선 탐색한다.
만약 BeanNameViewResolver에서 없으면 UrlBasedViewResolve에서 탐색한다. -->
<bean id="beanNameResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver">
<property name="order" value="0"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
<property name="order" value="1" /> <!-- 순서를 지정하는 property -->
</bean>
<bean id="fileDownload" class="simple.spring.view.FileDownloadView" />
</beans>
FileDownloadController.java
package simple.spring.file;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import simple.spring.file.repository.FileSaveRepository;
import simple.spring.file.vo.FileVO;
@Controller
public class FileDownloadController {
private static final Logger logger = LoggerFactory.getLogger(FileDownloadController.class);
// DispatcherServlet.xml 파일의 uploadPath bean의 constructor-arg를 가져옵니다.
@Autowired
private FileSaveRepository fileSaveRepository;
@RequestMapping(value = "/fileDownload")
public void fileDownload( HttpServletRequest request, HttpServletResponse response, ModelMap model )
throws IOException {
logger.debug("[FileDownloadController.fileDownload] 다운로드 시작 .....................................");
logger.debug("[FileDownloadController.fileDownload] file List :: {}", fileSaveRepository.findAll());
if ( fileSaveRepository.findAll().size() > 0 ) {
FileVO fileVO = fileSaveRepository.findById(1l);
File downloadFile = new File(fileVO.getTempFileName());
String orgnFileName = fileVO.getOrgnFileName();
byte fileByte[] = FileUtils.readFileToByteArray(downloadFile);
response.setContentType("application/octet-stream");
response.setContentLength(fileByte.length);
// User-Agent : 어떤 운영체제로 어떤 브라우저를 서버( 홈페이지 )에 접근하는지 확인함
String header = request.getHeader("User-Agent");
String fileName;
if ( (header.contains("MSIE")) || (header.contains("Trident")) || (header.contains("Edge")) ) {
// 인터넷 익스플로러 10이하 버전, 11버전, 엣지에서 인코딩
fileName = URLEncoder.encode(orgnFileName, "UTF-8");
} else {
// 나머지 브라우저에서 인코딩
fileName = new String(orgnFileName.getBytes("UTF-8"), "iso-8859-1");
}
logger.debug("[FileDownloadView.fileDownload] fileName :: {}", fileName);
// 형식을 모르는 파일첨부용 contentType
response.setContentType("application/octet-stream");
response.setContentLength(fileByte.length);
// 다운로드와 다운로드될 파일이름
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
BufferedInputStream in = null;
in = new BufferedInputStream(new FileInputStream(downloadFile));
// 파일복사
FileCopyUtils.copy(in, response.getOutputStream());
in.close();
response.getOutputStream().flush();
response.getOutputStream().close();
}
}
@RequestMapping(value = "/fileDownload2")
public ModelAndView fileDownload2( HttpServletRequest request, HttpServletResponse response, ModelMap model )
throws IOException {
logger.debug("[FileDownloadController.fileDownload2] 다운로드 시작 .....................................");
logger.debug("[FileDownloadController.fileDownload2] file List :: {}", fileSaveRepository.findAll());
if ( fileSaveRepository.findAll().size() > 0 ) {
FileVO fileVO = fileSaveRepository.findById(1l);
File downloadFile = new File(fileVO.getTempFileName());
ModelAndView modelAndView = new ModelAndView("fileDownload");
modelAndView.addObject("downloadFile", downloadFile);
modelAndView.addObject("orgnFileName", fileVO.getOrgnFileName());
return modelAndView;
} else {
return new ModelAndView("index");
}
}
}
FileDownloadView.java
package simple.spring.view;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;
public class FileDownloadView extends AbstractView {
private static final Logger logger = LoggerFactory.getLogger(FileDownloadView.class);
public FileDownloadView() {
setContentType("application/octet-stream; charset=utf-8");
} // 객체 생성할 때 실행되는 부분(생성자)
@Override
protected void renderMergedOutputModel( Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response ) throws Exception {
// ModelAndView 객체에 있는 참조변수 downloadFile를 꺼내서 저장
File file = (File) model.get("downloadFile");
String orgnFileName = (String) model.get("orgnFileName");
byte fileByte[] = FileUtils.readFileToByteArray(file);
response.setContentType(getContentType());
response.setContentLength(fileByte.length);
// User-Agent : 어떤 운영체제로 어떤 브라우저를 서버( 홈페이지 )에 접근하는지 확인함
String header = request.getHeader("User-Agent");
String fileName;
if ( (header.contains("MSIE")) || (header.contains("Trident")) || (header.contains("Edge")) ) {
// 인터넷 익스플로러 10이하 버전, 11버전, 엣지에서 인코딩
fileName = URLEncoder.encode(orgnFileName, "UTF-8");
} else {
// 나머지 브라우저에서 인코딩
fileName = new String(orgnFileName.getBytes("UTF-8"), "iso-8859-1");
}
logger.debug("[FileDownloadView.fileDownload] fileName :: {}", fileName);
// 다운로드와 다운로드될 파일이름
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
// 파일복사
FileCopyUtils.copy(in, response.getOutputStream());
} finally {
in.close();
response.getOutputStream().flush();
response.getOutputStream().close();
}
}
}
FileVO.java
package simple.spring.file.vo;
public class FileVO {
private long id;
private String orgnFileName;
private String tempFileName;
public long getId() {
return id;
}
public void setId( long id ) {
this.id = id;
}
public String getOrgnFileName() {
return orgnFileName;
}
public void setOrgnFileName( String orgnFileName ) {
this.orgnFileName = orgnFileName;
}
public String getTempFileName() {
return tempFileName;
}
public void setTempFileName( String tempFileName ) {
this.tempFileName = tempFileName;
}
@Override
public String toString() {
return "FileVO [id=" + id + ", orgnFileName=" + orgnFileName + ", tempFileName=" + tempFileName + "]";
}
}
FileSaveRepository.java
package simple.spring.file.repository;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;
import simple.spring.file.vo.FileVO;
/**
* 동시성 문제가 고려되어 있지 않음, 실무에서는 ConcurrentHashMap, AtomicLong 사용 고려
*/
@Component
public class FileSaveRepository {
private static Map<Long, FileVO> store = new HashMap<>();
private static long sequence = 0L;
private static final FileSaveRepository instance = new FileSaveRepository();
public static FileSaveRepository getInstance() {
return instance;
}
private FileSaveRepository() {
}
public FileVO save( FileVO file ) {
file.setId(++sequence);
store.put(file.getId(), file);
return file;
}
public FileVO findById( Long id ) {
return store.get(id);
}
public List<FileVO> findAll() {
return new ArrayList<>(store.values());
}
public void clearStore() {
store.clear();
}
}
https://hermeslog.tistory.com/651
https://hermeslog.tistory.com/650
728x90
'Spring Framework' 카테고리의 다른 글
[Spring] 개발환경 구축 - 대용량 Excel 다운로드 (0) | 2023.01.19 |
---|---|
[Spring] 개발환경 구축 - DBCP Connection Test (0) | 2022.12.29 |
[Spring] 개발환경 구축 - File Upload (1) | 2022.12.26 |
[Spring] 개발환경 구축 - MessagesSource (0) | 2022.12.22 |
[Spring] 개발환경 구축 - Logback (2) | 2022.12.21 |