Compared to the STRUTS1 tag library, the STRUTS2 tag Library has a huge improvement in that the STRUTS2 tag library is not dependent on any presentation layer technology. This means that most of STRUTS2 's tags can be used in JSP pages, or in template techniques such as velocity and freemarker.
STRUTS2 tags are defined in the S tag library, and the URI is/struts-tags space. Simply classify the tags of the struts2:
UI tags, which are used for HTML element tags.
Non-UI tags, mainly for data access, logic control and other tags.
Ajax tags, which are used for AJAX-supported tags.
First copy the Struts-tags.tld file to the WEB application project, for example, we copied it to/web-inf/tag/struts-tags.tld. /, which represents the root directory of the current web App.
Then, open Web. XML to configure the tag tag. Uri,<taglib-location>...</taglib-location> for configuring tag libraries between <taglib-uri>...</taglib-uri> Configure the location where the specific struts-tags.tld is stored. The configuration of the tag library must be placed between <taglib>...</taglib>.
<taglib>
<taglib-uri>
/struts-tags
</taglib-uri>
<taglib-location>
/web-inf/tag/struts-tags.tld
</taglib-location>
</taglib>
If your web app uses more than servlet 2.4 specifications, you do not need to configure the tag library definition in the. xml file, because the servlet 2.4 specification automatically loads the tag library definition file.
To use the STRUTS2 tag, you must first import the tag library and use the following code in the JSP page to import the STRUTS2 tag library:
<% @taglib prefix= "s" uri= "/struts-tags"%>
Where the URI is the URI of the STRUTS2 tag library, and the prefix property value is the prefix of the tag library. For example:
<S:ABC .../>
*****************************************
OGNL Expression Language
OGNL is the query language for an object, property. In Ognl there is a context (called context) with a type map, in which there is a root element (root), access to the properties of the root element can be directly used with the property name, but the access to the properties in other non-root elements must be added with special symbol #.
OGNL context map includes:
Application,session,value stack (root), require,parameters,attr
In Struts2, the context is actioncontext, the root element is the value stack, the value stack, which represents a family of objects instead of an object, where an instance of the action class is also part of the value stack. Because the action instance is placed in the value stack, and the value stack is one of the root elements (root), access to the properties in the action can be done without using the tag #, and the other access must use the # tag. For example: #foo. Blah, which indicates that the Blah property named Foo object in the context is obtained. Equivalent to executing the Foo.getblah () method.
Parameters object, used to access HTTP request parameters, such as #parameters[' foo ') or #parameters.foo for range call HttpServletRequest getparameter ("foo") The return value of the method.
The request object for accessing the HttpServletRequest property. For example: #request [' foo '] or #request.foo, which returns the return value of the getattribute ("foo") method that called HttpServletRequest.
The session object that is used to access the properties of the HttpSession. For example: #session [' foo '] or #session.foo
The Application object that is used to access the properties of the ServletContext. For example: #application [' foo '] or #application.foo
A attr object that accesses its properties (attribute) #attr by request > Session > Application Order. Username is equivalent to reading the Username property sequentially within the three scope (scope). Until it is found.
Based on the above, the name property of an element of a form in a JSP page can be directly to a VO class instance in the action. Property name, which stores the value of the element directly in the properties of the Vo class. Such as:
<input name= "Corpinfovo.standbyemail" class= "on_tx5" type= "text" maxlength= "" "Id=" Standbyemail "/>
OGNL supports all constant types:
String constants: A string enclosed in single or double quotation marks. Note that if you are a string constant of a single character, you must use double quotation marks.
Character constants: Characters enclosed in single quotation marks (' ').
Numeric constants: In addition to Int,long,float and double in Java, Ognl lets you specify BigDecimal constants using "B" or "B" suffixes, specifying BigInteger constants with "H" and "H" suffixes.
Boolean constant: TRUE or false.
Null constants
OGNL in the collection:
List collection, formatted similar to: {e1,e2,e3 ...} The collection contains three elements: E1,e2,e3. If more elements are needed, separate the multiple elements with commas.
Map collection, formatted like: #{key1:value1,key2:value2,...}, generates a map collection directly, separated by colons between each Key-value object in the Map object, separated by commas.
For example:
<s:if test= "' foo ' in {' foo ', ' Bar '} ' >
...
</s:if>
Curly braces {}, used to create the collection, separated by commas.
In and not in, to determine whether a value is in the collection.
Accessing the properties of JavaBean
If there is an employee object as the root object of the OGNL context, then for the following expression:
Name, the corresponding Java code is employee.getname ();
Address.country, the corresponding Java code is employee.getaddress (). Getcountry ();
%, which evaluates the value of the OGNL expression when the property of the flag is a string type. %{#foo [' Foo1 ']}. such as%{gettext (' key ')} can take out internationalized information
$, there are two main uses
Used to reference the OGNL expression in an internationalized resource file. For example, in the STRUTS2 configuration file:
<result type= "redirect" >ListPhoto.action?albumld=${albumld}</result>
***************************************
Struts2 's non-UI tags include control labels and data labels, which are primarily used to complete process control.
1 if, ElseIf, else tags
These three tags are used for branching control. 3 tag combinations are used, only the <s:if.../> tag can be used alone, behind the <s:elseif. /> and <s:else.../> are not to be used alone and must be combined with <s:if.../> tags. They can replace the IF statement of a JSP script, and the If label and else label can accept a test property that determines the Boolean expression that performs the judgment.
For example:
<s:set name= "age" value= "/>"
<s:if test= "expression" >
Label body
</s:if>
<s:elseif test= "expression" >
Label body
</s:elseif>
.....
<s:else>
Label body
</s:else>
S-IF.JSP:
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "%>
<% @taglib prefix= "s" uri= "/struts-tags"%>
<body>
<!--define an age property in the stack context with a value of 29-->
<s:set name= "age" value= "/>"
<!--If the attribute of age in the stack context is greater than 60-->
<s:if test= "#age >60" >
Elderly
</s:if>
<s:elseif test= "#age >35" >
Middle aged
</s:elseif>
<s:elseif test= "#age >15" >
Youth
</s:elseif>
<s:else>
Juvenile
</s:else>
For the <if.../> label,<elseif.../> tag, you must specify a test property, which is the test property to be conditionally judged.
</body>
test= "expression" can also be a property of an object, such as test= "#user. age>35".
2 iterator label
Iterator tags are primarily used to iterate over collections, where collections include list,set and arrays, and you can iterate over the map collection. When using the </s:iterator.../> tab for iterative output, you can specify three properties:
Value, which is an optional property, the Value property specifies the collection that is iterated, and the collection that is iterated is usually specified using the OGNL expression. If the Value property is not specified, the collection at the top of the Valuestack stack is used.
ID, which is an optional attribute that represents the element in the collection. The value is a string.
Status, which is an optional attribute that specifies the Iteratorstatus instance at iteration time. This instance allows you to determine the properties of the current iteration element. For example, whether it is the last, and the index of the current iteration element. The example contains the following properties:
Count (), which returns several elements that are currently iterated.
Index (), which returns the indexes of the current iteration element.
Even () that returns whether the currently iterated element is an even number.
First (), which returns whether the element that is currently being iterated is the number one element.
Last () returns whether the currently iterated element is the final element.
Odd () that returns whether the index of the currently iterated element is odd.
For example:
<s:iterator value= "{' Struts2 authoritative guide ', ' lightweight Java EE ', ' tested '}" id= "ne" status= "st" >
The properties of the current iteration element are judged. Determine if the index is an odd number
<s:if test= "#st. Odd" >
<tr>
<td>
NE represents the elements in the collection
<s:property value= "Ne"/>
</td>
</tr>
</s:if>
</s:iterator>
<%
List List = new ArrayList ();
List.add ("Max");
List.add ("Scott");
List.add ("Jeffry");
List.add ("Joe");
List.add ("Kelvin");
Request.setattribute ("names", list);
%>
<ol>
<s:iterator value= "#request. Names" id= "ne" status= "stuts" >
<!--judged by the current index-
<s:if test= "#stuts. Index > 2" >
<li>white <s:property value= "NE"/></li>
</s:if>
<s:else>
<li style= "Background-color:gray" ><s:property value= "ne"/></li>
</s:else>
</s:iterator>
</ol>
Iteration Map:
Trademap.keyset () Gets the set set of key for the map, T is the value in the set set, and ${t} represents the Key,trademap.get (#t) of the map to get the key (#t) corresponding to value.
<s:iterator id= "T" value= "Trademap.keyset ()" status= "St" >
<option value= "${t}" ><s:property value= "Trademap.get (#t)"/> </option>
</s:iterator>
</select>
When a property of an action is a list object, such as:
Private list<dgzzuservo> Listdguser;
Because the Action property is placed under the root element (Value Stack), access to the Action property can be without the # number. Then each element in the list is a Dgzzuservo, and Dgzzuservo is not under the root element, so the access to it needs to be added as follows:
<s:iterator value= "Listdguser" id= "Dguservo" status= "stuts" >
<tr>
<td><s:property value= "#dguserVO. UserID"/></td>
<td><s:property value= "#dguserVO. UserName"/></td>
<td><s:property value= "#dguserVO. Email"/></td>
<td><s:property value= "#dguserVO. Relationman"/></td>
<td><s:property value= "#dguserVO. Phone"/></td>
</tr>
And because list<dgzzuservo> is generic, you can also use the following methods:
<s:iterator value= "Listdguser" id= "Dguservo" status= "stuts" >
<tr>
<td><s:property value= "UserID"/></td>
<td><s:property value= "UserName"/></td>
<td><s:property value= "Email"/></td>
<td><s:property value= "Relationman"/></td>
<td><s:property value= "Phone"/></td>
</tr>
3append Label
The append tag is used to assemble multiple collection objects together into a new collection. This allows the iteration of multiple collections to be done through a <s:iterator.../> tag. You need to specify a var attribute when using the <s:append.../> tag, but you can also use the ID property but Var is recommended, which confirms the name of the new collection generated by the stitching. In addition <s:append.../> tags can accept multiple <s:param.../> sub-tags, each sub-label specifies a collection, <s:append. /> is responsible for stitching multiple sets of <s:param.../> tags into a single collection. For example:
<table>
<s:append id= "NewList" >
<s:param value= "{' Struts1 ', ' struts2 '}"/>
<s:param value= "{' http://www.crazyit.net.cn ', ' http://www.crazyit.org '}"/>
</s:append>
<s:iterator value= "#newList" status= "St" id= "Ele" >
<tr>
<td><s:property value= "#st. Count"/></td>
<td><s:property value= "Ele"/></td>
</tr>
</s:iterator>
</table>
The following example joins the three list objects in the action into a list and outputs the list:
<s:append id= "Myappenditerator" >
<s:param value= "MyList1"/>
<s:param value= "MyList2"/>
<s:param value= "MyList3"/>
</s:append>
<s:iterator value= "#myAppendIterator" >
<s:property/>
</s:iterator>
4 Generator Label
Using the generator tag, you can separate the enactment string into multiple substrings by a specified delimiter, and multiple, temporarily generated substrings can iterate the output using the iterator tag. It can be said that: Generator a string into a list collection, in the label body, the entire temporarily generated collection will be at the top of Valurstact, once the label ends, the collection will be removed valuestack.
You can specify the following properties when using generator tags:
Count, this property is an optional property that specifies the total number of elements in the build collection.
Separator, Required property that specifies the delimiter used to parse the string.
Val, this is a required property that specifies the delimiter used to parse the string.
Var, which is an optional attribute that, if specified, puts the resulting iterator object into the stack context. can also be replaced by an ID.
For example:
<s:generator var= "Newlist1" val= "' struts2 authoritative guide, lightweight j2ee,tested '" separator= "," ></s:generator>
<table>
<s:iterator value= "#newlist1" var= "ee" >
<tr><td><s:property value= "ee"/></td></tr>
</s:iterator>
</table>
In the following example, SSS is an attribute in the action. Note that the value of Var cannot be new, because new is the keyword
<s:generator separator= "," val= "SSS" var= "New2" ></s:generator>
<table>
<s:iterator value= "#new2" var= "ee" >
<tr><td><s:property value= "ee"/></td></tr>
</s:iterator>
</table>
5 Merge Tab
The use of the merge tag looks very much like the append tag and is used to stitch multiple collections together into a single set, but it is stitched together in a way that is different from append stitching.
6 Subset Label
The subset tag is used to get a subset of the collection. You can specify several properties when using subset Tags:
Count, which is an optional property that specifies the number of elements in the child set. If this property is specified, all elements in the original collection are obtained by default.
Source, which is an optional property that is used to specify the source collection. If you do not specify this property, the collection at the top of the Valuestack stack is obtained by default.
Start, which is an optional attribute that specifies that a subset is intercepted from the first element of the source collection. The default starts with the first element (start defaults to 0).
Var, ibid.
<s:subset source= "{' One ', ' I ', ' three ', ' four ', ' Five '}" start= "1" count= "4" >
...
</s:subset>
The following is a two-element traversal of index 1 in MyList1 using the subset tag. Note that the iterator in this face must be placed inside the iterator and iterator cannot configure other properties. Otherwise, there will be an error.
<s:subset source= "MyList1" var= "FF" start= "1" count= "2" >
<s:iterator>
<s:property/>
</s:iterator>
</s:subset>
7 Date Label
Date label, used to format the output a date, in addition to a date that can be formatted directly, the date label can also calculate the difference between the specified date and the current time.
Format, an optional property that specifies the format in which the date is formatted.
Nice, this is an optional property that can only be true or FALSE, which specifies whether to output the difference between the specified date and the current time. The default is false to not output.
Name, required, which specifies the date value to format.
Var, ibid.
<s:date name= "#attr. Now" format= "dd/mm/yyyy" nice= "true"/>
Ten param label
PARAM tags are primarily used to provide parameters to other labels. Properties of the param tag:
Name, optional attribute that specifies the parameter name that you want to set parameters for.
Value, an optional property that specifies the parameter value that you want to set the parameter to.
Two ways to param a label:
<s:param name= "Color" value= "Blue"/>
<s:param name= "Color" >blue</s:param>
11i18n
Loads the resource bundle into the value stack, which allows the text flag to access information for any resource bundle, not just the resource bundle currently managed by the action.
The Value property, which takes the path to the resource bundle, such as: COM.XXX.RESOURCES.APPMSG
For example, if the resource bundle exists: Helloworld=hello world!, the following will output Hello world!
<s:i18n name= "Applicationmessages" >
<s:text name= "HelloWorld"/>
</s:i18n>
12set
The set label assigns a variable a specific range of values. When you want to assign a complex expression to a variable, it is used every time you access a variable rather than a complex expression.
Name, which is a string that represents the name of the variable.
Scope, with a value of string, variable scope, can be application, session,request,page, or action.
Value, which will be assigned to the values of the variable. The value is object or string.
such as: <s:set name= "Bianliang" value= "/>"
13text
To support the internationalization of information labels, internationalization information must be placed in a and the current action through the resource bundle, if not found the corresponding Message,tag body will be treated as the default message, if there is no tag body, The name of the message will be used as the default message.
For example, the above <s:text name= "HelloWorld"/> used to output the value of HelloWorld in the resource file.
14property
<s:property/> Tag: is the label that outputs the specified value. Its default property is optional, and if the output property value is null, the value specified by the default property is displayed. Value is also an optional property that specifies the value of the property that needs to be output. If this property is not specified. The default output valuestack the top value of the stack.
Request scope: <s:property value= "#request. Name"/>
Session Range: <s:property value= "#session. Name"/>
Application range: <s:property value= "#application. Name"/>
<s:set name= "Foobar" value= "#{' foo1 ': ' bar1 ', ' foo2 ': ' Bar2 '}"/>
<p>the value of key "Foo1" is <s:property value= "#foobar [' foo1 ']"/></p>
The specified value is output using the property label, and if the specified value is a JavaScript or HTML statement, such a statement is not parsed but executed as a string output.
<s:property/> Take the value inside the map:
<s:property value= "usertypemap[' key ']"/>
If the key is a string, enclose it in quotation marks, and if it is an integer, pass in the value directly and do not enclose it in quotation marks.
If key is also dynamically obtained then this takes, for example:
<s:property value= "Usertypemap[userinfovo.usertype]"/>
15EL-expression
El is the abbreviation of Expresion language, which is the meaning of expression language.
The most basic syntax format for an EL expression is $ and {}. The EL expression has four hidden object pagescope,requestscope,sessionscope,applicationscope. If scope is not specified, its search order is: Pagescope-->requestscope-->sessionscope-->applicationscope.
Normal string
Request.setattribute ("Hello", "Hello World");
Struts2 Label output: <s:property value= "#request. Name"/>
El expression output: ${requestscope.hello} or ${hello}
Bean Object
Group Group = new Group ();
Group.setname ("Shang Academy");
User user = new user ();
User.setusername ("Zhang San");
User.setage (18);
User.setgroup (group);
User.setusertype ("user");
El expression output: ${user.username} (name in output group), ${user.group.name} (name in output group)
Struts2 Label output: <s:property value= "User.group.name"/>
Map Object
Map map=new HashMap ();
Map.put ("My", "11mymymy");
Map.put ("My1", "22mymymy1");
El expression output: ${map.my1} The result is, 22mymymy1.
Struts2 label output: <s:property value= "map[' my ']"/> result is 11mymymy because key is a string type, so it needs to be enclosed in quotation marks if it is not a string type.
If the key value in the map is a solid object such as:
Map.put ("user", user);
El expression output: ${map.user.password}//result is the value of the password property of the user object
Struts2 label output <s:property value= "map[' user '].password"/>//result is the value of the password property of the user object
If the key in the map is also dynamically taken, such as:
Struts2 Label output: <s:property value= "Map[uservo.username].username"/>//will output Zhang San, user object's UserName property value.
El expression output: ${map[uservo.username].username}//will output Zhang San, the UserName property value of the user object.
For El expressions, if you want to dynamically fetch values, you can use "[]" instead of "." cannot be dynamically evaluated. For example:
${sessionscope.user[data]} in data is a variable.
Note that if the map key is a number or a special string with spaces, such as a bar, you need to use $map[' special string '} In this form, enclose it in single quotation marks.
such as Map map=new HashMap ();
Map.put ("n", "11mymymy");
Then use the EL expression ${map.01} This will be an error, you can use the ${map[' 01 '} to take the value, so that no error.
List Object
List list=new ArrayList ();
List.add ("one");
List.add (user);
El expression output:
${list[0]}//the first element in the output list is the string one.
${list[1].username}//the value of the UserName property of the user object.
Struts2 Label Output:
<s:property value= "List[0"/>//ibid.
<s:property value= "List[1].username"/>//ibid.
Array Object
Private int[] array={1,2,3,4,5,6,7,8};
El expression output: ${array[3]}
Struts2 Label output: <s:property value= "array[2]"/>
Empty operator (null value check)
Use the empty operator to determine whether an object, collection, or string variable is empty or null. For example:
${empty Param.username}
If the username value in the parameter list for request is NULL, the value of the expression is true. The El can also be compared directly with NULL using the comparison operator. such as ${param.firstname = = null}.
Comparison operator Description
= = or EQ equality check
! = or NE unequal check
< or LT is less than check
> or GT greater than check
<= or le less than equals check
>= or GE greater than equals check
Arithmetic operators (+,-(two), *,/, Div,%, MoD) and logical Operations nonspacing (and, &&, or, | | 、!、 not) are the same as the Java language and are no longer listed.
Conditional operator? =
${a? B:C} If A is true returns b otherwise returns C
For example:
<select >
<option value= "1" ${param.op==1? "Selected": "}> option one </option>
<option value= "2" ${param.op==2? "Selected": "" > Options two </option>
</select >
1+2: ${1+2}<br>
10/5: ${10/5}<br>
Ten Div 5: ${10 Div 5}<br>
10%3: ${10% 3}<br>
MoD 3: ${10 mod 3}<br>
When you use an El expression to take a value, the HTML tag is interpreted if the value is taken with an HTML tag.
Note <%@ page iselignored= "True"%> indicates whether the El language is disabled, and true to suppress. False indicates that the. JSP2.0 enabled El language is not suppressed by default.
The EL expression can be used in nested with the C tag. For example:
<c:choose>
<c:when test= "${data.irregularheartbeat = = 0}" >
<input name= "Isnormal" value= "type=" Radio "> <input name=" "value=" "type=" Radio "checked> none </div>
</c:when>
<c:otherwise>
<input name= "Isnormal" value= "" type= "Radio" checked> have <input name= "" value= "" type= "Radio" > None </div>
</c:otherwise>
</c:choose>
If you use an EL expression with the following exception, you need to place Jsp-api.jar under Web-inf/lib and then resave the file either
Javax.servlet.jsp.pagecontext Cantnot is resolved to a type
************************************
2 Tag library El expression using Struts2