BAEL-1740: Cleanup and Annotation Approach

This commit is contained in:
Thoughtscript 2018-05-13 23:56:37 +01:00
parent eceb73823b
commit 368fb608f7
6 changed files with 117 additions and 55 deletions

View File

@ -1,12 +1,11 @@
package com.baeldung.servlets;
package com.baeldung;
public class Constants {
public static final String UPLOAD_DIRECTORY = "upload";
public static final String ENDPOINT = "/jspupload/uploadFile";
public static final String DEFAULT_FILENAME = "default.file";
public static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;
public static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
public static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;
}
}

View File

@ -24,10 +24,10 @@ public class FormServlet extends HttpServlet {
response.setHeader("Test", "Success");
response.setHeader("BMI", String.valueOf(bmi));
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/upload.jsp");
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/index.jsp");
dispatcher.forward(request, response);
} catch (Exception e) {
response.sendRedirect("upload.jsp");
response.sendRedirect("index.jsp");
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.servlets;
import com.baeldung.Constants;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import static com.baeldung.Constants.UPLOAD_DIRECTORY;
@MultipartConfig(fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 5 * 5)
public class MultipartServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String getFileName(Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename"))
return content.substring(content.indexOf("=") + 2, content.length() - 1);
}
return Constants.DEFAULT_FILENAME;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists())
uploadDir.mkdir();
try {
String fileName = "";
for (Part part : request.getParts()) {
fileName = getFileName(part);
part.write(uploadPath + File.separator + fileName);
}
request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
} catch (FileNotFoundException fne) {
request.setAttribute("message", "There was an error: " + fne.getMessage());
}
getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
}
}

View File

@ -1,61 +1,58 @@
package com.baeldung.servlets;
import static com.baeldung.servlets.Constants.MAX_FILE_SIZE;
import static com.baeldung.servlets.Constants.MAX_REQUEST_SIZE;
import static com.baeldung.servlets.Constants.MEMORY_THRESHOLD;
import static com.baeldung.servlets.Constants.UPLOAD_DIRECTORY;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import static com.baeldung.Constants.*;
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
private static final long serialVersionUID = 1L;
if (ServletFileUpload.isMultipartContent(request)) {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MEMORY_THRESHOLD);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
if (ServletFileUpload.isMultipartContent(request)) {
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MEMORY_THRESHOLD);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
try {
List<FileItem> formItems = upload.parseRequest(request);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
item.write(storeFile);
request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
}
}
}
} catch (Exception ex) {
request.setAttribute("message","There was an error: " + ex.getMessage());
}
getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
}
}
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();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
item.write(storeFile);
request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
}
}
}
} catch (Exception ex) {
request.setAttribute("message", "There was an error: " + ex.getMessage());
}
getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
}
}
}

View File

@ -12,4 +12,13 @@
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/uploadFile</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>MultiPartServlet</servlet-name>
<servlet-class>com.baeldung.servlets.MultipartServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MultiPartServlet</servlet-name>
<url-pattern>/multiPartServlet</url-pattern>
</servlet-mapping>
</web-app>

View File

@ -1,4 +1,4 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
@ -8,8 +8,16 @@
</head>
<body>
<div>Apache FileUpload</div>
<form method="post" action="uploadFile" enctype="multipart/form-data">
Choose a file: <input type="file" name="uploadFile" /><input type="submit" value="Upload" />
Choose a file: <input type="file" name="uploadFile"/><input type="submit" value="Upload"/>
</form>
</br>
<div>Servlet Multipart</div>
<form method="post" action="multiPartServlet" enctype="multipart/form-data">
Choose a file: <input type="file" name="multiPartServlet"/><input type="submit" value="Upload"/>
</form>
</body>
</html>