Image buttons in Struts (using ImageButtonBean class)

Basically, the recipe for using image buttons using the Struts tag library can be found on this page at j2ee.lagnada.com and this excerpt uit Ted Husted’s book Struts in Action.

Read on to see what I have to add to this.

Let me first illustrate why you would want image buttons πŸ˜‰

ImageButtonScreenShot

Basically, I thought it was unclear from Ted Husted’s page what to put exactly in the JSP page, and to be more specific, what established ‘the link’ between the image button in the JSP page and the corresponding field in the ActionForm.

Moreover, I did not understand why Ted Husted defined his own ImageButtoBean class, while there was one already present in the Stuts framework itself (maybe he has been working with an older Struts version?).

Combining the information of the above resources and using the ImageButtoBean class from the Struts framework, my solution is as follows:

In the JSP page, create image buttons as follows:

<html:image property="authorSearchButton" src="images/searchIcon.jpg" alt="authorSearch" />

In your ActionForm, create a corresponding member variable for this button with getter and setter methods:

import org.apache.struts.util.ImageButtonBean;

private ImageButtonBean authorSearchButton = new ImageButtonBean();

public void setAuthorSearchButton(ImageButtonBean button)
{
    this.authorSearchButton = button;
}

public ImageButtonBean getAuthorSearchButton()
{
    return this.authorSearchButton;
}

Note the correspondence of the name in the JSP page and the ActionForm (explained nicely on the above mentioned the HTML buttons webpage).

Also, add a isSelected() method to your ActionForm:

public int getSelected()
{
    if (getAuthorSearchButton().isSelected())
    {
          return AUTHOR_SEARCH;
    }
}

I use an int value, but you may choose your own type, of course.

Now you can use this method in your Action class, so this could be something like

public ActionForward execute(
    ActionMapping mapping,
    ActionForm actionForm,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception
{
    int selected = ((PublicationSearchForm) actionForm).getSelected();

    switch (selected)
    {
        case AUTHOR_SEARCH:
        // etc.

Since I have multiple image buttons on my form, I implemented a switch statement. Now I can take appropriate actions to each of the button presses!

Note also that this solution is elegant in the sense that it doesn’t rely on Javascript.

12 Comments

  1. gaurav December 11, 2007
  2. Pingback: AdSense Money Maker March 27, 2007
  3. Jon October 26, 2005
  4. Natalia August 12, 2005
  5. Aino July 18, 2005
  6. Ionamin3 July 17, 2005
  7. Zeger Hendrikse July 5, 2005
  8. Tony July 1, 2005
  9. Umashankar June 24, 2005
  10. Olaf Geibig February 22, 2005
  11. Leon van Tegelen August 26, 2004
  12. Zeger Hendrikse August 26, 2004
  13. Jasper August 26, 2004