Skip to Main Content
Jakarta Struts Cookbook
book

Jakarta Struts Cookbook

by Bill Siggelkow
February 2005
Intermediate to advanced content levelIntermediate to advanced
528 pages
12h 53m
English
O'Reilly Media, Inc.
Content preview from Jakarta Struts Cookbook

7.7. Determining the Action Based on User Input

Problem

You want to change the target action for a form based on user input.

Solution

Call a JavaScript function, like the one shown in Example 7-5, from an event handler on the HTML control that determines the action.

Example 7-5. JavaScript function to change a form's action

<script>
      function swapAction(control) {
        formAction = document.getElementById("empForm").action;
        if (control.checked)
          newAction = '<html:rewrite page="/CreateEmployee.do"/>';
        else
          newAction = '<html:rewrite page="/UpdateEmployee.do"/>';
        document.getElementById("empForm").action = newAction;
      }
</script>
<html:form styleId="empForm" action="/UpdateEmployee">
    New Employee: <html:checkbox property="create" 
      onclick='swapAction(this)"'/><br />
    ... rest of the page

Discussion

JavaScript makes this problem easy to solve. You might be tempted to hardcode the new value for the action in the function. However, the function will be a lot more robust if you use the html:rewrite tag. Using this tag ensures the action URI includes the appropriate application context prefix. It generates the session token if cookies are disabled. You can verify this works by disabling cookies on your browser. If you clicked the "New Employee" checkbox and submit the form you'd see a URL like the following:

http://localhost/jsc-ch05/CreateEmployee.do;jsessionid=
C0691FF1D538431815A448C4278BA999

If you had hardcoded the action, you'd lose the session. The drawback to this solution is you must specify the ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Jakarta Struts

Programming Jakarta Struts

Chuck Cavaness
Beginning Spring Framework 2

Beginning Spring Framework 2

Bruce Snyder, Sing Li, Anne Horton, Thomas Van de Velde, Naveen Balani, Christian Dupuis
Java Cookbook

Java Cookbook

Ian F. Darwin
Struts 2 in Action

Struts 2 in Action

J. Scott Stanlick, Chad Michael Davis, Donald J. Brown

Publisher Resources

ISBN: 059600771XSupplemental ContentErrata Page