Home > Articles > Web Services > XML

  • Print
  • + Share This
From the author of

Saving User Choices

The form action is simple; all it does is set the preferred style in a cookie, reload the original page, and close the window:

Saving the Choice in ASP

Save the form action as prefs_action.asp:

<%@ language = "VBSCRIPT" %>
 Response.Cookies("stylechoice") = Request.Form("choice")
<script type="text/javascript">

This page has two sections. The first section, the ASP command, simply sets the stylechoice cookie, giving it the value that was submitted with the form. The second section outputs Javascript commands that the browser will execute.

Saving the Choice in Java

This form action should be saved as prefs_action.java in the classes folder, and compiled to prefs_action.class:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class prefs_action extends HttpServlet {

  public void doPost(HttpServletRequest request, 
            HttpServletResponse response)
  throws IOException, ServletException
    PrintWriter out = response.getWriter();

    String stylechoice = request.getParameter("choice");
    Cookie styleCookie = new Cookie("stylechoice", stylechoice);

    out.println("<script type=\"text/javascript\">");
    out.println("  self.opener.location=self.opener.location;");
    out.println("  self.close();");

In this case, rather than a doGet() method, we have a doPost() method because the form was set to submit via the post method rather than the get method.

This method starts out just as before, sending the header information and creating the out PrintWriter. Next, we get the value submitted on the form using the getParameter() method, and use it to create the Cookie object. We then add the styleCookie object to the response.

The rest of the method sends JavaScript to the browser for execution.

The Result

When all is said and done, the browser will have received a new cookie (or cookie value, if the cookie already existed) and two Javascript commands. The first is


The reference self.opener refers to the window object that caused this window to open. In this case, that's the main Primary Outpost window. This command causes it to set the location to the current location—in other words, to reload the page. For now, this will have no obvious purpose, but next we will add code to the main page that causes the choice to take effect.

Finally, the last command, self.close(), closes the popup window.

To see this in action, submit the form in the popup window.

  • + Share This
  • 🔖 Save To Your Account