This snippet is from a servlet which acts as a generic form posting utility used throughout some of my sites. Irrelevant of the dressing of the JSP, it can be presenting the user a form for any number of reasons, but in each case when submitted the form contents will be emailed to my site admins. The initial problem I encountered whilst writing was that when you iterate the submitted request parameters, the order they come out will be at random. So you can either parse the request query itself OR give your form fields names which when alphabetically sorted will make sense. The latter is the quickest method.. Anyway here is the servlet, It uses collections to first construct a List, which you can then use Collections to sort, and finally use Collections again to create a new Enumeration of the sorted list. Enough babble heres the code :
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ StringBuffer sb = new StringBuffer(); sb.append("The following information was posted via the website;\n\n"); // Sort the list List paramList = Collections.list(request.getParameterNames()); Collections.sort(paramList); Enumeration sortedList = Collections.enumeration(paramList); // iterate the list and append to a StringBuffer for (Enumeration e = sortedList; e.hasMoreElements();) { String paramName = (String) e.nextElement(); String[] values = request.getParameterValues(paramName); sb.append(paramName + " = " + values[0] + "\n"); sb.append("\n"); } // Email admin the sorted form contents Utils.Send_SMTP("mailer@dbws.net", Utils.adminEmails, "Website Form Submission", sb.toString()); request.getRequestDispatcher("thankyou.jsp").forward(request, response); }