Recipe7.7.Determining the Action Based on User Input


Recipe 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 style 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 Struts ActionServlet mapping prefix or extension (for example, /action or .do). Unlike the html:link tag, the Struts 1.1 html:rewrite tag doesn't support the action attribute, which would eliminate this problem. Struts 1.2 corrects this annoyance; the html:rewrite tag supports the action attribute like the html:link tag.

See Also

An interesting thread on this discussion from the struts-user mailing list can be found at http://marc.theaimsgroup.com/?l=struts-user&m=107885895821471&w=2.



    Jakarta Struts Cookbook
    Jakarta Struts Cookbook
    ISBN: 059600771X
    EAN: 2147483647
    Year: 2005
    Pages: 200

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net