Handling multiple buttons in HTML Form in Struts

By: Charles Emailed: 1697 times Printed: 2200 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

The <html:submit> tag  is used to submit the HTML form. The usage of the tag is as follows:

<html:submit><bean:message key=”button.save”/></html:submit>

This will generate a HTML as follows.

<input type="submit" value="Save Me">

This usually works okay if there was only one button with “real” Form submission (The other one maybe a Cancel button). Hence it suffices to straight away process the request in CustomerAction. However you will frequently face situations where there are more than one or two buttons submitting the form. You would want to execute different code based on the buttons clicked. If you are thinking, “No problem. I will have different ActionMapping (and hence different Actions) for different buttons”, you are out of luck! Clicking any of the buttons in a HTML Form always submits the same Form, with the same URL. The Form submission URL is found in the action attribute of the form tag as:

<formname=”CustomForm”action=”/App1/submitCustomerForm.do”/>

and is unique to the Form. You have to use a variation of the <html:submit> as shown below to tackle this problem.

<html:submit property=”step”>
<bean:message key=”button.save”/>
</html:submit>

The above SubmitTag, has an additional attribute named property whose value is step. The meaning of the property attribute is similar to that in <html:text> - It represents a JavaBeans property in the ActionForm and generates the name of the Form input element. This tag generates a HTML as follows 

<input type="submit" name=”step” value="Save Me">

The generated HTML submit button has a name associated with it. You have to now add a JavaBeans property to your ActionForm whose name matches the submit button name. In other words an instance variable with a getter and setter are required. If you were to make this change in the application just developed, you have to add a variable named “step” in the CustomerForm and then add two methods getStep() and setStep(). The Struts Framework sets the value of the step by Introspection, just like it does on the other fields. In the CustomerAction, the logic corresponding to the Save Me button is executed after performing a check for the Save Me button. Listing below shows the modified execute() method from CustomerAction. The changes are shown in bold. When the Save Me button is pressed, the custForm.getStep() method returns a value of “Save Me” and the corresponding code block is executed.  

// CustomerAction modified for multiple button Forms
public class CustomerAction extends Action
{
public ActionForward execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
if (isCancelled(request)) {
System.out.println(Cancel Operation Performed”);
return mapping.findForward(“mainpage”);
}
CustomerForm custForm = (CustomerForm) form;
ActionForward forward = null;
if ( “Save Me”.equals(custForm.getStep()) ) {
System.out.println(“Save Me Button Clicked”);

String firstName = custForm.getFirstName();
String lastName = custForm.getLastName();
System.out.println(“Customer First name is “ +
firstName);
System.out.println(“Customer Last name is “ +
lastName);
forward = mapping.findForward(“success”);
}

return forward;
}
}

In Struts applications, when using regular buttons, it is customary for all submit buttons to have the same name (except Cancel and Reset buttons). This is for convenience purposes. In HTML, when a form is submitted, only one of the submit buttons is pressed and hence only the value of that button is submitted. The ActionForm can thus have a single instance variable for all the submit buttons in its Form. This makes the if-else check in the Action class easier. Suppose that the HTML Customer Form that we show to the users has another button with label “Spike Me”. The submit button can still have the name “step” (same as the “Save Me” button). This means the CustomerForm class has a
single JavaBeans property “step” for the submit buttons. In the  CustomerAction you can have check if the custForm.getStep() is “Save Me” or “Spike Me”. If each of the buttons had different names like button1, button2 etc. then the CustomerAction would have to perform checks as follows:

if (“Save Me”.equals(custForm.getButton1()) {
// Save Me Button pressed
} else if (“Spike Me”.equals(customForm.getButton2()) {
// Spike Me button pressed
}

Using the HTML Button Label to distinguish the buttons works for most of the cases except when you have a internationalized Struts web application. Consider the HTML rendered for a Spanish user. By virtue of the Message Resource Bundles (<bean:message> tag), the Spanish user will see a label of “Excepto Mí” instead of “Save Me”. However the CustomerAction class is still looking for the hard coded “Save Me”. Consequently the code block meant for “Save Me” button never gets executed.


Struts Home | All Struts Tutorials | Latest Struts Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(11)


1. View Comment

This tutorial is very good. Actually I have been searching the solution for a such a problem that you have sloved. But I have not understood The last topic of this tutorial regarding internationalized Struts web application in this context. How the value remain same as "Save Me" but the spanish person see it as "âExcepto Míâ. The Key that shows âExcepto Míâ instand of "Save Me" obviously set your bean step property to the value âExcepto Míâ but not "Save Me" and your action class has no way to know it that it means Save Me. You have to hard code the if clause to handle Excepto Mí as well.

View Tutorial          By: farhaan at 2008-03-20 15:22:13
2. View Comment

farhaan, thats why I said, "Using the HTML Button Label to distinguish the buttons works for most of the cases except when you have a internationalized Struts web application." in the last para. Therefore in this case, like you have rightly suggested that we may use a ( || ) or clause in the if statement to handle multiple strings.

View Tutorial          By: Charles at 2008-03-21 01:36:46
3. View Comment

hello sir

i am simulating railway reservations system using servlets technology.

i m using HTML client and JAVA server

i have multiple submit buttons in a single form in my HTML script

how to retrieve the values in my form into the java file

my server code is :

public class insert_into_DB extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
Connection con;
Statement s;
ResultSet rs;


/* I NEED MY VALUES IMPORTED FROM HTML FILE HERE */


res.setContentType("text/html");
PrintWriter out=res.getWriter();
try
{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:civilsupp");
s=con.createStatement();
String str="insert into shop values("+s1+",'"+s2+"',"+s3+","+s4+","+s5+")";
s.executeUpdate(str);
out.println("<html>");
out.println("<center><br><br><h3>ADDED<br><br>");
out.println("</html>");
con.close();
}
catch(Exception e)
{
out.println(e);
}
}
}

