클라이언트의 요청을 처리하고 그 결과를 반환하는 자바 웹 프로그래밍 기술로 Servlet 클래스로 구현되어있다.
Servlet Container (Web Container)
Servlet, JSP 를 실행할 수 있는 소프트웨어 (Tomcat 등)을 의미함. 요청이 들어올 때마다 새로운 자바 스레드를 만들고 HttpServletRequest 와 HttpServletResponse 객체를 생성해 관리하며 알맞은 JSP 파일을 서블릿 파일로 변환한 뒤 컴파일하여 이것을 실행한 결과를 반환한다.
@PostMapping("/uploadFile")
public void uploadFile(@RequestParam("file") MultipartFile file){
// 파일 기본 정보
System.out.println("file name : " + file.getOriginalFilename());
System.out.println("file size : " + file.getSize());
try(
// 프로젝트 폴더에 temp.jpg 이름으로 파일 생성
FileOutputStream fos = new FileOutputStream("./temp.jpg");
InputStream is = file.getInputStream()
){
int readCount;
byte[] buffer = new byte[1024];
// 데이터 쓰기
while((readCount = is.read(buffer)) != -1){
fos.write(buffer, 0, readCount);
}
}catch(Exception e){
e.printStackTrace();
}
}
2. 파일 다운로드
Java code
@GetMapping("/downloadFile")publicvoiddownloadFile(HttpServletResponse response){
// 프로젝트 폴더의 temp.jpg 파일 로드
String fileName = "temp.jpg";
File file = new File("./" + fileName);
// 클라이언트에서 아래의 이름으로 파일이 받아진다.
String newFileName = "newTemp.jpg";
try (
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream out = response.getOutputStream()
){
// 응답이 파일 타입이라는 것을 명시
response.addHeader("Content-Disposition", "attachment;filename=\""+newFileName+"\"");
// 응답 크기 명시
response.setContentLength((int)file.length());
int read = 0;
// 실제 데이터 전송// OutputStream 의 Deafult 버퍼 사이즈는 8192 Byte// 이 루프를 8000 번 정도 돌때마다 약 8KB 정도의 데이터가 전송 while((read = bis.read()) != -1) {
out.write(read);
}
} catch(IOException e) {
e.printStackTrace();
}
}
---
* HTTP MultiPart 로 파일 전송시 formData 에서 확인이 불가능, 단 파일을 null 로 전달하면 확인 가능 (크롬 기준)
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.example.demo.TestMapper"><resultMapid="parentResultType"type="com.example.demo.Parent"><idcolumn="parentId"property="id"/><resultcolumn="parentValue"property="value"/><collectionproperty="childList"resultMap="childList"/></resultMap><resultMapid="childList"type="com.example.demo.Child"><idcolumn="childId"property="id"/><resultcolumn="parentId"property="parentId"/><resultcolumn="childValue"property="value"/></resultMap><selectid="selectParentList"resultMap="parentResultType">
SELECT
t1.id AS parentId
, t1.value AS parentValue
, t2.id AS childId
, t2.value AS childValue
FROM
parent t1
LEFT JOIN child t2
ON t1.id = t2.parentId
</select></mapper>
Parent.java
public class Parent {
String id;
String value;
List<Child> childList = new ArrayList<>();
}
Child.java
public class Child {
Integer id;
Integer parentId;
String value;
}
3. 확인
Mapper 에서 정의한 selectParentList 쿼리를 사용하여 1. 의 환경의 DB 에서 조회할 경우,