Presents your JAVA E-NEWSLETTER for March 6, 2003 <-------------------------------------------> USE INHERITANCE TO IMPROVE YOUR STRUTS APPLICATIONS By implementing a base action class as a helper for your other actions, you can save more time when using Struts. Among other uses, a base action can initialize data access resources, set up or centralize logging, or create objects that child classes will need. http://jakarta.apache.org/struts/ To create a base action, define an abstract class that extends Action and declares an abstract method that base classes must implement. In this case, we've declared the doExecute method for all concrete base classes to implement: import org.apache.Struts.action.Action; public abstract class BaseAction extends Action { public abstract ActionForward doExecute( ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException; } The base class implements the Action method, execute. In the execute method, the base class ensures resources are available and calls the doExecute, which the child class has implemented. We've done a lot of work here so that classes that extend the base class don't have to, as you can see in the code: public ActionForward execute(. . .) . . . // make sure the customer is logged in Object r = request.getSession().getAttribute(Constants.MEMBER_BEAN); if ( r == null ) { // if the customer is not logged in, forward to login page request.getSession().setAttribute( Constants.DESTINATION_PATH, request.getServletPath()); request.getRequestDispatcher(Constants.LOGIN_ACTION) .forward(request, response); return null; } try { ReviewTeamDao dao = this.daoFactory.getReviewTeamDao(); request.getSession() .setAttribute(Constants.TEAMS_KEY, dao.getAll()); } catch (DaoException e) { throw new ServletException("error fetching review teams", e); } // call the derived class's implementation of doExecute return doExecute(mapping, actionForm, request, response); } Now all the child class has to do is implement the doExecute method to perform its duties: public ActionForward doExecute(. . .) . . . request.getSession().removeAttribute("sparkyReview"); try { ViewReviewForm form = (ViewReviewForm) actionForm; ReviewDao dao = this.daoFactory.getReviewDao(); Review review = dao.getById(form.getReviewId()); if ( review != null ) { request.getSession() .setAttribute("sparkyReview", review); this.notifier.reviewViewed(review); return mapping.findForward("success"); } } catch (Exception e) { log.error(e); } return mapping.findForward("error"); } Writing the same code over and over is always drudgery, so take advantage of two major aspects of object-oriented programming (OOP)--inheritance and polymorphism--to make your job easier. You won't be able to use a base action for all your action classes, but when you can, it will save you coding time. ----------------------------------------