Using JavaScript to submit a form in Struts

By: Apache Foundation  

You can submit a form with a link as below. BTW, the examples below assume you are in an <html:form> block and 'myForm' is picked up from the struts-config.xml name field of the action.


    <a href='javascript:void(document.forms["myForm"].submit()>My Link</a>

Now the trick in the action is to decode what action you intend to perform. Since you are using JavaScript, you could set a field value and look for it in the request or in the form.

... html/javascript part ...


        <input type='hidden' value='myAction' />
        <input type='button' value='Save Meeeee'
            onclick='document.forms["myForm"].myAction.value="save";
                     document.forms["myForm"].submit();' />
        <input type='button' value='Delete Meeeee'
            onclick='document.forms["myForm"].myAction.value="delete";
                     document.forms["myForm"].submit();' />

... the java part ...


        class MyAction extends ActionForm implements Serializable {

            public ActionForward execute (ActionMapping map, ActionForm form,
                HttpServletRequest req, HttpServletResponse) {

                    String myAction = req.getParameter("myAction");

                    if (myAction.equals("save") {
                           // ...  save action  ...
                    } else if (myAction.equals("delete") {
                           // ...  delete action  ...
                    }
                }
            }
        }

This is just one of many ways to achieve submitting a form and decoding the intended action. Once you get used to the framework you will find other ways that make more sense for your coding style and requirements. Just remember this example is completely non-functional without JavaScript.




Archived Comments

1. Hello! I've been following your weblog for a while now and finally got the bravery to go ahead and g
View Tutorial          By: Pole dance barcelona at 2017-05-04 12:33:18

2. coficoh
View Tutorial          By: coficoh at 2017-04-23 07:35:38

3. eetinudx
View Tutorial          By: eetinudx at 2017-04-23 07:03:20

4. ofpokuhoqarin
View Tutorial          By: ofpokuhoqarin at 2017-04-23 06:58:09

5. raxiiwaekosej
View Tutorial          By: raxiiwaekosej at 2017-04-23 06:52:11

6. But what will happen when user clicks on a link which submits the form and the user session has alre
View Tutorial          By: Force login page at 2012-12-03 16:58:37

7. nice
View Tutorial          By: srfds at 2012-05-28 09:25:15

8. how do i write the above same code using ajax and jquery?
View Tutorial          By: Karthik at 2011-08-29 11:21:45


Most Viewed Articles (in Struts )

Latest Articles (in Struts)

Comment on this tutorial