Skip to content

Commit 368fb60

Browse files
committed
BAEL-1740: Cleanup and Annotation Approach
1 parent eceb738 commit 368fb60

6 files changed

Lines changed: 121 additions & 59 deletions

File tree

javax-servlets/src/main/java/com/baeldung/servlets/Constants.java renamed to javax-servlets/src/main/java/com/baeldung/Constants.java

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1-
package com.baeldung.servlets;
1+
package com.baeldung;
22

33
public class Constants {
44

55
public static final String UPLOAD_DIRECTORY = "upload";
6-
public static final String ENDPOINT = "/jspupload/uploadFile";
6+
public static final String DEFAULT_FILENAME = "default.file";
77

88
public static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;
99
public static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
1010
public static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;
11-
12-
}
11+
}

‎javax-servlets/src/main/java/com/baeldung/servlets/FormServlet.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,10 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
2424
response.setHeader("Test", "Success");
2525
response.setHeader("BMI", String.valueOf(bmi));
2626

27-
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/upload.jsp");
27+
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/index.jsp");
2828
dispatcher.forward(request, response);
2929
} catch (Exception e) {
30-
response.sendRedirect("upload.jsp");
30+
response.sendRedirect("index.jsp");
3131
}
3232
}
3333

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.baeldung.servlets;
2+
3+
import com.baeldung.Constants;
4+
5+
import javax.servlet.ServletException;
6+
import javax.servlet.annotation.MultipartConfig;
7+
import javax.servlet.http.HttpServlet;
8+
import javax.servlet.http.HttpServletRequest;
9+
import javax.servlet.http.HttpServletResponse;
10+
import javax.servlet.http.Part;
11+
import java.io.File;
12+
import java.io.FileNotFoundException;
13+
import java.io.IOException;
14+
15+
import static com.baeldung.Constants.UPLOAD_DIRECTORY;
16+
17+
@MultipartConfig(fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 5 * 5)
18+
public class MultipartServlet extends HttpServlet {
19+
20+
private static final long serialVersionUID = 1L;
21+
22+
private String getFileName(Part part) {
23+
for (String content : part.getHeader("content-disposition").split(";")) {
24+
if (content.trim().startsWith("filename"))
25+
return content.substring(content.indexOf("=") + 2, content.length() - 1);
26+
}
27+
return Constants.DEFAULT_FILENAME;
28+
}
29+
30+
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
31+
32+
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
33+
File uploadDir = new File(uploadPath);
34+
if (!uploadDir.exists())
35+
uploadDir.mkdir();
36+
37+
try {
38+
String fileName = "";
39+
for (Part part : request.getParts()) {
40+
fileName = getFileName(part);
41+
part.write(uploadPath + File.separator + fileName);
42+
}
43+
request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
44+
} catch (FileNotFoundException fne) {
45+
request.setAttribute("message", "There was an error: " + fne.getMessage());
46+
}
47+
getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
48+
}
49+
}
Lines changed: 48 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,58 @@
11
package com.baeldung.servlets;
22

3-
import static com.baeldung.servlets.Constants.MAX_FILE_SIZE;
4-
import static com.baeldung.servlets.Constants.MAX_REQUEST_SIZE;
5-
import static com.baeldung.servlets.Constants.MEMORY_THRESHOLD;
6-
import static com.baeldung.servlets.Constants.UPLOAD_DIRECTORY;
3+
import org.apache.commons.fileupload.FileItem;
4+
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
5+
import org.apache.commons.fileupload.servlet.ServletFileUpload;
76

8-
import java.io.File;
9-
import java.io.IOException;
10-
import java.util.List;
117
import javax.servlet.ServletException;
128
import javax.servlet.http.HttpServlet;
139
import javax.servlet.http.HttpServletRequest;
1410
import javax.servlet.http.HttpServletResponse;
15-
import org.apache.commons.fileupload.FileItem;
16-
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
17-
import org.apache.commons.fileupload.servlet.ServletFileUpload;
11+
import java.io.File;
12+
import java.io.IOException;
13+
import java.util.List;
14+
15+
import static com.baeldung.Constants.*;
1816

1917
public class UploadServlet extends HttpServlet {
20-
21-
private static final long serialVersionUID = 1L;
22-
23-
protected void doPost(HttpServletRequest request, HttpServletResponse response)
24-
throws ServletException, IOException {
25-
26-
if (ServletFileUpload.isMultipartContent(request)) {
27-
28-
DiskFileItemFactory factory = new DiskFileItemFactory();
29-
factory.setSizeThreshold(MEMORY_THRESHOLD);
30-
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
31-
32-
ServletFileUpload upload = new ServletFileUpload(factory);
33-
upload.setFileSizeMax(MAX_FILE_SIZE);
34-
upload.setSizeMax(MAX_REQUEST_SIZE);
35-
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
36-
File uploadDir = new File(uploadPath);
37-
if (!uploadDir.exists()) {
38-
uploadDir.mkdir();
39-
}
40-
41-
try {
42-
List<FileItem> formItems = upload.parseRequest(request);
43-
44-
if (formItems != null && formItems.size() > 0) {
45-
for (FileItem item : formItems) {
46-
if (!item.isFormField()) {
47-
String fileName = new File(item.getName()).getName();
48-
String filePath = uploadPath + File.separator + fileName;
49-
File storeFile = new File(filePath);
50-
item.write(storeFile);
51-
request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
52-
}
53-
}
54-
}
55-
} catch (Exception ex) {
56-
request.setAttribute("message","There was an error: " + ex.getMessage());
57-
}
58-
getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
59-
}
60-
}
18+
19+
private static final long serialVersionUID = 1L;
20+
21+
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
22+
23+
if (ServletFileUpload.isMultipartContent(request)) {
24+
25+
DiskFileItemFactory factory = new DiskFileItemFactory();
26+
factory.setSizeThreshold(MEMORY_THRESHOLD);
27+
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
28+
29+
ServletFileUpload upload = new ServletFileUpload(factory);
30+
upload.setFileSizeMax(MAX_FILE_SIZE);
31+
upload.setSizeMax(MAX_REQUEST_SIZE);
32+
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
33+
File uploadDir = new File(uploadPath);
34+
if (!uploadDir.exists()) {
35+
uploadDir.mkdir();
36+
}
37+
38+
try {
39+
List<FileItem> formItems = upload.parseRequest(request);
40+
41+
if (formItems != null && formItems.size() > 0) {
42+
for (FileItem item : formItems) {
43+
if (!item.isFormField()) {
44+
String fileName = new File(item.getName()).getName();
45+
String filePath = uploadPath + File.separator + fileName;
46+
File storeFile = new File(filePath);
47+
item.write(storeFile);
48+
request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
49+
}
50+
}
51+
}
52+
} catch (Exception ex) {
53+
request.setAttribute("message", "There was an error: " + ex.getMessage());
54+
}
55+
getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
56+
}
57+
}
6158
}

‎javax-servlets/src/main/webapp/WEB-INF/web.xml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,13 @@
1212
<servlet-name>UploadServlet</servlet-name>
1313
<url-pattern>/uploadFile</url-pattern>
1414
</servlet-mapping>
15+
16+
<servlet>
17+
<servlet-name>MultiPartServlet</servlet-name>
18+
<servlet-class>com.baeldung.servlets.MultipartServlet</servlet-class>
19+
</servlet>
20+
<servlet-mapping>
21+
<servlet-name>MultiPartServlet</servlet-name>
22+
<url-pattern>/multiPartServlet</url-pattern>
23+
</servlet-mapping>
1524
</web-app>
Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
1+
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
22
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
33
<html>
44

@@ -8,8 +8,16 @@
88
</head>
99

1010
<body>
11+
<div>Apache FileUpload</div>
1112
<form method="post" action="uploadFile" enctype="multipart/form-data">
12-
Choose a file: <input type="file" name="uploadFile" /><input type="submit" value="Upload" />
13+
Choose a file: <input type="file" name="uploadFile"/><input type="submit" value="Upload"/>
14+
</form>
15+
16+
</br>
17+
18+
<div>Servlet Multipart</div>
19+
<form method="post" action="multiPartServlet" enctype="multipart/form-data">
20+
Choose a file: <input type="file" name="multiPartServlet"/><input type="submit" value="Upload"/>
1321
</form>
1422
</body>
1523
</html>

0 commit comments

Comments
 (0)