*********** THANK YOU *************


View Tutorial          By: karthick at 2008-08-30 03:09:42
4. View Comment

To handle multiple submit buttons you can use standard Struts1 classes DispatchAction EventDispatchAction LookupDispatchAction

View Tutorial          By: Vic at 2008-12-23 12:03:43
5. View Comment

Thanks for the solution. I must say however that this solution works ALL the time, including internationalized apps. Here is how to make it work:

1) in your JSP you refer to the resourceBundle to set the value of the submit button
(i.e. <bean:message key=âbutton.saveâ/>)

2) use the same value in your action.
e.g.
ResourceBundle res = ResourceBundle.getBundle("ApplicationResources",(Locale) request.getSession().getAttribute(Globals.LOCALE_KEY));

if(custForm.getStep().equals(res.getString("button.save"))){
//Do your stuff here
{

This way, the resource bundle will always give you the value corresponding to the locale.

Cheers,
Pierre


View Tutorial          By: Pierre at 2009-11-19 20:16:35
6. View Comment

Thank you so much. I have migrated from the .NET to the J2EE platform and I was missing the Event Model(Click Event) , until this.

Thanks.


View Tutorial          By: kanika at 2011-05-31 12:23:33
7. View Comment

thanks for this tutorial! it's very useful

View Tutorial          By: Miguel at 2011-06-26 21:15:00
8. View Comment

Very useful tutorial. But if same code is executed for both the buttons in the struts-config file then how would it be possible to write separate forward for each button.

View Tutorial          By: Jitendra Kumar Mahto at 2011-08-12 15:10:14
9. View Comment

HI, Thanks for your beautiful tutorial.

I have two buttons in one form and having two different actions my frame work is like that. How i can handle this situation .

Any suggestions will be appreciated.

Thanks In Advance.

Chintan


View Tutorial          By: Chintan at 2011-10-06 07:35:01
10. View Comment

great !!!!!!!!!!!!!!!!!!!!!

View Tutorial          By: arjun at 2012-03-24 14:55:10
11. View Comment

Awesome post....

View Tutorial          By: Zeeshan Ali Ansari at 2012-11-24 06:35:20

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Charles
arraycopy example in Java
Action listeners in JSF
Automatically Including Preludes and Codas in JSP
Using realloc() Function in C
Handling multiple buttons in HTML Form in Struts
Fopen and Getc implementation program in C
Pointers to Structures example program in C
Pointers vs. Multi-dimensional Arrays in C
getch and ungetch in C
Bitwise Operators in C
Variables and Arithmetic Expressions in C
Differences between JavaServer Faces technology and Struts
assert() example program in C++
'double buffering' Sample program in J2ME
Converting Default Function Arguments in C++ to Java

More Tutorials in Struts
Configuring JDBC DataSources in Struts
Struts Classes
FAQ: Why was reload removed from Struts (since 1.1)?
FAQ: Why are my checkboxes not being set from ON to OFF?
Using JavaScript to submit a form in Struts
How to prepopulate a form in Struts
Simple example of using the requiredif Validator rule in Struts
Chaining actions in Struts
When is the best time to validate input in Struts
What is a Plug-in and how to use Java plug-ins with Struts?
7 Best Practices of Struts
Origin and Architecture of Struts
ActionErrors and ActionError in Struts
Tutorial on Struts Configuration File - struts-config.xml in Struts - from the book: Struts Survival Guide. Basics to Best Practices
Handling multiple buttons in HTML Form in Struts

More Latest News
Most Viewed Articles (in Struts )
Tutorial on Struts Configuration File - struts-config.xml in Struts - from the book: Struts Survival Guide. Basics to Best Practices
MVC Architecture (Model 2 Architecture)
Handling Duplicate Form Submissions in Struts
Struts 1 vs Struts 2
Handling multiple buttons in HTML Form in Struts
Configuring JDBC DataSources in Struts
Using Multibox in Struts
FAQ: Why are my checkboxes not being set from ON to OFF?
What is Struts? Which Version of Struts to use?
Is Struts the most popular web application framework for Java?
What is a Model View Controller (MVC) Model?
History of Struts
WebWork 2 is now Apache Struts 2
Struts Classes
Downloading and installing Struts
Most Emailed Articles (in Struts)
What is a Model View Controller (MVC) Model?
Struts and Tiles - Steps to use Struts and Tiles
Creating Struts Modules
History of Struts
WebWork 2 is now Apache Struts 2
Creating the first application using Struts 2
ActionErrors and ActionError in Struts
IncludeAction in Struts
Handling Duplicate Form Submissions in Struts
Guidelines for Struts Application Development
7 Best Practices of Struts
Is Struts the most popular web application framework for Java?
Downloading and installing Struts
The directories and files of a Struts application
Editing struts-config.xml in a Struts Application