LifeTime Action类Struts 1.3.10

时间:2014-10-29 12:54:55

标签: java servlets struts struts-1

扩展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");
    }
}

1 个答案:

答案 0 :(得分:2)

Struts 1.x动作是单例并持续应用程序的生命周期。

因此,它们必须是可重入且线程安全的。

除非您只有一个用户,否则上述示例将无法正常运行。

需要创建ProcBox实例变量并将其存储在HttpSession中,这对每个客户端都是唯一的。你可以使用类似的东西:

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;
    }

}