httpservletrequest

search for more blogs here

 

"MultipartFilter" posted by ~Ray
Posted on 2008-03-12 23:11:58

/* * 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> * &lt;filter&gt; * &lt;description&gt; * 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. * &lt;/description&gt; * &lt;filter-name&gt;multipartFilter&lt;/filter-name&gt; * &lt;filter-class&gt;net balusc webapp. MultipartFilter&lt;/filter-class&gt; * &lt;init-param&gt; * &lt;description&gt; * 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. * &lt;/description&gt; * &lt;param-name&gt;maxFileSize&lt;/param-name&gt; * &lt;param-value&gt;1048576&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;/filter&gt; * &lt;filter-mapping&gt; * &lt;filter-name&gt;multipartFilter&lt;/filter-name&gt; * &lt;url-pattern&gt;/*&lt;/url-pattern&gt; * &lt;/filter-mapping&gt; * </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}"> &nbsp;<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


"MultipartFilter" posted by ~Ray
Posted on 2008-03-12 23:11:58

/* * net/balusc/webapp/MultipartFilter java * * Copyright (C) 2007 BalusC * * This program is remove software; you can redistribute 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 schedule is distributed in the hope that it ordain 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 command Public License along with this program; 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;merchandise java util. Collections;import java util. Enumeration;merchandise java util. HashMap;merchandise java util. List;import java util. Map;import javax servlet. separate;import javax servlet. FilterChain;import javax servlet. FilterConfig;merchandise javax servlet. ServletException;merchandise javax servlet. ServletRequest;import javax servlet. ServletResponse;import javax servlet http. HttpServletRequest;import javax servlet http. HttpServletRequestWrapper;import org apache commons fileupload. FileItem;import org apache commons fileupload. FileUploadException;import org apache commons fileupload plough. DiskFileItemFactory;import org apache commons fileupload servlet. ServletFileUpload;/** * analyse for multipart HttpServletRequests and parse the multipart create data so that all regular * form fields are available in the parameterMap of the HttpServletRequest and that all form register * fields are available as attribute of the HttpServletRequest. The attribute determine of a create 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> * &lt;separate&gt; * &lt;description&gt; * Check 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 evaluate of the HttpServletRequest. The attribute * value of a create file handle can be an instance of FileItem or FileUploadException. * &lt;/description&gt; * &lt;filter-name&gt;multipartFilter&lt;/filter-name&gt; * &lt;filter-class&gt;net balusc webapp. MultipartFilter&lt;/filter-class&gt; * &lt;init-param&gt; * &lt;description&gt; * 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. * &lt;/description&gt; * &lt;param-name&gt;maxFileSize&lt;/param-name&gt; * &lt;param-value&gt;1048576&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;/filter&gt; * &lt;filter-mapping&gt; * &lt;filter-name&gt;multipartFilter&lt;/filter-name&gt; * &lt;url-pattern&gt;/*&lt;/url-pattern&gt; * &lt;/filter-mapping&gt; * </pre> * * @author BalusC * @link http://balusc blogspot com/2007/11/multipartfilter html */public categorise MultipartFilter implements Filter { // Init --------------------------------------------------------------------------------------- private desire maxFileSize; // Actions ------------------------------------------------------------------------------------ /** * assemble the 'maxFileSize' parameter. * @throws ServletException If 'maxFileSize' parameter determine is not numeric. * @see javax servlet. separate#init(javax servlet. FilterConfig) */ public void init(FilterConfig filterConfig) throws ServletException { // assemble maxFileSize. String maxFileSize = filterConfig getInitParameter("maxFileSize"); if (maxFileSize != null) { if (!maxFileSize matches("^\\d+$")) { throw new ServletException("MultipartFilter 'maxFileSize' is not numeric."); } this maxFileSize = Long parseLong(maxFileSize); } } /** * Check the type communicate and if it is a HttpServletRequest then analyse the request. * @throws ServletException If parsing of the given HttpServletRequest fails. * @see javax servlet. separate#doFilter( * javax servlet. ServletRequest javax servlet. ServletResponse javax servlet. FilterChain) */ public void doFilter(ServletRequest request. ServletResponse response. FilterChain arrange) throws ServletException. IOException { // Check write communicate if (request instanceof HttpServletRequest) { // Cast approve to HttpServletRequest. HttpServletRequest httpRequest = (HttpServletRequest) request; // analyse HttpServletRequest. HttpServletRequest parsedRequest = parseRequest(httpRequest); // act with separate chain chain doFilter(parsedRequest response); } else { // Not a HttpServletRequest chain doFilter(communicate response); } } /** * @see javax servlet. Filter#destroy() */ public void destroy() { // I am a boring method. } // Helpers ------------------------------------------------------------------------------------ /** * analyse the given HttpServletRequest. If the communicate is a multipart request then all multipart * request items will be processed else the request will be returned unchanged. During the * processing of all multipart request items the name and determine of each regular form field ordain * be added to the parameterMap of the HttpServletRequest. The name and File disapprove of each create * 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 size then * the FileUploadException will be added as attribute 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 communicate if (!ServletFileUpload isMultipartContent(communicate)) { // If not then return the request unchanged go request; } // alter the multipart request items. // I'd rather call the "FileItem" categorise "MultipartItem" instead or so. What a stupid name ;) List<FileItem> multipartItems = null; try { // analyse the multipart request items multipartItems = new ServletFileUpload(new DiskFileItemFactory()) parseRequest(request); // say: we could use ServletFileUpload#setFileSizeMax() here but that would throw a // FileUploadException immediately without processing the other fields. So we're // checking the file size only if the items are already parsed. See processFileField(). } catch (FileUploadException e) { throw new ServletException("Cannot analyse multipart request: " + e getMessage()); } // Prepare the communicate parameter map. Map<String. arrange[]> parameterMap = new HashMap<String. String[]>(); // Loop through multipart request items for (FileItem multipartItem : multipartItems) { if (multipartItem isFormField()) { // affect regular create field (input write="text|communicate|checkbox|etc" select etc) processFormField(multipartItem parameterMap); } else { // affect form file field (input type="file") processFileField(multipartItem communicate); } } // Wrap the request with the parameter map which we just created and return it return wrapRequest(request parameterMap); } /** * Process multipart request item as regular form field. The name and value of each regular * form field will 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<arrange. String[]> parameterMap) { arrange name = formField getFieldName(); String value = formField getString(); String[] values = parameterMap get(name); if (values == null) { // Not in parameter map yet so add as new value parameterMap put(label new String[] { value }); } else { // Multiple field values so add new determine to existing arrange int length = values length; String[] newValues = new arrange[length + 1]; System arraycopy(values. 0 newValues. 0 length); newValues[length] = value; parameterMap put(name newValues); } } /** * affect multipart request item as file field. The label and FileItem disapprove 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 file coat then the FileUploadException * will be added as evaluate value instead of the FileItem object. * @param fileField The file field to be processed. * @param communicate 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 file size of " + maxFileSize + " bytes.")); // Immediately delete temporary file to free up memory and/or disk space fileField delete(); } else { // File uploaded with good size request setAttribute(fileField getFieldName() fileField); } } // Utility (may be refactored to public utility class) ---------------------------------------- /** * cover the given HttpServletRequest with the given parameterMap. * @param request The HttpServletRequest of which the given parameterMap have 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<String. String[]> getParameterMap() { return parameterMap; } public arrange[] getParameterValues(arrange label) { return parameterMap get(name); } public String getParameter(arrange name) { String[] params = getParameterValues(name); go params != null && params length > 0 ? params[0] : null; } public Enumeration<String> getParameterNames() { return Collections enumeration(parameterMap keySet()); } }; }} <filter> <description> 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 form file fields are available as evaluate of the HttpServletRequest. The evaluate value 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 size of the uploaded file in bytes. Set to 0 to indicate an unlimited file size. The example value of 1048576 indicates a maximum register 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></filter><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 register 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 register 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 transfer was failed. The only cause can be that the register size exceeded the configured maximum register coat. package mypackage;import java io. File;import java io. IOException;import java util. Collection;import java util. Map;import javax servlet. ServletException;import javax servlet http. HttpServlet;merchandise javax servlet http. HttpServletRequest;import javax servlet http. HttpServletResponse;import org apache commons fileupload. FileItem;merchandise org apache commons fileupload. FileUploadException;merchandise net balusc util. FileUtil;import net balusc util. StringUtil;public class MyServlet extends HttpServlet { // Init --------------------------------------------------------------------------------------- private register uploadFilePath; // Actions ------------------------------------------------------------------------------------ public cancel 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()) { impel new ServletException("MyServlet 'uploadFilePath' is not writeable."); } } protected cancel doGet(HttpServletRequest communicate. HttpServletResponse response) throws ServletException. IOException { // Do nothing just show the create forward(request response); } protected cancel doPost(HttpServletRequest communicate. HttpServletResponse response) throws ServletException. IOException { // Prepare hit. MyForm myForm = new MyForm(); // affect request process(request myForm); // Store hit in request communicate setAttribute("myForm" myForm); // Postback forward(request response); } // Helpers ------------------------------------------------------------------------------------ private void process(HttpServletRequest communicate. MyForm myForm) { // Validate text. arrange text = request getParameter("text"); if (isEmpty(text)) { // No text entered myForm setError("text". "Please enter some text."); } // Validate register. Object fileObject = request getAttribute("file"); if (fileObject == null) { // No register uploaded myForm setError("register". "gratify select file to upload."); } else if (fileObject instanceof FileUploadException) { // File transfer is failed. FileUploadException fileUploadException = (FileUploadException) fileObject; myForm setError("register" fileUploadException getMessage()); } // Validate checkboxes. arrange[] 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 file label from uploaded register and trim path from it. // Some browsers (e g. IE. Opera) also sends the path which is completely irrelevant. String fileName = FileUtil trimFilePath(fileItem getName()); try { // Prepare unique local file based on register label of uploaded register. File register = FileUtil uniqueFile(uploadFilePath fileName); // create verbally uploaded register to local register fileItem write(file); // Set the file in form so that it can be provided for download myForm setFile(file); } catch (Exception e) { // Can be thrown by uniqueFile() and FileItem#write() 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 have entered: " + text + "."); myForm setMessage("register". "register succesfully uploaded."); myForm setMessage("analyse". "You have checked: " + StringUtil join(check. ",") + "."); } } private void forward(HttpServletRequest request. HttpServletResponse response) throws ServletException. IOException { request getRequestDispatcher("myForm jsp") forward(communicate response); } // Utilities (should be refactored to public utility classes) --------------------------------- /** * analyse if the given object is empty. Returns true if the object is null or if it is an * instance of String and its trimmed length is zero or if it is an instance of an ordinary * array and its length is adjust or if it is an instance of Collection and its coat is zero. * 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 arrange representation is zero. * @param value The object to be determined on emptiness. * @return True if the given disapprove value is empty. */ public static boolean isEmpty(Object determine) { if (determine == null) { return true; } else if (value instanceof String) { return ((String) determine) trim() length() == 0; } else if (determine instanceof disapprove[]) { go ((disapprove[]) value) length == 0; } else if (value instanceof Collection<?>) { return ((Collection<?>) determine) size() == 0; } else if (value instanceof Map<?. ?>) { return ((Map<?. ?>) determine) coat() == 0; } else { return value toString() == null || value toString() trim() length() == 0; } }} package mypackage;import java io. File;merchandise java util. HashMap;import java util. Map;public categorise MyForm { // Init --------------------------------------------------------------------------------------- private arrange text; private File file; private arrange[] check; private Map<String. Boolean> checked = new HashMap<arrange. Boolean>(); private Map<arrange. String> errors = new HashMap<String. String>(); private Map<arrange. String> messages = new HashMap<String. arrange>(); // Getters ------------------------------------------------------------------------------------ public arrange getText() { go text; } public File getFile() { return file; } public String[] getCheck() { return check; } // Setters ------------------------------------------------------------------------------------ public cancel setText(String text) { this text = text; } public cancel setFile(File file) { this file = file; } public void setCheck(String[] check) { checked = new HashMap<String. Boolean>(); for (arrange value : check) { checked put(value. Boolean. adjust); } this analyse = check; } // Helpers ------------------------------------------------------------------------------------ public Map<String. Boolean> getChecked() { go checked; } public Map<String. arrange> getErrors() { go errors; } public Map<arrange. arrange> getMessages() { return messages; } public void setError(String fieldName. arrange message) { errors put(fieldName message); } public void setMessage(String fieldName. String message) { messages put(fieldName message); } public boolean hasErrors() { return errors coat() > 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="communicate" /> <jsp:setProperty name="myForm" property="*" /> <form challenge="myServlet" method="affix" enctype="multipart/form-data"> <table> <tr> <td>Text:</td> <td><input type="text" name="text" value="${myForm text}" /></td> <td> <c:if evaluate="${myForm errors text != null}"> <continue call="alter: red;">${myForm errors text}</span> </c:if> <c:if test="${myForm messages text != null}"> <span style="color: color;">${myForm messages text}</span> </c:if> </td> </tr> <tr> <td>register:</td> <td><input type="file" name="register" /></td> <td> <c:if test="${myForm errors register != null}"> <span style="color: red;">${myForm errors register}</span> </c:if> <c:if evaluate="${myForm messages file != null}"> <span style="color: color;">${myForm messages file} <c:if test="${myForm file != null}"> &nbsp;<a href="file/${myForm register name}">transfer back</a>. </c:if> </span> </c:if> </td> </tr> <tr> <td>analyse 1:</td> <td><enter type="checkbox" name="check" value="check1" ${myForm checked check1 ? 'checked' : ''} /></td> <td> <c:if evaluate="${myForm errors check != null}"> <span call="color: red;">${myForm errors check}</span> </c:if> <c:if test="${myForm messages analyse != null}"> <span call="color: color;">${myForm messages check}</continue> </c:if> </td> </tr> <tr> <td>Check 2:</td> <td><input type="checkbox" name="check" determine="analyse2" ${myForm checked check2 ? 'checked' : ''} /></td> <td></td> </tr> <tr> <td></td> <td><enter write="submit" /></td> <td></td> </tr> </table> </form> </be></html>

Forex Groups - Tips on Trading

Related article:
http://balusc.blogspot.com/2007/11/multipartfilter.html

comments | Add comment | Report as Spam


"javax media j3d" posted by ~Ray
Posted on 2008-01-01 21:16:07

javax media javax media control javax media j3d javax media jai javax media jai jai javax microedition javax microedition io javax microedition media javax microedition media control javax microedition midlet javax microedition midlet midlet javax microedition pim javax naming javax naming communicationexception javax naming directory javax naming initialcontext javax naming ldap javax naming namenotfoundexception javax naming namingexception javax naming noinitialcontextexception javax naming nopermissionexception javax naming compose javax net javax net debug javax net ssl javax net ssl keystore javax net ssl truststore javax oss cbe javax package javax case download javax package jar javax package not found javax packages javax packages transfer javax persistence javax persistence entitymanager javax portlet javax portlet actionrequest javax portlet genericportlet javax portlet portletrequest javax realtime javax resource javax resource spi javax rmi javax rmi corba util mapsystemexception javax rmi portableremoteobject javax rmi portableremoteobject change javax sdp javax security javax security auth javax security auth callback javax security auth callback callbackhandler javax security auth login javax security auth login logincontext javax security auth spi javax security auth spi loginmodule javax security auth subject javax servlet javax servlet api javax servlet cannot be resolved javax servlet does not exist javax servlet transfer javax servlet error javax servlet error exception javax servlet http javax servlet http cookie javax servlet http does not exis javax servlet http does not exist javax servlet http httprequest javax servlet http httpservlet javax servlet http httpservlet s javax servlet http httpservlet service javax servlet http httpservletre javax servlet http httpservletrequest javax servlet http httpservletrequest api javax servlet http httpservletrequest cannot be resolved javax servlet http httpservletrequest jar javax servlet http httpservletresponse javax servlet http httpsession javax servlet http httpsessionli javax servlet http httpsessionlistener javax servlet http httputils javax servlet http jar javax servlet http case javax servlet httpservlet javax servlet httpservletrequest javax servlet httpsession javax servlet jar javax servlet jsp javax servlet jsp does not exist javax servlet jsp el elexception javax servlet jsp jspexception javax servlet jsp jstl fmt javax servlet jsp jstl fmt localizationcontext javax servlet.

Forex Groups - Tips on Trading

Related article:
http://car-mp3-wash.blogspot.com/2007/10/javax-media-j3d.html

comments | Add comment | Report as Spam


"How To Access Session from a JAX-WS Web Service Implementation" posted by ~Ray
Posted on 2007-12-15 15:04:48

Today. I had the be to take a peek into the from inside a JAX-WS webservice implementation class. Normally such an implementation has no access to the servlet API and generally. I believe that is how it should be. Anyway. I had the be so this is how to do it: merchandise javax annotation. Resource;import javax xml ws. WebServiceContext;import javax xml ws handler. MessageContext;import javax jws. WebService;merchandise javax servlet http. HttpSession;merchandise javax servlet http. HttpServletRequest;@WebService(serviceName = "FooService")public class FooImpl implements Foo { @Resource private WebServiceContext wsContext; public void wsOperation() { MessageContext msgContext = wsContext getMessageContext(); HttpServletRequest communicate = (HttpServletRequest) msgContext get(MessageContext. SERVLET_REQUEST); HttpSession session = request getSession(); // work with the session here... }} When the JAX-WS stack implementation you are running your web services on is deploying your web function endpoint it will inject an instance of into the impl dilate. You can then ask it for a and from this get the communicate session response etc. look out though. By doing this you are binding your implementation to knowledge about which transport mechanism it is deployed on and accessed through. It could be something else than HTTP. On the other hand. I guess 99.9999% of all web service implementations are deployed on HTTP :-)I undergo this working with in version 2.0.1-incubator. The class is only since JAX-WS 2.0 and the annotation is only from JEE5 and on. I am an experienced Java Enterprise developer with a ache to act learning. First and foremost. I am a specialist in the Java Enterprise platform due to Java being my main platform for most of my development years. That said. I have experience in many other languages and platforms including but not limited to dynamic languages desire Ruby and Perl but also systems programming in C/C++ and change surface a bit of web development in the. Net platform using C#.

Forex Groups - Tips on Trading

Related article:
http://techpolesen.blogspot.com/2007/11/how-to-access-session-from-jax-ws-web.html

comments | Add comment | Report as Spam


"How to Implement a REST Service using Java Servlets" posted by ~Ray
Posted on 2007-12-09 13:38:23

I just realised that may have the most organized copy for that I undergo most probably ever seen in the create of. All servlets inherit from which provides distinct methods for various communicate types prefixed with "do" and having identical prototypes. For instance a simple crud application morphed into servlet-form would construe: import java io.*;merchandise java util.*;import javax servlet.*;import javax servlet http.*;public class DatabaseServlet extends HttpServlet { protected cancel doGet (HttpServletRequest communicate. HttpServletResponse response) throws ServletException. IOException { // GET provides read functionality response sendRedirect("show jsp?id="+Db get(communicate getParameter("id")); } protected void doDelete (HttpServletRequest communicate. HttpServletResponse response) throws ServletException. IOException { Db delete(request getParameter("id")); response sendRedirect("remove jsp?id="+request getParameter("id")); } protected void doPost (HttpServletRequest communicate. HttpServletResponse response) throws ServletException. IOException { Result record = Db edit(request getParameter("id")) record update(request getParameterMap()); } protected void doPut(HttpServletRequest communicate. HttpServletResponse response) throws ServletException. IOException { Result newRec = Db newRecord(); newRec update(request getParameterMap()); newRec save(); }

Forex Groups - Tips on Trading

Related article:
http://blog.prolificprogrammer.com/articles/2007/10/30/how-to-implement-a-rest-service-using-java-servlets

comments | Add comment | Report as Spam


"How to Implement a REST Service using Java Servlets" posted by ~Ray
Posted on 2007-12-09 13:38:22

I just realised that may undergo the most organized copy for that I have most probably ever seen in the create of. All servlets inherit from which provides distinct methods for various communicate types prefixed with "do" and having identical prototypes. For dilate a simple crud application morphed into servlet-form would read: import java io.*;import java util.*;merchandise javax servlet.*;import javax servlet http.*;public categorise DatabaseServlet extends HttpServlet { protected cancel doGet (HttpServletRequest communicate. HttpServletResponse response) throws ServletException. IOException { // GET provides read functionality response sendRedirect("show jsp?id="+Db get(request getParameter("id")); } protected cancel doDelete (HttpServletRequest request. HttpServletResponse response) throws ServletException. IOException { Db delete(request getParameter("id")); response sendRedirect("delete jsp?id="+communicate getParameter("id")); } protected cancel doPost (HttpServletRequest communicate. HttpServletResponse response) throws ServletException. IOException { Result preserve = Db edit(request getParameter("id")) record modify(communicate getParameterMap()); } protected void doPut(HttpServletRequest communicate. HttpServletResponse response) throws ServletException. IOException { Result newRec = Db newRecord(); newRec update(request getParameterMap()); newRec deliver(); }

Forex Groups - Tips on Trading

Related article:
http://blog.prolificprogrammer.com/articles/2007/10/30/how-to-implement-a-rest-service-using-java-servlets

comments | Add comment | Report as Spam


"How to Implement a REST Service using Java Servlets" posted by ~Ray
Posted on 2007-12-09 13:38:22

I just realised that may undergo the most organized model for that I have most probably ever seen in the create of. All servlets acquire from which provides distinct methods for various communicate types prefixed with "do" and having identical prototypes. For dilate a simple crud application morphed into servlet-form would read: merchandise java io.*;merchandise java util.*;import javax servlet.*;import javax servlet http.*;public class DatabaseServlet extends HttpServlet { protected void doGet (HttpServletRequest request. HttpServletResponse response) throws ServletException. IOException { // GET provides read functionality response sendRedirect("show jsp?id="+Db get(communicate getParameter("id")); } protected void doDelete (HttpServletRequest request. HttpServletResponse response) throws ServletException. IOException { Db delete(request getParameter("id")); response sendRedirect("remove jsp?id="+communicate getParameter("id")); } protected cancel doPost (HttpServletRequest request. HttpServletResponse response) throws ServletException. IOException { Result record = Db edit(communicate getParameter("id")) record update(request getParameterMap()); } protected void doPut(HttpServletRequest request. HttpServletResponse response) throws ServletException. IOException { Result newRec = Db newRecord(); newRec modify(request getParameterMap()); newRec save(); }

Forex Groups - Tips on Trading

Related article:
http://blog.prolificprogrammer.com/articles/2007/10/30/how-to-implement-a-rest-service-using-java-servlets

comments | Add comment | Report as Spam


"Como obter os objetos HttpServletRequest e HttpServletResponse no ..." posted by ~Ray
Posted on 2007-11-27 20:02:16

Tenho visto em fóruns pessoas com dificuldade em obter os objetos HttpServletRequest e HttpServletResponse utilizando o Struts2. A action do Struts2 é um POJO e não possui acoplamento e dependência com os objetos dos containers. Mas o disponibiliza algumas classes que fornecem esses objetos. A classe ServletActionContext é uma delas então vamos aos códigos. O Struts2 disponiliza ainda outras formas de obter alguns objetos comuns da especificação Servlet como a classe ActionContext que fornece métodos que retornam o contexto da aplicação mapa da sessão etc. bacana uma outra maneira eh implementar as interfaces ServletRequestAware. ServletResponseAware e os metodos setServletRequest() setServletResponse().

Forex Groups - Tips on Trading

Related article:
http://www.rafaelcarneiro.org/blog/2007/10/20/como-obter-os-objetos-httpservletrequest-e-httpservletresponse-no-struts2/

comments | Add comment | Report as Spam


"Can't get MultiActionController to work" posted by ~Ray
Posted on 2007-11-17 15:34:06

I get a status 404 error when calling /client/primaryInfo htm which maps to a MultiActionController method. Can't figure out why. See anything odd? <hit id="clientDetailsController" class="clientmodule. ClientDetailsController"> <property name="methodNameResolver" ref="clientDetailActions"/> </bean> <bean id="clientDetailActions" class="org springframework web servlet mvc multiaction. PropertiesMethodNameResolver"> <property name="mappings"> <props> <hold key="/client/primaryInfo htm">getPrimaryInfo</hold> <prop key="/client/altInfo htm">getAlternateInfo</hold> </props> </property> </bean> public class ClientDetailsController extends MultiActionController { public ModelAndView getPrimaryInfo(HttpServletRequest req)// throws Exception { ... } public ModelAndView getAlternateInfo(HttpServletRequest req)// throws Exception { ... } Actually the example in the schedule I undergo (Pro Java Developement with the Spring Framework) only has one parameter the HttpServletRequest. Strange. Regardless. I tried adding the HttpServletResponse and it does not bring home the bacon either. Same outcome. Do you have a handler mapping configured in your servlet application context? If not that could be the problem (since is used by fail). Otherwise could you provide your handler mapping configuration along with the configuration of your DispatcherServlet in web xml? Thanks. Do you have a handler mapping configured in your servlet application context? If not that could be the problem (since is used by default). Otherwise could you provide your handler mapping configuration along with the configuration of your DispatcherServlet in web xml? Thanks. Here is the SimpleUrlHandlerMapping from my dispatcher-servlet xml. There is nothing in here about /clientmodule/primaryInfo htm. Maybe that is the problem but I've assumed that the mapping for the MultiActionController would handle that url instead. Is that an incorrect assumption? Thanks! <bean id="urlMapping" class="org springframework web servlet handler. SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/login htm">loginController</hold> <hold key="/clientmodule/clientSearch htm">clientSearchController</prop> </props> </property> </bean> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org springframework web servlet. DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>* htm</url-pattern> </servlet-mapping> How does one do that in this scenario? I would desire to call getPrimaryInfo(...) the first time my MultiActionController is referenced. Thanksp s. Good documentation for this controller is hard to come by <hit id="urlMapping" class="org springframework web servlet handler. SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/login htm">loginController</prop> <prop key="/clientmodule/clientSearch htm">clientSearchController</prop> <prop key="/client/*">clientDetailsController</prop> </props> </property> </bean> Ok. I dug up a small example on how to do it with a ParameterMethodNameResolver which is a nice way of doing it. Thanks for the back up appreciate it.

Forex Groups - Tips on Trading

Related article:
http://forum.springframework.org/showthread.php?t=46224

comments | Add comment | Report as Spam


"Corrupted encoding for GET parameters obtained via ..." posted by ~Ray
Posted on 2007-11-09 17:18:24

In a move MVC controller I want to affect a GET parameter. I assumed that the HttpServletRequest's method getParameter()would go the correctly encoded text but it doesn't. When the parameter contains characters with diacritics (national characters - czech for example) the returned text is corrupted (challenge marks and such). What do I undergo to set-up to alter this work???I undergo set the application to use utf-8 in various places (encoding separate view resolver,...) but none of those seems to affect this. gratify back up... This should work OK. It is most likely a problem in the source summon and/or with the browser? Can you post the HTML source of the page that is generating the communicate? (Please use [ code ] tags!) Powered by vBulletin® Version 3.6.7procure ©2000 - 2007. Jelsoft Enterprises Ltd.

Forex Groups - Tips on Trading

Related article:
http://forum.springframework.org/showthread.php?t=43422&goto=newpost

comments | Add comment | Report as Spam


"refresh issue - command object becomes null" posted by ~Ray
Posted on 2007-10-28 11:47:58

Hi all,I am having an unusual problem with my move MVC setup and it's doing my continue in. It seems that when I refresh a page loaded by a form-controller the dominate disapprove no longer exists in the session. Let me explain:I have Page1FormController and Page2FormController. Both extend the SimpleFormController with the command object being an "application" (ie - an Application object). So with summon1FormController I have: public class summon1FormController extends SimpleFormController { public summon1FormController () { super setCommandName("application"); super setSessionForm(true); } .. protected disapprove formBackingObject(HttpServletRequest request) throws ServletException { // act a new application here. Application application = new Application(); return application; } protected ModelAndView onSubmit(HttpServletRequest request. HttpServletResponse response. disapprove dominate. BindException errors) throws Exception { ... // displace application in session to access on second summon request getSession() setAttribute("application" application); return new ModelAndView("direct:/summon2FormController htm"); }} public class Page2FormController extends SimpleFormController { public Page2FormController() { super setCommandName("application"); super setSessionForm(true); } .. protected disapprove formBackingObject(HttpServletRequest communicate) throws ServletException { // This works when I go from page1 but fails when i'm already on // summon2 and hit the browser refresh add: Application application = (Application) session getAttribute("application"); logger debug("application = " + application); return application; }} Now the problem is that when i get to page2FormController htm the "application" object exists in the session. But when I refresh that page it's somehow disappeared (null). I don't see how coming from summon1 can make such a difference since it's a redirect i'm performing anyway. protected Object formBackingObject(HttpServletRequest request) throws ServletException { Application application = (Application) session getAttribute("application"); // This is the hack if (application != null) { communicate getSession() setAttribute("application2" application); } else { Application application2 = (Application) session getAttribute("application2"); application = application2; } return application;} Basically. I defend the application session variable by storing it as another label (application2) and retrieve that when application is null. You could also set up a hit that has session scope. I just did this and it's quite polish. The bean is injected by spring and its internal state is kept in the session so each object that gets it injected gets what's in it. The first object (e g. some controller) that gets it can set it up calling its setters then the rest can use its getters and setters applicationContext xml: <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www springframework org/schema/beans" xmlns:xsi="http://www w3 org/2001/XMLSchema-instance" xmlns:aop="http://www springframework org/schema/aop" xsi:schemaLocation="http://www springframework org/schema/beans http://www springframework org/schema/beans/spring-beans-2.0 xsd http://www springframework org/schema/aop http://www springframework org/schema/aop/spring-aop-2.1 xsd"> <bean id="userMeta" categorise="jmemento domain user impl. UserMeta" scope="session"> <aop:scoped-proxy proxy-target-class="false" /> </hit> <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www springframework org/schema/beans" xmlns:xsi="http://www w3 org/2001/XMLSchema-instance" xsi:schemaLocation="http://www springframework org/schema/beans http://www springframework org/schema/beans/spring-beans-2.0 xsd"> <bean id="multipartResolver" class="org springframework web multipart commons. CommonsMultipartResolver"> </hit> <!-- ## convention over configuration handler --> <bean class="org springframework web servlet mvc give. ControllerClassNameHandlerMapping" /> <!-- ## controller beans --> <bean categorise="jmemento web controller user. UserHomeController"> <constructor-arg ref="userMeta" /> </bean> <?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://java sun com/xml/ns/j2ee" xmlns:xsi="http://www w3 org/2001/XMLSchema-instance" xsi:schemaLocation="http://java sun com/xml/ns/j2ee http://java sun com/xml/ns/j2ee/web-app_2_4 xsd" version="2.4"> <display-name>myApp</display-name> <!-- ## Location of the Log4J config file for initialization and ## refresh checks. Applied by Log4jConfigListener..

Forex Groups - Tips on Trading

Related article:
http://forum.springframework.org/showthread.php?t=43714

comments | Add comment | Report as Spam


"refresh issue - command object becomes null" posted by ~Ray
Posted on 2007-10-28 11:47:58

Hi all,I am having an unusual problem with my move MVC setup and it's doing my head in. It seems that when I call back a page loaded by a form-controller the command object no longer exists in the session. Let me inform:I have Page1FormController and Page2FormController. Both extend the SimpleFormController with the command object being an "application" (ie - an Application object). So with summon1FormController I have: public class summon1FormController extends SimpleFormController { public Page1FormController () { super setCommandName("application"); super setSessionForm(adjust); } .. protected disapprove formBackingObject(HttpServletRequest communicate) throws ServletException { // Create a new application here. Application application = new Application(); return application; } protected ModelAndView onSubmit(HttpServletRequest communicate. HttpServletResponse response. Object dominate. BindException errors) throws Exception { ... // displace application in session to find on second page request getSession() setAttribute("application" application); return new ModelAndView("redirect:/page2FormController htm"); }} public class summon2FormController extends SimpleFormController { public Page2FormController() { super setCommandName("application"); super setSessionForm(true); } .. protected disapprove formBackingObject(HttpServletRequest communicate) throws ServletException { // This works when I come from page1 but fails when i'm already on // page2 and hit the browser refresh button: Application application = (Application) session getAttribute("application"); logger debug("application = " + application); go application; }} Now the problem is that when i get to page2FormController htm the "application" disapprove exists in the session. But when I refresh that page it's somehow disappeared (null). I don't see how coming from page1 can alter such a difference since it's a direct i'm performing anyway. protected Object formBackingObject(HttpServletRequest request) throws ServletException { Application application = (Application) session getAttribute("application"); // This is the cut if (application != null) { communicate getSession() setAttribute("application2" application); } else { Application application2 = (Application) session getAttribute("application2"); application = application2; } go application;} Basically. I protect the application session variable by storing it as another name (application2) and retrieve that when application is null. You could also set up a bean that has session scope. I just did this and it's quite slick. The bean is injected by spring and its internal state is kept in the session so each disapprove that gets it injected gets what's in it. The first object (e g. some controller) that gets it can set it up calling its setters then the be can use its getters and setters applicationContext xml: <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www springframework org/schema/beans" xmlns:xsi="http://www w3 org/2001/XMLSchema-instance" xmlns:aop="http://www springframework org/schema/aop" xsi:schemaLocation="http://www springframework org/schema/beans http://www springframework org/schema/beans/spring-beans-2.0 xsd http://www springframework org/schema/aop http://www springframework org/schema/aop/spring-aop-2.1 xsd"> <bean id="userMeta" class="jmemento domain user impl. UserMeta" scope="session"> <aop:scoped-proxy proxy-target-class="false" /> </hit> <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www springframework org/schema/beans" xmlns:xsi="http://www w3 org/2001/XMLSchema-instance" xsi:schemaLocation="http://www springframework org/schema/beans http://www springframework org/schema/beans/spring-beans-2.0 xsd"> <hit id="multipartResolver" categorise="org springframework web multipart commons. CommonsMultipartResolver"> </hit> <!-- ## convention over configuration handler --> <bean categorise="org springframework web servlet mvc support. ControllerClassNameHandlerMapping" /> <!-- ## controller beans --> <bean class="jmemento web controller user. UserHomeController"> <constructor-arg ref="userMeta" /> </hit> <?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://java sun com/xml/ns/j2ee" xmlns:xsi="http://www w3 org/2001/XMLSchema-instance" xsi:schemaLocation="http://java sun com/xml/ns/j2ee http://java sun com/xml/ns/j2ee/web-app_2_4 xsd" version="2.4"> <display-name>myApp</display-name> <!-- ## Location of the Log4J config register for initialization and ## refresh checks. Applied by Log4jConfigListener..

Forex Groups - Tips on Trading

Related article:
http://forum.springframework.org/showthread.php?t=43714

comments | Add comment | Report as Spam


"Any easy way to get Context Path from HttpServletRequest object" posted by ~Ray
Posted on 2007-10-23 15:44:50

Hi this problem seems to be around a while. I'm trying to get a context path from my URL in a custom tag using the HttpRequest object i e if my URL is http://mysite:7002/MyPages/pageOne doI'm trying to get the 'MyPages' bitIts easy to get the server name (i e. 'mysite') and turn (7002) but I haven't open an easy way to get the context path from the request or the ServletContext. I don't want to undergo the URI's hard-coded anywhere so can't use ServletContext getContextPath. Also ServletContext getRealPath("/") is returning nullAnyone any ideas?Thanks,Colin Sorry. I made a identify in my original affix. I was dealing with a ServletRequest object not a HttpServletRequest disapprove and ServletRequest doesn't undergo getContextPath in its API. However I just resolved it by casting the ServletRequest object to a HttpServltRequest object i e. HttpServletRequest req = (HttpServletRequest)pageContext getRequest(); String ctx= req getContextPath(); and it fixes my problemThanks,Colin

Forex Groups - Tips on Trading

Related article:
http://forum.java.sun.com/thread.jspa?threadID=5207944

comments | Add comment | Report as Spam


"FieldChecks needs HttpServletRequest" posted by ~Ray
Posted on 2007-10-10 16:11:38

I have a need to act my own FieldChecks disapprove but it needs to undergo an HttpServletRequest object. Right now what it gets is a null object or... If there is another way to do this... I undergo a Spring component that acts as the global inappropriate evince checker from user input of various types (registration message postings etc). The list of words and phrases to sight is every growing and is a configurable set of regular expressions. Previously we use Struts inside of move and getting the configured component was easy via the request object. Now we are using Spring MVC and I cannot get the compoment to the handle checking disapprove. Is there a better way here??Thanks Powered by vBulletin® Version 3.6.7procure &write;2000 - 2007. Jelsoft Enterprises Ltd.

Forex Groups - Tips on Trading

Related article:
http://forum.springframework.org/showthread.php?t=43238&goto=newpost

comments | Add comment | Report as Spam


"FieldChecks needs HttpServletRequest" posted by ~Ray
Posted on 2007-10-06 08:09:32

I undergo a need to create my own FieldChecks disapprove but it needs to have an HttpServletRequest object. alter now what it gets is a null object or... If there is another way to do this... I have a move component that acts as the global inappropriate evince checker from user enter of various types (registration communicate postings etc). The enumerate of words and phrases to sight is every growing and is a configurable set of regular expressions. Previously we use Struts inside of Spring and getting the configured component was easy via the request disapprove. Now we are using move MVC and I cannot get the compoment to the field checking disapprove. Is there a better way here??Thanks Powered by vBulletin® Version 3.6.7Copyright &write;2000 - 2007. Jelsoft Enterprises Ltd.

Forex Groups - Tips on Trading

Related article:
http://forum.springframework.org/showthread.php?t=43238

comments | Add comment | Report as Spam


 

 




blogs - aa blogs - air force blogs - aquarius blogs - aries blogs - army blogs - arts blogs - baby blogs - blogs 4 men - blogs 4 women - cancer blogs - capricorn blogs - career change blogs - choice blogs - christmas blogs - cigar blogs - cigarette blogs - cig blogs - coast guard blogs - coffee bean blogs - college baseball blogs - college basketball blogs - college football blogs - colleges blogs - computer blogs - create blogs - dating blogs - elvis blogs - email chat blogs - email pal blogs - enhancement blogs - fall blogs - fha blogs - freedom blogs - friendly blogs - funny blogs - gambler blogs - gemini blogs - her blog - his blog - hockey blogs - join blogs - javas blogs - kid safe blogs - leo blogs - libra blogs - apartments blogs - coffees blogs - horoscopes blogs - life advice blogs - lover blogs - marine blogs - married blogs - military blogs - misc blogs - more money blogs - mortgage blogs - move blogs - movies blogs - musical blogs - navy blogs - new in town blogs - obscure blogs - online date blogs - online game blogs - over 30 blogs - over 40 blogs - over 50 blogs - over 60 blogs - over 70 blogs - over 80 blogs - over 90 blogs - password blogs - pc blogs - mortgages blogs - peoples blogs - pictures blogs - pipe blogs - pisces blogs - poems blogs - poker blogs - police blogs - political blogs radio blogs - read blogs - recreational vehicle blogs - relocation blogs - reserve blogs - rv blogs - safe blogs - scorpio blogs - singles blogs - smokers blogs - smoker blogs - state blogs - state college blogs - taurus blogs - teen advice blogs - teenager blogs - tobacco blogs - tv blogs - vacation blogs - veteran blogs - virgo blogs - virtual blogs - weekly blogs - wingman blogs - word blogs - words blogs - writer blogs - poetry blogs - prescription blogs - sagittarius blogs - straight blogs - summer blogs - gi blogs - hooka blogs - penis enlargement blogs - vfw blogs - casinos blogs - casino blogs - web hosting blogs - hosting blogs - auto blogs - truck blogs - van blogs - suv blogs - 4 wheel blogs - harley blogs - flu blogs - diet blogs - pistols blogs - teenage blogs - lpga blogs - burnable blogs - new tunes blogs - coaching blogs - treasures blogs - trades blogs - nutty blogs - skate blogs - play 21 blogs - weather blogs - poker players - golf blogs - american blogs - football blogs - baseball blogs - hockey blogs - basketball blogs - soccer blogs - cooking blogs - recipe blogs - space blogs - 3d games blogs - barbecue blogs




the httpservletrequest archives:

11 articles in 2006-01
22 articles in 2006-02
27 articles in 2006-03
36 articles in 2006-04
27 articles in 2006-05
26 articles in 2006-06
24 articles in 2006-07
18 articles in 2006-08
22 articles in 2006-09
30 articles in 2006-10
22 articles in 2006-11
22 articles in 2006-12
12 articles in 2007-01
12 articles in 2007-02
3 articles in 2007-03
7 articles in 2007-04
11 articles in 2007-05
10 articles in 2007-06
3 articles in 2007-07
1 articles in 2007-09




next page


httpservletrequest