What's the purpose of storing objects directly

2019-09-19 06:36发布

问题:

Based from what I've researched, I've seen that tags such as <s:set>, <s:push> or by creating an <s:bean> are able to insert references directly to the ActionContext or ValueStack. This confuses me a lot because why can't you just have one dedicated place to store everything? Probably just put everything in the ActionContext since it's basically acts as a ServletContext.

To make it even more confusing, if you wanted to access values in the ValueStack, you'll have to use Struts tags such as <s:property> but if the value's just stored in the ActionContext, you just use the #value prefix provided by OGNL.

Can someone please clear this up for me? When I used Spring, I believe everything that I needed (request, session, applicationContext) was inside the ServletContext and to access these values on my webpage, I could just use the $ prefix to access anything within context.

回答1:

Every place has its dedicated storage where you can put your objects for later use/retrieve running across some invocation context. Whatever context is running the framework is associated. The context is the way of communicating between scoped objects inside it you can access using Java or other expression language (EL) like OGNL.

In OGNL the action context is the OGNL context, and the value stack is a root.

The framework sets the OGNL context to be our ActionContext, and the value stack to be the OGNL root object. (The value stack is a set of several objects, but to OGNL it appears to be a single object.) Along with the value stack, the framework places other objects in the ActionContext, including Maps representing the application, session, and request contexts. These objects coexist in the ActionContext, alongside the value stack (our OGNL root).

The ActionContext is ThreadLocal, so you can use it in one thread. The best way to get the action context/value stack from this thread is using static method.

ActionContxt ctx = ActionContext.getContext();
ValueStack vs = ctx.getValueStack();

Interceptors also have a parameter passed, known as invocation context, which is the action context.

The value stack has also its own context, the validation has its own context. So, these definitions never end.