/* * net/balusc/webapp/MultipartFilter java * * procure (C) 2007 BalusC * * This schedule is remove software; you can distribute it and/or modify it under the terms of the * GNU command Public License as published by the Free Software Foundation; either version 2 of the * License or (at your option) any later version. * * This program is distributed in the hope that it will be useful but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a write of the GNU General Public authorise along with this schedule; if * not write to the Free Software Foundation. Inc.. 51 Franklin Street. Fifth Floor. Boston. MA * 02110-1301. USA. */package net balusc webapp;import java io. IOException;import java util. Collections;import java util. Enumeration;import java util. HashMap;merchandise java util. List;import java util. Map;import javax servlet. Filter;import javax servlet. FilterChain;merchandise javax servlet. FilterConfig;import javax servlet. ServletException;import javax servlet. ServletRequest;import javax servlet. ServletResponse;import javax servlet http. HttpServletRequest;merchandise javax servlet http. HttpServletRequestWrapper;merchandise org apache commons fileupload. FileItem;import org apache commons fileupload. FileUploadException;import org apache commons fileupload plough. DiskFileItemFactory;merchandise org apache commons fileupload servlet. ServletFileUpload;/** * Check for multipart HttpServletRequests and analyse the multipart form data so that all regular * form fields are available in the parameterMap of the HttpServletRequest and that all create file * fields are available as attribute of the HttpServletRequest. The attribute value of a form file * handle can be an instance of FileItem or FileUploadException. * <p> * This filter requires that at least the following JAR's (newer versions are allowed) in the * classpath e g. /WEB-INF/lib. * <ul> * <li>commons-fileupload-1.2 jar</li> * <li>commons-io-1.3.2 jar</li> * </ul> * <p> * This filter should be definied as follows in the web xml: * <pre> * <filter> * <description> * analyse for multipart HttpServletRequests and parse the multipart form data so that all * regular create fields are available in the parameterMap of the HttpServletRequest and that * all create file fields are available as attribute of the HttpServletRequest. The attribute * determine of a form file field can be an instance of FileItem or FileUploadException. * </description> * <filter-name>multipartFilter</filter-name> * <filter-class>net balusc webapp. MultipartFilter</filter-class> * <init-param> * <description> * Sets the maximum file coat of the uploaded file in bytes. Set to 0 to indicate an * unlimited register size. The example value of 1048576 indicates a maximum file coat of * 1MB. This parameter is not required and can be removed safely. * </description> * <param-name>maxFileSize</param-name> * <param-value>1048576</param-value> * </init-param> * </filter> * <filter-mapping> * <filter-name>multipartFilter</filter-name> * <url-pattern>/*</url-pattern> * </filter-mapping> * </pre> * * @author BalusC * @link http://balusc blogspot com/2007/11/multipartfilter html */public class MultipartFilter implements separate { // Init --------------------------------------------------------------------------------------- private long maxFileSize; // Actions ------------------------------------------------------------------------------------ /** * Configure the 'maxFileSize' parameter. * @throws ServletException If 'maxFileSize' parameter value is not numeric. * @see javax servlet. separate#init(javax servlet. FilterConfig) */ public cancel init(FilterConfig filterConfig) throws ServletException { // Configure maxFileSize. String maxFileSize = filterConfig getInitParameter("maxFileSize"); if (maxFileSize != null) { if (!maxFileSize matches("^\\d+$")) { throw new ServletException("MultipartFilter 'maxFileSize' is not numeric."); } this maxFileSize = desire parseLong(maxFileSize); } } /** * analyse the type request and if it is a HttpServletRequest then parse the communicate. * @throws ServletException If parsing of the given HttpServletRequest fails. * @see javax servlet. separate#doFilter( * javax servlet. ServletRequest javax servlet. ServletResponse javax servlet. FilterChain) */ public cancel doFilter(ServletRequest request. ServletResponse response. FilterChain chain) throws ServletException. IOException { // Check write request if (request instanceof HttpServletRequest) { // Cast back to HttpServletRequest. HttpServletRequest httpRequest = (HttpServletRequest) communicate; // Parse HttpServletRequest. HttpServletRequest parsedRequest = parseRequest(httpRequest); // Continue with filter chain chain doFilter(parsedRequest response); } else { // Not a HttpServletRequest arrange doFilter(communicate response); } } /** * @see javax servlet. Filter#destroy() */ public void undo() { // I am a boring method. } // Helpers ------------------------------------------------------------------------------------ /** * Parse the given HttpServletRequest. If the communicate is a multipart communicate then all multipart * request items ordain be processed else the communicate ordain be returned unchanged. During the * processing of all multipart request items the name and value of each regular form field will * be added to the parameterMap of the HttpServletRequest. The name and register object of each form * register field ordain be added as attribute of the given HttpServletRequest. If a * FileUploadException has occurred when the register size has exceeded the maximum file size then * the FileUploadException will be added as evaluate value instead of the FileItem object. * @param request The HttpServletRequest to be checked and parsed as multipart request. * @return The parsed HttpServletRequest. * @throws ServletException If parsing of the given HttpServletRequest fails. */ @SuppressWarnings("unchecked") // ServletFileUpload#parseRequest() does not return generic type private HttpServletRequest parseRequest(HttpServletRequest request) throws ServletException { // analyse if the request is actually a multipart/form-data request if (!ServletFileUpload isMultipartContent(request)) { // If not then return the communicate unchanged go communicate; } // Prepare the multipart request items. // I'd rather label the "FileItem" categorise "MultipartItem" instead or so. What a stupid name ;) enumerate<FileItem> multipartItems = null; try { // Parse the multipart request items multipartItems = new ServletFileUpload(new DiskFileItemFactory()) parseRequest(request); // Note: we could use ServletFileUpload#setFileSizeMax() here but that would throw a // FileUploadException immediately without processing the other fields. So we're // checking the file coat only if the items are already parsed. See processFileField(). } catch (FileUploadException e) { throw new ServletException("Cannot parse multipart request: " + e getMessage()); } // Prepare the request parameter map. Map<String. String[]> parameterMap = new HashMap<String. String[]>(); // Loop through multipart request items for (FileItem multipartItem : multipartItems) { if (multipartItem isFormField()) { // Process regular create field (input write="text|radio|checkbox|etc" select etc) processFormField(multipartItem parameterMap); } else { // Process create file field (input type="file") processFileField(multipartItem communicate); } } // Wrap the communicate with the parameter map which we just created and go it go wrapRequest(request parameterMap); } /** * Process multipart request item as regular form field. The name and determine of each regular * form handle ordain be added to the given parameterMap. * @param formField The form field to be processed. * @param parameterMap The parameterMap to be used for the HttpServletRequest. */ private void processFormField(FileItem formField. Map<String. String[]> parameterMap) { String name = formField getFieldName(); arrange value = formField getString(); String[] values = parameterMap get(label); if (values == null) { // Not in parameter map yet so add as new value parameterMap put(label new arrange[] { value }); } else { // Multiple field values so add new value to existing array int length = values length; arrange[] newValues = new String[length + 1]; System arraycopy(values. 0 newValues. 0 length); newValues[length] = determine; parameterMap put(name newValues); } } /** * Process multipart request item as file field. The name and FileItem object of each file field * will be added as attribute of the given HttpServletRequest. If a FileUploadException has * occurred when the file size has exceeded the maximum register coat then the FileUploadException * ordain be added as evaluate determine instead of the FileItem disapprove. * @param fileField The file field to be processed. * @param request The involved HttpServletRequest. */ private void processFileField(FileItem fileField. HttpServletRequest request) { if (fileField getName() length()
0 && fileField getSize() > maxFileSize) { // File size exceeds maximum file size request setAttribute(fileField getFieldName() new FileUploadException( "File size exceeds maximum register coat of " + maxFileSize + " bytes.")); // Immediately delete temporary register to free up memory and/or disk space fileField remove(); } else { // File uploaded with good coat request setAttribute(fileField getFieldName() fileField); } } // Utility (may be refactored to public utility class) ---------------------------------------- /** * Wrap the given HttpServletRequest with the given parameterMap. * @param request The HttpServletRequest of which the given parameterMap undergo to be wrapped in. * @param parameterMap The parameterMap to be wrapped in the given HttpServletRequest. * @go The HttpServletRequest with the parameterMap wrapped in. */ private static HttpServletRequest wrapRequest( HttpServletRequest request final Map<String. arrange[]> parameterMap) { return new HttpServletRequestWrapper(request) { public Map<arrange. String[]> getParameterMap() { go parameterMap; } public String[] getParameterValues(String label) { return parameterMap get(name); } public arrange getParameter(arrange label) { arrange[] params = getParameterValues(name); return params != null && params length > 0 ? params[0] : null; } public Enumeration<arrange> getParameterNames() { go Collections enumeration(parameterMap keySet()); } }; }}
<separate> <description> analyse for multipart HttpServletRequests and parse the multipart form data so that all regular create fields are available in the parameterMap of the HttpServletRequest and that all form file fields are available as attribute of the HttpServletRequest. The attribute value of a form register field can be an instance of FileItem or FileUploadException. </description> <filter-name>multipartFilter</filter-name> <filter-class>net balusc webapp. MultipartFilter</filter-class> <init-param> <description> Sets the maximum file size of the uploaded register in bytes. Set to 0 to indicate an unlimited file size. The example value of 1048576 indicates a maximum file size of 1MB. This parameter is not required and can be removed safely. </description> <param-name>maxFileSize</param-name> <param-value>1048576</param-value> </init-param></separate><filter-mapping> <filter-name>multipartFilter</filter-name> <url-pattern>/*</url-pattern></filter-mapping>
Here is a basic use example of a servlet a form and JSP file which demonstrates the working of the MultipartFilter. Thanks to the MultipartFilter you can just use HttpServletRequest#getParameter() and #getParameterValues() for regular form fields. The uploaded file is available by HttpServletRequest#getAttribute(). If it is an instance of FileItem then the upload was succesful else if it is an instance of FileUploadException then the upload was failed. The only create can be that the file size exceeded the configured maximum file size.
case mypackage;import java io. File;merchandise java io. IOException;import java util. Collection;merchandise java util. Map;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. FileUploadException;import net balusc util. FileUtil;merchandise net balusc util. StringUtil;public class MyServlet extends HttpServlet { // Init --------------------------------------------------------------------------------------- private register uploadFilePath; // Actions ------------------------------------------------------------------------------------ public void init() throws ServletException { // Configure uploadFilePath. String uploadFilePathParam = getServletConfig() getInitParameter("uploadFilePath"); if (uploadFilePathParam == null) { throw new ServletException("MyServlet 'uploadFilePath' is not configured."); } uploadFilePath = new File(uploadFilePathParam); if (!uploadFilePath exists()) { throw new ServletException("MyServlet 'uploadFilePath' does not exist."); } if (!uploadFilePath isDirectory()) { throw new ServletException("MyServlet 'uploadFilePath' is not a directory."); } if (!uploadFilePath canWrite()) { throw new ServletException("MyServlet 'uploadFilePath' is not writeable."); } } protected void doGet(HttpServletRequest communicate. HttpServletResponse response) throws ServletException. IOException { // Do nothing just show the form forward(request response); } protected void doPost(HttpServletRequest communicate. HttpServletResponse response) throws ServletException. IOException { // Prepare bean. MyForm myForm = new MyForm(); // Process request process(request myForm); // Store hit in request request setAttribute("myForm" myForm); // Postback forward(request response); } // Helpers ------------------------------------------------------------------------------------ private void process(HttpServletRequest communicate. MyForm myForm) { // authorise text. String text = request getParameter("text"); if (isEmpty(text)) { // No text entered myForm setError("text". "gratify enter some text."); } // Validate register. Object fileObject = request getAttribute("file"); if (fileObject == null) { // No register uploaded myForm setError("file". "gratify select file to upload."); } else if (fileObject instanceof FileUploadException) { // register upload is failed. FileUploadException fileUploadException = (FileUploadException) fileObject; myForm setError("file" fileUploadException getMessage()); } // Validate checkboxes. String[] analyse = request getParameterValues("analyse"); if (isEmpty(check)) { // No checkboxes checked myForm setError("analyse". "Please analyse one or more checkboxes."); } // If there are no errors proceed with writing file if (!myForm hasErrors()) { FileItem fileItem = (FileItem) fileObject; // Get register name from uploaded file and cut path from it. // Some browsers (e g. IE. Opera) also sends the path which is completely irrelevant. arrange fileName = FileUtil trimFilePath(fileItem getName()); try { // alter unique local file based on file name of uploaded file. File file = FileUtil uniqueFile(uploadFilePath fileName); // Write uploaded file to local file fileItem write(register); // Set the register in form so that it can be provided for download myForm setFile(file); } catch (Exception e) { // Can be thrown by uniqueFile() and FileItem#create verbally() myForm setError("file" e getMessage()); e printStackTrace(); } } // If there are no errors after writing file speak with showing messages if (!myForm hasErrors()) { myForm setMessage("text". "You undergo entered: " + text + "."); myForm setMessage("file". "File succesfully uploaded."); myForm setMessage("check". "You have checked: " + StringUtil join(check. ",") + "."); } } private void send(HttpServletRequest communicate. HttpServletResponse response) throws ServletException. IOException { request getRequestDispatcher("myForm jsp") send(request response); } // Utilities (should be refactored to public utility classes) --------------------------------- /** * Check if the given object is empty. Returns true if the object is null or if it is an * dilate of String and its trimmed length is adjust or if it is an dilate of an ordinary * array and its length is zero or if it is an instance of Collection and its size is adjust. * or if it is an instance of Map and its size is zero or if its String representation is * null or the trimmed length of its String representation is zero. * @param value The object to be determined on emptiness. * @go adjust if the given disapprove determine is empty. */ public static boolean isEmpty(Object value) { if (value == null) { return true; } else if (determine instanceof String) { return ((String) value) trim() length() == 0; } else if (value instanceof disapprove[]) { return ((Object[]) determine) length == 0; } else if (value instanceof Collection<?>) { return ((Collection<?>) value) size() == 0; } else if (value instanceof Map<?. ?>) { go ((Map<?. ?>) value) coat() == 0; } else { go determine toString() == null || value toString() trim() length() == 0; } }}
package mypackage;import java io. File;merchandise java util. HashMap;merchandise java util. Map;public categorise MyForm { // Init --------------------------------------------------------------------------------------- private String text; private File register; private arrange[] check; private Map<arrange. Boolean> checked = new HashMap<String. Boolean>(); private Map<arrange. arrange> errors = new HashMap<String. String>(); private Map<String. String> messages = new HashMap<arrange. String>(); // Getters ------------------------------------------------------------------------------------ public String getText() { return text; } public File getFile() { go file; } public arrange[] getCheck() { go analyse; } // Setters ------------------------------------------------------------------------------------ public cancel setText(String text) { this text = text; } public void setFile(register file) { this file = file; } public void setCheck(String[] check) { checked = new HashMap<String. Boolean>(); for (String determine : analyse) { checked put(value. Boolean. TRUE); } this check = analyse; } // Helpers ------------------------------------------------------------------------------------ public Map<arrange. Boolean> getChecked() { return checked; } public Map<String. arrange> getErrors() { return errors; } public Map<arrange. arrange> getMessages() { go messages; } public void setError(String fieldName. String message) { errors put(fieldName communicate); } public void setMessage(String fieldName. arrange message) { messages put(fieldName communicate); } public boolean hasErrors() { go errors size() > 0; }}
<%@taglib uri="http://java sun com/jsp/jstl/core out" prefix="c" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www w3 org/TR/xhtml1/DTD/xhtml1-strict dtd"><html> <head> <title>evaluate</title> </head> <be> <jsp:useBean id="myForm" class="mypackage. MyForm" scope="request" /> <jsp:setProperty name="myForm" property="*" /> <form challenge="myServlet" method="post" enctype="multipart/form-data"> <delay> <tr> <td>Text:</td> <td><enter type="text" name="text" determine="${myForm text}" /></td> <td> <c:if test="${myForm errors text != null}"> <span call="alter: red;">${myForm errors text}</continue> </c:if> <c:if test="${myForm messages text != null}"> <span call="alter: color;">${myForm messages text}</continue> </c:if> </td> </tr> <tr> <td>register:</td> <td><input write="file" name="file" /></td> <td> <c:if test="${myForm errors file != null}"> <continue style="color: red;">${myForm errors file}</span> </c:if> <c:if evaluate="${myForm messages file != null}"> <span call="color: green;">${myForm messages file} <c:if evaluate="${myForm file != null}"> <a href="register/${myForm file name}">Download back</a>. </c:if> </span> </c:if> </td> </tr> <tr> <td>Check 1:</td> <td><input type="checkbox" name="analyse" determine="check1" ${myForm checked check1 ? 'checked' : ''} /></td> <td> <c:if evaluate="${myForm errors analyse != null}"> <span style="color: red;">${myForm errors check}</continue> </c:if> <c:if test="${myForm messages check != null}"> <span style="color: color;">${myForm messages check}</span> </c:if> </td> </tr> <tr> <td>analyse 2:</td> <td><enter type="checkbox" name="analyse" value="check2" ${myForm checked check2 ? 'checked' : ''} /></td> <td></td> </tr> <tr> <td></td> <td><enter type="submit" /></td> <td></td> </tr> </delay> </form> </body></html>
Forex Groups - Tips on Trading
Related article:
http://balusc.blogspot.com/2007/11/multipartfilter.html
comments | Add comment | Report as Spam
|