Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added discussion of local variable to highlight part of the compliant example code, plus cleaned up wording a little.

...

This compliant solution stores the last parameter in the HttpSession object, which is provided as part of the HttpServletRequest. The servlet mechanism keeps track of the session, providing the client with the session's ID, which is stored as a cookie by the client's browser. The other information in the session, including the last attribute, are stored by the server. Consequently, the servlet provides the last value that was presented to the servlet in the same session (irregardless of what avoiding race conditions with requests from other sessions are making requests).). The local variable, which temporarily holds data in this example, is not vulnerable to race conditions in a singleton.  

Code Block
bgColor#ccccff
langjava
public class SampleServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");

    String current = request.getParameter("current");
    HttpSession session = request.getSession();
    Object attr = session.getAttribute("last");
    String last = (attr == null) ? "null" : attr.toString();

    if (current != null) {
      out.println("Current Parameter:");
      out.println(sanitize(current));
      out.println("<br>Last Parameter:");
      out.println(sanitize(last));
    };

    out.println("<p>");
    out.print("<form action=\"");
    out.print("SampleServlet\" ");
    out.println("method=POST>");
    out.println("Parameter:");
    out.println("<input type=text size=20 name=current>");
    out.println("<br>");
    out.println("<input type=submit>");
    out.println("</form>");

    session.setAttribute("last", current);
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
    doGet(request, response);
  }

  // Filter the specified message string for characters
  // that are sensitive in HTML.
  public static String sanitize(String message) {
    // ...
  }
}

...