Using JavaScript to submit a form in Struts

May 22nd, 2011No Comments

You can submit a form with a link as below. 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.

Java Script Part

  1. <input type=’hidden’ value=’myAction’ />
  2. <input type=’button’ value=’Save’    onclick=’document.forms["myForm"].myAction.value=”save”;
  3. document.forms["myForm"].submit();’ />
  4. <input type=’button’ value=’Delete onclick=’document.forms["myForm"].myAction.value=”delete”;
  5. document.forms["myForm"].submit();’ />

Java Part

  1. class MyAction extends ActionForm implements Serializable {
  2. public ActionForward execute (ActionMapping map, ActionForm form, HttpServletRequest  req, HttpServletResponse res ) {
  3. String myAction = req.getParameter(“myAction”);
  4. if (myAction.equals(“save”) {
  5. // …  code part comes here for save function  …
  6. } else if (myAction.equals(“delete”) {
  7. // …  code part comes here for delete function  …
  8. }
  9. }
  10. }
  11. }

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.

VN:F [1.9.10_1130]
Rating: 10.0/10 (3 votes cast)
VN:F [1.9.10_1130]
Rating: +4 (from 4 votes)

Using JavaScript to submit a form in Struts, 10.0 out of 10 based on 3 ratings

About author:

All entries by

Leave a Reply