티스토리 뷰
개발 환경
java version "21.0.4" 2024-07-16 LTS
Java(TM) SE Runtime Environment (build 21.0.4+8-LTS-274)
Java HotSpot(TM) 64-Bit Server VM (build 21.0.4+8-LTS-274, mixed mode, sharing)
Tomcat v10.1
사전 정보
Tomcat v10.1 에서 "Commons FileUpload" 를 사용하는 경우 다음과 같은 오류가 지속적으로 발생했다.
The type javax.servlet.http.HttpServletRequest cannot be resolved.
It is indirectly referenced from required type org.apache.commons.fileupload.servlet.ServletFileUpload
The method parseRequest(HttpServletRequest) from the type ServletFileUpload refers to the missing type HttpServletRequest
원인은?
Tomcat v10.1 은 "jakarta.servlet.http.HttpServletRequest" 사용하는 반면
Commons FileUpload.jar 는 "javax.servlet.http.HttpServletRequest" 을 사용하기 때문에 "upload.parseRequest(request)" 에서 오류가 발생한다.
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
List<FileItem> formItems = upload.parseRequest(request);
tomcat v10.1 사용시 발생하는 오류인데 어떻게 해결해야 하지?
아래 3개의 파일을 WEB-INF -> lib 폴더에 추가하고 코드를 수정했다.
fileUpload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<form name="fileUploadForm" action="fileUpload.do" method="post" encType="multipart/form-data">
<p>
파일1: <input type="file" name="file1" />
</p>
<p>
파일2: <input type="file" name="file2" />
</p>
<input type="submit" value="Data Send" />
</form>
</body>
</html>
fileUpload.servlet
package jspFileManager.ex1;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import org.apache.commons.fileupload2.core.DiskFileItemFactory;
import org.apache.commons.fileupload2.core.FileItem;
import org.apache.commons.fileupload2.jakarta.servlet6.JakartaServletFileUpload;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet(
name = "UploadServlet",
urlPatterns = {"/fileUpload.do"}
)
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (JakartaServletFileUpload.isMultipartContent(request)) {
DiskFileItemFactory factory = DiskFileItemFactory.builder().get();
JakartaServletFileUpload upload = new JakartaServletFileUpload(factory);
upload.setFileSizeMax(1024*1024);
upload.setSizeMax(1024*1024);
String uploadPath = "/Users/jeonghun/eclipse-workspace/uploadedFiles";
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
item.write(Path.of(uploadPath, fileName));
response.getWriter().println(String.format(
"Filed Name = %s, File Name = %s, File Size = %s "
, item.getFieldName()
, item.getName()
, item.getSize()
));
}
}
}
} catch (Exception ex) {
System.out.println("There was an error: " + ex.getMessage());
}
}
}
}
fileDownload.java
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"
isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<img src="${ pageContext.request.contextPath }/fileDownload.do?fileName=Designer (30).jpeg" width="500" height="500" />
<br>
<a href="${ pageContext.request.contextPath }/fileDownload.do?fileName=Designer (30).jpeg"> file download</a>
</body>
</html>
fileDownload.servlet
package jspFileManager.ex1;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/fileDownload.do")
public class fileDownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doHandle(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doHandle(req, resp);
}
protected void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String file_repo = "/Users/jangjeonghun/eclipse-workspace/uploadedFiles";
String fileName = "Designer (30).jpeg";
String downloadFileFullPath = String.format("%s/%s", file_repo, fileName);
ServletOutputStream outputStream = response.getOutputStream();
File file = new File(downloadFileFullPath);
response.setHeader("Cache-Control", "no-cache");
response.addHeader("Content-disposition", "attachment; fileName="+fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[1024*8];
while(true) {
int count = fileInputStream.read(buffer);
if(count == -1) { break; }
outputStream.write(buffer, 0, count);
}
fileInputStream.close();
outputStream.close();
}
}
추가 정보
- Total
- Today
- Yesterday
- 표현 언어(expression language)
- java 키워드 정리
- 스프링 프레임워크(spring framewordk)
- 문자 자르기
- 스프링 시큐리티(spring security)
- 특정 문자를 기준으로 자르기
- jstl(java standard tag library)
- 람다식(lambda expression)
- java.sql
- java-개발 환경 설정하기
- 인텔리제이(intellij)
- jsp 오픈 소스
- async
- 진수 변환
- .submit()
- 스프링 프레임워크(spring framework)
- jstl(java standard tag library)-core
- java web-mvc
- 제품 등록
- In App Purchase
- System.Diagnostics
- REST API
- nl2br
- 상품 등록
- 스프링 시큐리티(spring security)-http basic 인증
- await
- system.io
- error-java
- 메이븐(maven)
- MainActor
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |