Study __struts2 of Ognl,valuestack,stackcontext in Struts2

Source: Internet
Author: User
Tags java web

http://jwx0925.iteye.com/blog/630335 [/color] Learning Struts2, has been not clear how the value of the form is passed to the action, the Internet to check some information, basic understanding. Below basically is from several people's Bolg reprint come over, later remember not clear again to see ~

[color=red] First look at the experiment JSP page I did
Java code

<s:form action= "Hello/converter.action" method= "POST" >
		<s:textfield "point" name= "dot" label=: textfield>
		<s:textfield name= "Point2" label= "2" ></s:textfield>
		<s:textfield name= " Point3 "label=" 3 "></s:textfield>
		<s:textfield name=" Age "label=" ages "></s:textfield>
		<s:textfield name= "date" label= "dates" ></s:textfield>
		<s:submit name= "Submit" ></s:submit>
	</s:form>

Result graph (obtained by <s:debug></s:debug>)
Value stack:



Stack Context:






We can see from the diagram
Valuestack include the values I Pass (point,point2,point3,age,date)
Properties such as request application Ognlvaluestack (root) session parameters are included in the stack context

Value Stack (valuestack)
Struts2 sets the OGNL context to Actioncontext in Struts2 (which is still used internally as Ognlcontext) and set the value stack to the root object of the OGNL.
We know that the root object in the OGNL context can be accessed directly, without any special "tags", while other objects in the reference context need to be marked with "#". Because the value stack is the root object in the context, it can be accessed directly. So how do you access the objects in the value stack? STRUTS2 provides a special ognlpropertyaccessor that automatically finds all the objects in the stack (from the top of the stack to the bottom of the stack) and directly finds an object with the attributes you are looking for. That is, any object in the value stack can be accessed directly without the need to use "#".
There are two objects in the stack: Student and employee, two objects have the name attribute, student number, and employee has the pay attribute salary. Employee first into the stack, student after the stack, at the top of the stack, then for the expression name, access is the student Name property, because the student object is at the top of the stack, the expression salary, access is the employee's salary attribute. As you can see, accessing the object properties or methods in the value stack does not need to indicate the object or "#", as if the object in the value stack is the same as the root object in the OGNL context. This is the improvement that Struts2 on the basis of OGNL.

Action instances in the value stack
The Struts2 frame always puts the action instance on top of the stack. Because the action is in the value stack, and the value stack is the root of the OGNL, the attribute that refers to the action can omit the "#" tag, which is why we can directly access the properties of the action in the results page.

Named objects in the Struts2
Struts2 also provides named objects that are not saved in the value stack, but are kept in actioncontext, so access to these objects requires a "#" tag. These named objects are all map types.

Parameters
Used to access request parameters. such as: #parameters [' id '] or #parameters.id, which is equivalent to calling the GetParameter () method of the HttpServletRequest object.
Note that parameters is essentially a map object constructed using the request parameters in the HttpServletRequest object, and a measure object is created (already created before the action instance is invoked), It has nothing to do with the HttpServletRequest object.
  
Request
Used to access request properties. such as: #request [' user '] or #request.user, which is equivalent to calling the GetAttribute () method of the HttpServletRequest object.

Session
Used to access the session property. such as: #session [' user '] or #session.user, which is equivalent to calling the GetAttribute () method of the HttpSession object.

Application
Used to access the Application property. such as: #application [' user '] or #application.user, equivalent to calling the ServletContext getattribute () method.

attr
If PageContext is available, the PageContext is accessed, otherwise the request, session, and application objects are searched sequentially.

Here is the turn: First, the next Actioncontext, Valuestack, Stack context Three

Actioncontext
An action call creates a Actioncontext
Call: Actioncontext context = Actioncontext.getcontext ()

Valuestack
Implemented by OGNL framework
You can simply think of it as a stack (List).

Stack object: An object that is placed in a stack, typically an action.
Stack context (map): Stack contexts, which contain a series of objects, including the Request/session/attr/application map.
EL: Access to arbitrary properties of the object, call the object's methods, traverse the entire object knot ...

Actioncontext is the action context and can get the request session application
Valuestack is the value stack that holds the values in the form
Stack context stack contexts are also used to store values



Struts2 further expands the concept of the OGNL context, and in struts2, the OGNL context is usually as follows:

|--request

|

|--application

|

Context Map---|--ognlvaluestack (root) [user, Action, Ognlutil, ...]

|

|--session

|

|--attr

|

|--parameters




In Struts2, the OGNL expression is handled using a standard-named context. The top-level object that handles OGNL is a map (also called a context map), and OGNL is a top-level object (root) in this context. In usage, the top-level object's property access is not required for any tag prefix. and other non top-level object access, you need to use the # tag.
The STRUTS2 framework sets the OGNL context to our actioncontext. And valuestack as the root object of the OGNL. In addition to the value stack, the STRUTS2 framework also places map objects representing application, sessions, and request objects into Actioncontext. (This is why STRUTS2 recommends that you do not directly access the Servlet API in the action class, and that he can partially replace these (Servlet API) features with Actioncontext objects to facilitate testing of the action class.) )
An instance of the action, always placed in the value stack. Because the action is placed in the stack and the stack is root (the root object), access to the attributes in the action can omit the # tag. However, to access the properties of other objects in Actioncontext, you must bring the # tag to let OGNL know, not from the root object, but from other objects.
Then the code to access the properties in the action can be written like this

<s:property value= "PostalCode"/>
Access to non-root object properties in other Actioncontext is as follows:
<s:property value= "#session. Mysessionpropkey"/> or
<s:property value= "#session [' Mysessionpropkey ']"/> or
<s:property value= "#request [' Myrequestpropkey ']"/>
For collection, the content is simple.
<s:select label= "label" name= "name" list= "{' name1 ', ' name2 ', ' Name3 '}" value= '%{' name2 '} "/>
This is the process list. This code creates a Drop-down option on the page that contains the contents of the list, and the default value is name2.
Process map

<s:select label= "label" name= "name" list= "#{' foo ': ' Foovalue ', ' bar ': ' Barvalue '}"/>

It should be noted that a value is judged to be in collection. We are going to use in or not to process.
<s:if test= "' foo ' in {' foo ', ' Bar '}" >
Muhahaha
</s:if>
<s:else>
Boo
</s:else>
Alternatively, you can use wildcards to select a subset of the collection object.
?—— all elements that match the selection logic
^--only extracts the first element that conforms to the selection logic
$--only extracts the last element that conforms to the selection logic
Person.relatives. {#this. gender = ' Male '}

`````````````````````````````````````````````````````````````````````````````````

The following are some of the questions of the supplementary excerpt:

Question: In Struts2, how to use its own tag to read variables in action.

Struts2 's own tag will look for the corresponding object in Valuestack according to the OGNL expression in value. Because the action is at the top of the Valuestack, by default, the OGNL expression in Struts2 's tag finds the variable in the action. Note that the contents of value are directly ognl expressions without any El label wrapper.

For example: <s:property value= "User.Name"/>

Question: In Struts2, how to use its own tag to read variables in httpservletrequest,httpsession.

In the above knowledge, we know that in the context of OGNL in Struts2, the map encapsulation of servlet objects such as Request,session,application is included. Now that these objects are in the context of the OGNL, based on the basic knowledge of OGNL, we can access the values of these variables by adding the # symbol before the expression.

For example: <s:property value= "%{#application. Myapplicationattribute}"/>
<s:property value= "%{#session. Mysessionattribute}"/>
<s:property value= "%{#request. Myrequestattribute}"/>
<s:property value= "%{#parameters. Myparameter}"/>



Question: In Struts2, how to use Jstl to read variables in action.

This is a long history of the problem. Because in fact, a lot of friends (including me) do not use Struts2 own tag library, but use Jstl, probably because jstl tag cubby less, simple and easy-to-use reasons.

As we know, jstl the default is to find the value of an object corresponding to an El expression from the Page,request,session,application four scopes. So if you want to use JSTL to read the variables in the action, you need to put the variables in the action in the request field. So, back in the webwork2.1.x era, we'd write an interceptor to do this thing. The general principle is to read all the variables in the action, sequentially, and then call Request.setattribute () to set it up before the action is done. The specific way to integrate, please refer to the following document: http://wiki.opensymphony.com/display/WW/Using+WebWork+and+XWork+with+JSP+2.0+and+JSTL+1.1

However, with the development of the times, the above method is no longer recommended for use. (Even so, we can still learn it's a problem-solving mentality) for now, since the Webwork2.2, including Struts2, have used another way of integration: to decorate the httpservletrequest. Let's take a look at the source code:
Java code
public class Strutsrequestwrapper extends Httpservletrequestwrapper {/** * the constructor * @par   
    AM REQ The request */public Strutsrequestwrapper (HttpServletRequest req) {super (req);  }/** * Gets The object, looking in the value stack if not found * @param s the attribute Key */Public Object getattribute (String s) {if (s!= null && s.startswith ("Javax.servle   
            T ")) {//don ' t bother with the standard Javax.servlet attributes, we can short-circuit this   
        WW-953 and the forums post linked in, issue for more info return Super.getattribute (s);   
        } Actioncontext CTX = Actioncontext.getcontext ();   
  
        Object attribute = Super.getattribute (s);   
        Boolean alreadyin = false;   
        Boolean B = (Boolean) ctx.get ("__requestwrapper.getattribute");   
   if (b!= null) {         Alreadyin = B.booleanvalue (); }//Note:we don ' t let # come through or else a request for//#attr. foo or #request. Foo could c   
            Ause an endless loop if (!alreadyin && attribute = = null && s.indexof ("#") = = 1) { try {//If not found, then try the Valuestack ctx.put ("__requestwrapper.getattr   
                Ibute ", boolean.true);   
                Valuestack stack = Ctx.getvaluestack ();   
                if (stack!= null) {attribute = Stack.findvalue (s);   
            finally {ctx.put ("__requestwrapper.getattribute", Boolean.false);   
    } return attribute;  

 }   
}

See it. This class will be executed at the time of Struts2 initialization, replacing HttpServletRequest, running throughout the Struts2, and executing this method when we try to invoke Request.getattribute (). (This is a typical adorner pattern) when executing the above method, it first invokes the Request.getattribute () of the HttpServletRequest Central Plains, and if it is not found, it continues to look in the valuestack. And the action is in the Valuestack, so the variable in action can find the corresponding value by ognl the expression.

Here, in the widespread use of El expressions today, JSTL1.1 also supports the direct use of El expressions. Notice the difference with the direct use of struts2 tag, where you need to use El notation: ${}

For example: ${user.name}, <c:out value= "${department.name}"/>

Question: In Struts2, how to use templates such as Freemarker to read variables in action and variables in HttpServletRequest and httpsession.

Freemarker and other templates in Struts2 have corresponding result, and in these result, freemarker templates will be based on the contents of Valuestack and Actioncontext, the template can be identified with the model, This allows the templates to read the contents of Valuestack and Actioncontext in their own syntax.

For freemarker reading of variables, refer to Struts2 's official documentation, very detailed: http://struts.apache.org/2.0.14/docs/freemarker.html

Set Value calculation

Struts2 using OGNL for value calculation means that the view layer passes data to the control layer and can be set to the corresponding Java object. This process logically requires two steps to complete:

1. For each request, a actioncontext corresponding to the action is established as the context and valuestack of the OGNL, and the action is pressed into the Valuestack

2. Before the request enters the action code, through some general mechanism, collects the parameter which the page uploads passes over, and invokes the OGNL related code, sets the value to the action.
The first step above is done when the URL request is processed, and the second step is done by the STRUTS2 built-in interceptor.






Due to browsing too many articles, the specific source address could not be recorded. But thanks to the original author on the internet ...

http://kang36897.blog.163.com/blog/static/1704737320104144194505/ struts2: About El can get action properties

2010-05-14 16:19:04|  Category: Java EE | Tags: | report | font size Big Small subscribe to a buddy today to learn struts2, try to use OGNL, because of relevance bar, and then jump to El above, the result of the magical things happen, he used El expression from the request field inside incredibly got the action clock properties, this sky-shattering, As we all know, the Struts2 objects are placed in the Actioncontext, as shown in the following figure:

This screenshot comes from STURTS2 in actin, because the action is in Valuestack, but Valuestack and request seem to have no intersection.
He actually got it, doubt began, by adding <S:DEBUG/> tags in the page found a problem, actually in the request there are struts2.valuestack such a variable bar, doubts did not disperse, but became more, how to do.
Finally found a similar post from the Internet:
Original link: http://i.laoer.com/struts2-use-el-jstl.html

Recently in the company to do some training in Java Web development, while some of the projects have been done to do some review, now in the engineering, engineers directly using Jstl to get the properties of the action, this usage I have never used to really, because in my impression, Struts2 These action attributes, should be in the Valuestack, and in some cases, from the Valuestack value is a very troublesome thing, in doing the day B Community 8 o'clock, I will refer to the STRUTS2 tag library, its own extension of the tag library, To get the value in Valuestack, and Jstl should be from page, Request, session and application in order to take the value, the STRUTS2 will valuestack in the value also into the Request. At the same time we directly use the EL tag also directly removed the action attribute value, it is really put in the request. But opening Struts2 's debug found no value in the request.

With this question, I googled it and soon found the answer:

question: In Struts2, how to use Jstl to read variables in action.

This is a long history of the problem. Because in fact, a lot of friends (including me) do not use Struts2 own tag library, but use Jstl, probably because jstl tag cubby less, simple and easy-to-use reasons.

As we know, jstl the default is to find the value of an object corresponding to an El expression from the Page,request,session,application four scopes. So if you want to use JSTL to read the variables in the action, you need to put the variables in the action in the request field. So, back in the webwork2.1.x era, we'd write an interceptor to do this thing. The general principle is to read all the variables in the action, sequentially, and then call Request.setattribute () to set it up before the action is done. The specific way to integrate, please refer to the following document: http://wiki.opensymphony.com/display/WW/Using+WebWork+and+XWork+with+JSP+2.0+and+JSTL+1.1

However, with the development of the times, the above method is no longer recommended for use. (Even so, we can still learn it's a problem-solving mentality) for now, since the Webwork2.2, including Struts2, have used another way of integration: to decorate the httpservletrequest. Let's take a look at the source code:


1
2
3
4
5
6
7 8 9
30 (a) (a) This is the same as
the
48
 public class Strutsrequestwrapper extends Httpservletrequestwrapper { /** * the constructor * @pa
     RAM req the request */public Strutsrequestwrapper (HttpServletRequest req) {super (req); }  /** * Gets The object, looking in the value stack if not found * @param s the attribute Key/Public Object getattribute (String s) {if (s!= null && s.startswith ("Javax.servlet")) {//don ' t bother with the standard Javax.servlet attributes, we can short-circuit this///
         W-953 and the forums post linked in, issue for more info return Super.getattribute (s);
         }   Actioncontext CTX = Actioncontext.getcontext ();
Object attribute = Super.getattribute (s);
           Boolean alreadyin = false;
         Boolean B = (Boolean) ctx.get ("__requestwrapper.getattribute"); if (b!= null) {Alreadyin = b. Booleanvalue (); }  //Note:we don ' t let # come through or else a request for//#attr. foo or #request. Foo could c
             Ause an endless loop if (!alreadyin && attribute = = null && s.indexof ("#") = = 1) { try {//If not found, then try the Valuestack ctx.put ("__requestwrapper.getattribute",
                 Boolean.true);
                 Valuestack stack = Ctx.getvaluestack ();
                 if (stack!= null) {attribute = Stack.findvalue (s);
             finally {ctx.put ("__requestwrapper.getattribute", Boolean.false);
    } return attribute; }
}

See it. This class will be executed at the time of Struts2 initialization, replacing HttpServletRequest, running throughout the Struts2, and executing this method when we try to invoke Request.getattribute (). (This is a typical adorner pattern) when executing the above method, it first invokes the Request.getattribute () of the HttpServletRequest Central Plains, and if it is not found, it continues to look in the valuestack. And the action is in the Valuestack, so the variable in action can find the corresponding value by ognl the expression.

Here, in the widespread use of El expressions today, JSTL1.1 also supports the direct use of El expressions. Notice the difference with the direct use of struts2 tag, where you need to use El notation: ${}

For example: ${user.name}, <c:out value= "${department.name}"/>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.