On Sun, 8 Aug 2004 03:23:35 -0400, Joe Hertz <[EMAIL PROTECTED]> wrote:
> [snip]
> Now, I can only count on this working if, and only if, the Action class
> itself got instantiated for the purpose of processing the request, and
> destroyed afterward (otherwise the protected variable is going to get
> shared between requests). Am I safe here?

You are not safe here ... there is one and only one instance of each
Action, shared by all requests through the lifetime of the web
application.

> 
> If not, I suppose I could make it a ThreadLocal, but then I'd just be
> replacing the create/destroy steps with a casting step. And since my
> goal here is to try abd have all the work done outside of the "real"
> methods, that's kind of self-defeating. Same holds true with using
> request.setAttribute() instead. Ideally the persistence layer shouldn't
> have to know it's in a web application, so I'd like to not have to pass
> in a request object to it at any point.
> 
> Am I safe with my first guess? (I suspect not).  Failing that, what's a
> better idea?
> 

A useful design pattern for something like this is to create a common
subclass for your actions that does the setup/teardown work in the
execute() method, and then delegates to the action-specific work in
some other method.  For your scenario, it might look like this:

    public abstract class BaseAction extends Action {

        public ActionForward execute(...) throws Exception {
            Persistence persistence =
ActionHelper.getPersistenceObject(request);
            try {
                ActionForward forward = delegate(mapping, form,
request, response, persistence);
            } finally {
                persistence.release)(;
            }
        }

        protected abstract ActionForward delegate(ActionMapping
mapping, ActionForm form,
          HttpServletRequest request, HttpServletResponse response,
Persistence persistence)
          throws Exception;

    }

Then, your real business logic is implemented in a delegate() method
that is passed in for you, and you never have to remember to allocate
and release the persistence object.

    public class RealAction extends BaseAction {

        protected ActionForward delegate(...) {
            ... use the persistence object as needed ...
        }

    }

This is pretty close to what you've got now ... the key difference is
that it uses a local variable instead of an instance variable to avoid
sharing problems.  Also, because of the finally clause, it also
ensures that the persistence object is cleaned up, even if the
delegate() method throws an exception.

Craig

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to