Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to assign names to buttons and tell which button was pressed in the Action class?

 
Peter Primrose
Ranch Hand
Posts: 755
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

Up until today I had only 2 buttons in my struts pages (usually submit and cancel). They worked fine since I used to ask the code below in my Action class:



If it wasn�t cancel � it was submit and life was easy and fun.

So�what if I have 5 buttons in my page, how can I tell which button the user has pressed?

In swing, that�s easy: JButton b1 = new JButton() and later:
If (e.getSource==b1) //I call it by the name
{

}


How can I assign names to each button and tell in my action class which button was pressed.

Thanks
 
Merrill Higginson
Ranch Hand
Posts: 4864
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Like this:

In your JSP:
<html:submit property="colorButton" value="red" />
<html:submit property="colorButton" value="blue" />
<html:submit property="colorButton" value="green" />
<html:submit property="colorButton" value="orange" />

In your ActionForm:


In the execute method of your Action class:

You could also make your Action extend DispatchAction.

P.S. Just so you know, in the case of a cancel button, The Action class has an isCancelled method that accomplishes the same thing as your code above.
[ October 05, 2006: Message edited by: Merrill Higginson ]
 
Peter Primrose
Ranch Hand
Posts: 755
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
*PERFECT*

I did this (disregard the naming and the fw, only for testing):
struts-config.xml


and the bean


the coode in the jsp just as you instructed and when it gets to the ACTION, I did this:

String action = (String)((DynaActionForm)form).get("colorButton");

I did this without the usage of DispatchAction. I wonder what is the value of DispatchAction and would that eliminate the bean? if so, how would the Action look like (I must get the property somehow?!)

thank you Merrill!
 
Merrill Higginson
Ranch Hand
Posts: 4864
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
DispatchAction would not eliminate the need for an ActionForm bean. It is used if you want to avoid a long if/else structure in your program. It allows you to create individual methods for each of the buttons that are automatically called by DispatchAction.

This link gives a good explanation of what DispatchAction does and how to use it.
[ October 06, 2006: Message edited by: Merrill Higginson ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic