Using JavaScript to submit a form in Struts

By: Apache Foundation Viewed: 153452 times    

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.

Most Viewed Articles (in Struts )

Latest Articles (in Struts)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

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

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

3. But what will happen when user clicks on a link wh
View Tutorial          By: Force login page at 2012-12-03 16:58:37

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

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

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

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

8. Hello! I've been following your weblog for a while
View Tutorial          By: Pole dance barcelona at 2017-05-04 12:33:18