Re: how to handle two submit buttons in form? (webpage)
GArlington wrote:
Option 1: give them different names and handle which one was clicked
on the server
The Model-View-Controller and Front Controller patterns work well to do this.
The controller can be global to an application, as in Struts, or specific to
a page, as in JSF.
Here's an example of the latter, in the form of a method that would be common
to doPost() and doGet() in a page's controller servlet. It looks at the
command label from the submit button, which here we postulate to be one of {
"Insert", "Delete", "Exit" }.
Rather than postulating differently-named buttons, assume that the value of
the "command" request parameter corresponds to the desired action. It's easy
to adapt the logic to differently-named controls if you prefer.
Imagine that method names in the snippet refer to some reasonable
implementations. Assume there's a BizLogic ("business logic") interface or
abstract class that defines an execute() method that returns a Result, another
custom type. There are three implementation classes: InsertLogic, DeleteLogic
and ExitLogic. The execute() method of each subclass does the right thing for
the indicated action.
The process extracts the value of the command button, looks up the appropriate
logic implementation based on the command, captures the result of that logic,
embeds it in a request attribute and forwards to the next view (JSP).
In this example the command-to-BizLogic mapping is hard-coded, but in practice
is configured at deployment time. Exception handling in this example is
minimal, and logging is ignored, also at variance with correct production
practices.
This snippet itself has not been tested or compiled. It is adapted from
working code, and actually should work for suitable definitions of the omitted
material.
A decent hand-written controller servlet can be quite short, on the scale of
the snippet herein, and be rock-solid and expandable without rewrite or
recompile just by adding command-to-logic mappings.
<snippet>
protected void processRequest(
HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
enum Command { INSERT, DELETE, EXIT }
String cmd = request.getParameter( "command" );
if ( cmd == null )
{
throw new ServletException( "no command" );
}
BizLogic logic;
switch( Command.valueOf( cmd.toUpperCase() ) )
{
case INSERT:
logic = new InsertLogic();
break;
case DELETE:
logic = new DeleteLogic();
break;
default:
case EXIT:
logic = new ExitLogic();
break;
}
logic.setRequest( request );
request.setAttribute( "logic", logic );
Result result = logic.execute();
String view = lookupView( cmd, result );
RequestDispatcher rd = request.getRequestDispatcher( view );
if ( rd == null )
{
throw new ServletException( "cannot forward" );
}
rd.forward(request, response );
}
</snippet>
--
Lew