Search code examples
javaservletsstrutsstruts-1

LifeTime Action class Struts 1.3.10


What is the lifetime of the class that extends Action (Struts 1.3.10)?

public class AddProcessAction extends Action {

    ProcBox procBox = new ProcBox();

    @Override
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        procBox.addToProcBox((ProcessForm)form);
        return mapping.findForward("success");
    }
}

Solution

  • Struts 1.x actions are singletons and last the lifetime of the application.

    Therefore they must be re-entrant and thread safe.

    Your example above will not work correctly unless you have only one user.

    The ProcBox instance variable needs to be created and stored in your HttpSession, which is unique for each client. You could use something like:

    public class AddProcessAction extends Action {
    
        private static final String PROC_BOX_SESSION_ATTR = "addProcessAction.procBox";
    
        @Override
        public ActionForward execute(ActionMapping mapping, 
                                     ActionForm form, 
                                     HttpServletRequest request,
                                     HttpServletResponse response) throws Exception {
            final procBox = acquireProcBoxFrom(request);
            procBox.addToProcBox((ProcessForm)form);
            return mapping.findForward("success");
        }
    
        private ProcBox acquireProcBoxFrom(HttpServletRequest request) {
            final HttpSession httpSession = request.getSession();
            ProcBox procBox = (ProcBox)httpSession.getAttribute(PROC_BOX_SESSION_ATTR);
            if (procBox == null) {
                procBox = new ProcBox();
                httpSession.setAttribute(PROC_BOX_SESSION_ATTR, procBox);
            }
            return procBox;
        }
    
    }