6.10. Dispatching to Related Operations with Action Mappings

Problem

You want to use a single Action class to process related operations yet allow the form type, validation rules, and other action attributes to vary for each operation.

Solution

Extend the Struts pre-built MappingDispatchAction (only available in Struts 1.2 or later) with your own subclass. Provide methods for each operation you wish to be callable. Each method should have the same signature as the execute() method. The class shown in Example 6-8 provides three related operations: create( ), update( ), and delete( ).

Example 6-8. MappingDispatchAction for related operations

package com.oreilly.strutsckbk.ch06; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.PropertyUtils; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.MappingDispatchAction; public class MyMappingDispatchAction extends MappingDispatchAction { public ActionForward create( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { PropertyUtils.setSimpleProperty(form, "dispatchedTo", "create"); return mapping.findForward("success"); } public ActionForward update( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse ...

Get Jakarta Struts Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.