I had a requirement for a project at work to insert some preprocessing into our Struts actions that will check to see if something fancy has to happen to decorate the page differently based on a branded association.  I thought to myself, "hmm, that will be easy".  I was mostly right.  I have been working mostly with Struts 2 lately, which provides us with a handy dandy prepare() method to override, that is always called before the execute() method in a Struts 2 class that extends ActionSupport.  This is simple:
public class AwesomeActionSupport implements Preparable
{ 
  private Integer integerToSet;    
  private Boolean someBool;
  public void prepare() throws Exception    
  {          
    if( someBool )           
    {                
      integerToSet = new Integer( 1 );          
    }           
    else           
    {
      integerToSet = 1;          
    }   
  }
  public String execute()   
  {         
    System.out.println( integerToSet );
    return SUCCESS;   
  }
  //GETTERS/SETTERS FOR PRIVATE VARS ABOVE
}
As you can see it's quite simple when using Struts 2.  Sadly, most of the functionality in our application is still running Struts 1 for now.  This makes something easy much less simple.  There isn't really a built-in mechanism to make a pre-execution call.  Here's what I came up with:
public abstract class AwesomeAction extends Action
{
  public ActionForward execute(ActionMapping mapping, ActionForm form,                               
                               HttpServletRequest request, HttpServletResponse response) 
    throws Exception   
  {    
    //do prep work    
    request.setAttribute( "whatever the action needs", theValue );    
    return perform( mapping, form, request, response );      
  }
  /**   
    * A stub for performing the execute method, to be implemented by each    
    * individual struts action, after the execute pre-processing is performed   
    *    
    * @param mapping   
    * @param form   
    * @param request   
    * @param response   
    * @return   
    * @throws Exception   
    */  
  public abstract ActionForward perform( ActionMapping mapping, ActionForm form,                                         
                                         HttpServletRequest request, HttpServletResponse response) 
    throws Exception;
}
 
 


 
 Posts
Posts
 
