文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Struts常用标记库

Struts常用标记库

时间:2006-11-22  来源:huangxkst

Struts框架提供了丰富的自定义标记库来构建它的视图。struts提供的自定义标记库主要分成以下几类:

(因为我当时学的是英文版的,所以我将重要的和大家分享以下。。^_^!!!...)

一、HTML Tag Library

The HTML tag library is mainly used to render the fields on input forms. However, there are other uses for the tag library, including: displaying error messages, displaying messages, rendering links with URL rewriting a session id encoding, generating JavaScript validation code, and supporting i18n.

(1)、Using the HTML Tags

To use the HTML tag library, do the following:

1.Copy the TLD file, struts-html.tld, to the WEB-INF directory of your web application.

2.The compiled code for the struts HTML tag library is in the struts.jar file, so make sure that the JAR file is in your WEB-INF/lib directory.

3.Add the following taglib element to your web.xml file (WEB-INF/web.xml).

<taglib>

  <taglib-uri>struts-html</taglib-uri>

  <taglib-location>/WEB-INF/struts-html.tld</taglib-location>

</taglib>

Add the following taglib directive to the JSP that wants to use the HTML tag library:

<%@ taglib uri="struts-html" prefix="html" %>

Once you have properly installed a tag library, you can start using the tags.

html:base

The html:base  tag inserts an HTML <base> tag, which allows the page to use relative URL references. If you not use this tag, the JSP page can only use URLs that are relative to the last requested resource. Note, if using Model 2 type architecture, all of the requests will be to actions. You would use the html:base tag as follows:

<html:base />

which would render the following HTML code:

<base

href="http://localhost:8080/strutsTut/welcome.jsp">

The html:base tag would go inside of the html:head tag.

 

You can specify a different target and server name with the server attribute and the target attribute as follows:

<html:base target="/foo/welcome.jsp" server="arc-mind" />

The above would generate the following HTML:

 

<base

href="http://arc-mind:8080/struts-exercise-taglib/html-link.jsp"

target="/foo/welcome.jsp">

The main focus of the HTML tag libraries is the form control elements (fields and buttons).

Common Attributes

Many of the HTML custom tags have a similar set of attributes.

Table 7.1: Common Attributes

Optional?

                                                   

Property  

Attribute

Description

(Yes/No)

Associates

this field with the property from the corresponding ActionForm.

No

accessKey

Similar in concept to mnemonic in Swing.

Yes

alt

Specifies alternative text, which is used when the browser

cannot render this tag.

Yes

altKey

The altKey attribute is the same as the alt attribute except that it specifies the name of the key in the resource bundle. The messages in the resource bundle will display. Resource bundles are organized by country and language.

Yes

disabled

If set to true, disables the input element, which usually causes it to be grayed out by the browser.(Defaults to false.)

Yes

indexed

Renders indexed property names. The indexed attribute only works in the context of the logic:iterate tag. Defaults to false.

Yes

onblur

Allows you to write an event handler for when the element loses its focus. You write event handlers with client-side JavaScript.

Yes

onchange

Specifies an event handler for when the element loses input focus and its value changes.

Yes

onclick

Specifies an event handler when the element is clicked with a mouse.

Yes

ondblclick

Specifies an event handler for when the element is double-clicked with a mouse.

Yes

onfocus

Specifies an event handler for when the element receives focus.

Yes

onkeydown

Specifies an event handler for when the element has focus and the user presses a key.

Yes

onkeypress

Specifies an event handler for when the element has focus, and the user presses a key and then releases the key.

Yes

onkeyup

Specifies an event handler for when the element has focus and the user presses a key.

Yes

onmousedown

Specifies an event handler for when the element receives a mouse click down.

Yes

onmousemove

Specifies an event handler for when the element is under the mouse pointer and the mouse pointer moves.

Yes

onmouseout

The mouse leaves.

Yes

onmouseover

The mouse moves over.

Yes

onmouseup

The mouse button goes up while over the element.

Yes

style

Specifies an in-line style (CSS).

Yes

styleClass

Specifies a style class; gets rendered as a class attribute.

Yes

styleId

Specifies a style id; gets rendered as an id attribute.

Yes

tabindex

Specifies tab order.

Yes

title

Specifies the advisory title text for the input control; this gets used as they tool tip by the browser.

Yes

titleKey

The titleKey attribute is the same as the title attribute, except it gets the title out of the resource bundle using the key specified by titleKey. This is used to support internationalization.

Yes

value

Specifies a label for a button. If you use the value attribute with any other type of input, it will render a default value.

Yes

html:button

The html:button tag is used to render HTML button tags.

Thus, the following tag, which would be inside of an html:form tag:

<html:button property="action">BUTTON</html:button

would generate the following HTML:

<input type="button" name="action" value="BUTTON">

html:cancel

The html:cancel tag is used to render a Cancel button. The cancel tag has special support throughout the Struts framework. There is a helper method in the action class called isCanceled() that checks to see if this button was pressed. In addition, the RequestProcessor checks to see if the Cancel button was pushed before it does form population and validation. If you click the Cancel button, the form will not be validated or populated.

You could use the html:cancel tag inside of a form as follows:

<html:cancel>Cancel</html:cancel>

The code above would render the following HTML:

<input type="submit" 

       name="org.apache.struts.taglib.html.CANCEL" 

       value="Cancel" onclick="bCancel=true;">

Notice that the onclick attribute sets a flag called bCancel to true (in JavaScript). This is for when you are using the Validator framework to generate client-side JavaScript validation code. See Chapter 4 for more details

If you wanted to include internationalization support, you could also use the tag as follows:

<html:cancel><bean:write key="form.cancel" /></html:cancel>

See Chapter 14 for detailed information on internationalization for more details.

html:checkbox

The html:checkbox tag is used to render a check box.

Here is an example of using the checkbox tag:

<html:checkbox property="booleanProperty" />

The ActionForm that corresponds to this each html:form would have to have a property named booleanProperty.

The tricky thing about working with check boxes is that HTTP only sends boxes that are checked. Thus, in you ActionForm’s reset() method, you must set all check boxes to false to allow the request processor to populate the check boxes from the incoming request—see Chapter 3, which covers ActionForms in detail.

html:errors

The html:errors tag is used to display error messages to the end users. These error messages are typically ActionErrors for a given form. This tag is falling out of favor, and you should use the html:messages attribute instead.

Typically, the error messages are stored in the default resource bundle; you can use the bundle attribute of the html:errors tag to specify a different resource bundle.

 

By default, this tag will display error messages in the user's locale, which is stored in session scope; however you could override this by specifying a locale with the locale attribute.

 

By default, this tag will get the errors (ActionErrors) from request scope under the attribute name Globals.ERROR_KEY. (Global is a helper class, and ERROR_KEY is a constant.) This tag also provides an attribute called name that can be used to get the errors from another attribute name in request scope.

 

When you place errors into an ActionErrors object, you can associate those errors with a form field. The html:errors tag allows you to specify the name of the property associated with a particular set of error messag (i.e., for a form field). The property attribute of this tag is used to grab errors for a particular form field. If you do not specify the property attribute, you will get the error messages from all of the attributes.

 

When you use html:errors, you have to define the following HTML markup in your resource bundle:

errors.header=<ul>

errors.footer</ul>

errors.prefix=<li class="error">

errors.suffix=</li>

Generally speaking, it’s a bad idea to put HTML in your resource bundle. You can use the html:messages tag get around this limitation.

 

Once you have the above entries in your resource bundle, use the following code to display all of the errors on the page:

<html:errors />

To display an error message for a particular field, use this code:

<html:errors property="someFieldName" />

html:file

The html:file tag is used to allow end users to upload files. Consider that you might want users to be able to upload a picture of themselves. To do this, you must enable file upload in your Struts application. Of course, you don’t want them to upload a 1GB image of themselves, so you have to put some limits on the pictures that users upload.

First, you need to set up two areas for enabling the uploading of files: enable the user to supply the file with an HTML form and enable the Struts application to process the file upload.

 

To enable the user to upload a file, set the encoding type of html:form to multipart/form-data, and use the html:file tag as follows:

<html:form action="/UserUpdate"

           method="post"

           enctype="multipart/form-data"> 

   

   <html:file property="userImage"/> <br />

  ...

The property userImage in the userForm is of type FormFile (org.apache.struts.upload.FormFile). FormFile represents the file sent by the client. FormFile has a method called getInputStream(), which returns an inputStream. The action handler for this form uses FormFile to access the file:

public ActionForward execute(ActionMapping mapping,

                             ActionForm form,

                             HttpServletRequest request,

                             HttpServletResponse response) throws Exception {

    UserForm userForm = (UserForm) form;

   

    InputStream inputStream =

         userForm.getUserImage().getInputStream();

    // Do something with the inputStream, it is the file data.

    ...   

  }

To set up the Struts application to restrict file size and to specify the directory location, you could set up a controller element in the Struts config file as follows:

<controller maxFileSize="200K"

            tempDir="/temp/struts/user/uploads/"/>

This code snippet states that the temporary files will be put into a directory provided by your servlet container in the directory /temp/struts/user/uploads/ and that users are allowed to upload files up to 200 KB only. You can also specify the size of the input buffer and other parameters.

 

At eBlox, we allowed users to upload product data using this Struts feature, a vast improvement over the way we use to do it. When you compare this Struts feature to the way developers used to have to do it, you can easily see that the Struts approach is much easier than the alternatives.

html:form

The html:form tag renders an HTML form. The html:formtag is associated with an action mapping by the action attribute. The action attribute specifies the path of the action mapping. Each field in the html:form should correspond to a property of the associated ActionForm.

 

Therefore, when the user submits the form, the action associated with the action mapping will be invoked (if the form is valid). It is interesting that this tag inspects the action mapping and finds the ActionForm associated with he action mapping. If the ActionForm is in scope, the property values of the ActionForm will be rendered as the values in the HTML form field of the html:form tag. In fact, if the action mapping has an error (e.g., points to an

nvalid ActionForm), the page with the html:form tag will never display until you fix the action mapping.

 

There are many more things you can do with html:form, but these are not advisable. You could override the ActionForm associated with this HTML form by using the scope and type attributes. The scope attribute specifies where to look for the ActionForm, and the type attribute specifies what type of ActionForm it is (i.e., he fully qualified Java classname). This technique is not used in practice very often, but it is good to know that it exists. This feature will be removed in Struts 1.2, so don’t use it.

 

The focus attribute is used to set the initial focus to a particular input field in the form. Most of the other attributes are the same as the attributes for an HTML form; for example, the onreset and onsumbit attributes are he same.

 

The enctype attribute is used when you want to enable the end user to upload a file. To enable the user to upload a file, set the encoding type of html:form to multipart/form-data and use the html:file tag as follows:

<html:form action="/UserUpdate"

           method="post"

           enctype="multipart/form-data"> 

   

   <html:file property="userImage"/> <br />

  ...

See the Chapter 1 tutorial and Chapter 3 (ActionForms) to see more examples of using the html:form tag.

<html:hidden />

The html:hidden custom tag renders a hidden field in a form. Its usage is similar to the other input field wrapper ags. For example:

<html:hidden property="foo"/>

The code above would associate the hidden field with the foo property of the ActionForm. If the ActionForm is n scope when the html:form renders, then the value of this field will be the value of the foo property of the ActionForm subclass. When the HTML form gets submitted, the foo property of the ActionForm subclass will be opulated.

 

Tip:TIP: The problem I’ve seen developers have with the html:hidden tag is that they try to use it to pass all hidden fields, and then it errors out because the backing ActionForm subclass does not have that property. If you want to pass an arbitrary hidden field, just use the plain old <input type=“HIDDEN” value=“whatever”/> tag. I use this with the DispatchAction hidden field method discriminator, as I do not want the method discriminator as part of the ActionForm. This is really a matter of choice.

html:html

The html:html tag renders the <html> element. You can use the locale attribute (locale=“true”) to set the Locale object named by the HTTP Accept-Language. The xhtml attribute allows you to output to the browser using xhtml by producing the xml:lang attribute.

 

The locale attribute has been deprecated in Struts 1.2. Use the lang attribute in its place when you migrate to Struts 1.2. The lang attribute renders the locale stored in the user's session if found; otherwise, it uses the lang attribute from the Accept-Language HTTP header. If still not found, it uses the default locale of the server.

html:image

The html:image tag is used to render an image button. You can specify the image using the page or src attributes. The page attribute specifies the application-context relative path of the image source. The src attribute specifies a full URL location of the image source. It’s interesting to note that this tag supports nternationalization too. The page attribute and the src attribute have a corresponding pageKey attribute and srcKey attribute, which look up the image location per locale (language and/or country combination) in the esource bundle.

 

nternationalized images may not be an intuitive concept. However, different locales can have different conography. Simply put, images mean different things in different places Another reason you'll want to nternationalize your images is if the images contain text. The html:image tag supports a lot of the common attributes specified earlier, as well as the corresponding HTML attributes that you would expect. See the Struts online documentation for more details.

(1)html:img

The html:img tag renders an <img> element. It is very similar to the html:image tag with the exception that this tag is not an input field. The html:img tag supports the same concepts of internationalizing as the html:image tag.

 

It also supports all of the attributes that you would expect. See the Struts online documentation for more details.

 

The html:img tag uses the same mechanism to specify request parameters as the html:link tag (covered below).

<html:javascript />

The html:javascript renders JavaScript validation methods. This tag is tightly coupled with the Validator framework. (See Chapter 3 for a usage example.) Using the html:javascript tag, you can, for example, turn on and turn off the HTML comments. You can also use dynamically generated JavaScript code or you can use static JavaScript code. Again, see the online Struts documentation for more details.

html:link

The html:link tag renders an HTML anchor tag (i.e., a hyperlink). This tag uses a lot of the same common ttributes as described earlier.You have multiple options for rendering the URL of a hyperlink. You can use the ref, action, forward, or page attributes to specify the URL. The href attribute is used to specify a full URL without any knowledge of the web context of this web application. The page attribute is used to specify a web context relative link. The action attribute is used to specify a link to an action mapping, as described in the

truts config file. The forward attribute is used to specify a link to a global forward, as described in the Struts onfig file.

 

Tip:TIP: If you are following a Model 2/MVC architecture, then you should use the page attribute and the href attribute sparingly. In fact, you should almost never use the page attribute. The href attribute should only be used to link to resources that are not in the current web application. This helps you separate the controller from the View by not letting the View select the next View directly. Only the controller should select the next View. Using the action and forward attributes instead forces you to delegate selection of the next View to the controller.

 

Here is an example of linking to an action (/html-link.do) with the page attribute:

<html:link page="/html-link.do">

     Linking with the page attribute.

</html:link>

Notice that you do not have to specify the web context of the web application. Conversely, if you used the href ttribute, you would have to specify the web context as follows (where the context is struts-exercise):

<html:link

   href="http://otherserver/strutsTut/html-link.do">

        Using Href

</html:link>

Another way to link to the html-link.do action is to use the action attribute as follows:

<html:link action="/html-link">

  Using Action attribute

</html:link>

 

You can specify parameters by hard coding them as follows:

<html:link page="/htmllink.do?doubleProp=3.3&amp;longProp=32">

        Double and long via hard coded changes

</html:link>

Or, you can use the paramId, paramName, and paramProperty attributes as follows:

<html:link page="/html-link.do"

           paramId="booleanProperty"

           paramName="testbean"

           paramProperty="nested.booleanProperty">

  Boolean via paramId, paramName, and paramValue

</html:link>

The code above generates the query string as follows:

<a href="/struts-exercise-taglib/html-

   link.do?booleanProperty=false">

         Boolean via paramId, paramName, and paramValue</a>

The paramId attribute specifies the name of the parameter on the query string. The paramName attribute specifies the name of the JavaBean that is used to generate the value of the query string parameter. If you do not specify a paramProperty, then the toString value of the bean will be used. If you specify paramProperty, the value that the paramProperty will be used as the value of the query string parameter. You can also specify a paramScope where the link tag will look for the bean. If the scope tag is missing, the link tag looks for the bean and all the scopes starting with page scope (the innermost scope) and going to application scope (the outermost scope). The dot notation in the property attribute value means you are using a nested property (i.e., testbean.getNested().getBooleanProperty()).

In addition, you can pass multiple query string parameter properties by specifying a map with the name attribute demonstrated as follows:

<%

  java.util.HashMap newValues = new java.util.HashMap();

  newValues.put("floatProperty", new Float(444.0));

  newValues.put("intProperty", new Integer(555));

  newValues.put("stringArray", new String[]

   { "Value 1", "Value 2", "Value 3" });

  pageContext.setAttribute("newValues", newValues);

%>

...

      <html:link action="/html-link"

                 name="newValues">

        Float, int, and stringArray via name (Map)

      </html:link>

Notice that the Java scriptlet creates a HashMap and sticks the HashMap into page scope under the attribute

newValues. The link tag links to an action and specifies the HashMap as its list of query string parameters with

the name attribute. The code above would generate the following link:

<a href="/struts-exercise-taglib/html-

link.do?stringArray=Value+1&amp;stringArray=Value+2&amp;stringArray=Value

+3&amp;floatProperty=444.0&amp;intProperty=555">

Float, int, and stringArray via name (Map)</a>

Note:Many of the examples for this chapter are based on the WAR files that ship with the Struts package to demonstrate and test the use of the Struts tags. You can find these WAR files under the webapps directory of the Struts distribution.

 

You can on use the transaction attribute to generate a transaction token query string parameter based on the saved transaction token. To learn more about transaction tokens, read Chapter 5: Working with Actions.

html:messages

The html:messages tag displays a collection of messages. The messages can be represented as ActionErrors, ActionMessages, String, or String array objects.

 

To display the messages in the JSP, you use the html:messages tag as follows:

<ul>

<font color='green' >

<html:messages id="message" message="true">

  <li><%= message %></li>

</html:messages>

</font>

</ul>

The html:messages tag will iterate over all of the messages. Notice that the message attribute of html:messages is set to true. This forces html:messages to get the messages from Globals.MESSAGE_KEY in request scope. If you do not set the message attribute, the html:messages tag will display the errors instead (Globals.ERROR_KEY). The default is set to display error messages because that is what the tag is mostly used to do.

 

Another thing you may want to do is put the error message right next to the field that has the error. You can do that with html:messages as follows:

<html:text property='userName'/>

 <html:messages id="message" property='userName'>

 <font color="red">

      <%=message%>

 </font>

 </html:messages>

In the example above, the html:messages tag iterates over all of the error messages for the userName field.

If you like how html:errors specifies footer and headers in the resource bundle, you can do the same type of thing with html:messages as follows:

<html:messages property="property2" message="true" id="msg"

  header="messages.header" footer="messages.footer">

  <tr><td><%= pageContext.getAttribute("msg") %></td></tr>

</html:messages>

The code above uses the header and footer as keys to get messages out of the resource bundle. To get a list of all of the attributes that html:messages supports, see the online Struts documentation.

 

Note:As a best practice, you should use CSS, not the font tag. The font tag was used for simplicity.

html:multibox

The html:multibox custom tag is a little weird, and it’s bit hard to understand at first. Basically, this tag is used to manage an array of check boxes.

 

The html:multibox tag works with an array of strings. Each element in the array represents a check box. The multibox tag works similar to the html:select tag. When a string is added to the array, the corresponding check box is checked. Conversely, if the string is missing from the array, the corresponding check box is unchecked.

 

Once the form is submitted, the array property of the action form that is associated with the html:multibox tag is populated with all the strings that correspond to the checked check boxes. Here is an example usage of the tag as follows:

<logic:iterate id="newsLetter"

               name="user"

               property="newsLetterChoices">

                      

   <html:multibox property="selectedNewsLetters">          

       <bean:write name="newsLetter"/>

   </html:multibox>

       <bean:write name="newsLetter"/>          

</logic:iterate>

See the modified user registration form example at the end of this chapter for more details on usage.

html:select,  html:option, html:options, and html:optionsCollection

The html:select tag renders a drop-down selection or a list box to the end user. You can specify the options for the html:select tag with the html:select,  html:option, html:options, and html:optionsCollection tags.

The html:option tag generates an option for the html:select tag (<option>). The html:options tag is used to generate a group of HTML <option> elements inside of the html:select tag. The html:optionsCollection tag is also used to generate a list of HTML <option> elements from a collection of JavaBeans.

 

There is an example of using the html:select tag in the example application at the end of this chapter.

Here is an example of creating a single selection box:

<html:form action="html-select.do">

...

      <html:select property="singleSelect" size="10">

        <html:option value="Single 0">Single 0</html:option>

        <html:option value="Single 1">Single 1</html:option>

        <html:option value="Single 2">Single 2</html:option>

        <html:option value="Single 3">Single 3</html:option>

        <html:option value="Single 4">Single 4</html:option>

      </html:select>

The above would render a selection box that was 10 items long (size=“10”). Notice that values of the label are the bodies of the html:option tag. The value that gets submitted to the action is the value attribute. The corresponding ActionForm needs to have a property called singleSelect, which would be a string.

One potential problem with the code above is that it does not support internationalization. You can support internationalization as follows:

<html:select property="resourcesSelect" size="3">

<html:option value="Resources 0" key="resources0"/>

<html:option value="Resources 1" key="resources1"/>

     <html:option value="Resources 2" key="resources2"/>

</html:select>

Here is an example of creating a multiple that gets its values from one collection and its labels from another:

<html:select property="multipleSelect"

                  size="10" multiple="true">

  <html:options name="multipleValues"

                labelName="multipleLabels"/>

</html:select>

Notice that it sets the multiple attribute to true, this tells the custom tag to render a select input that allows multiple items in the selection list to be selected. When you set multiple=“true”, you have to make sure that the corresponding property of the ActionForm subclass is an array type. The html:options tag uses two collections.

 

The first collection is called multipleValues and is used to specify the values that are submitted to the action if the item is selected. The second collection is called multipleLabels, and it is used to populate the labels for the corresponding values in the first collection. There is more than one way to skin a cat:

<html:select property="collectionSelect"

             size="10" multiple="true">

  <html:options collection="options"

                property="value" labelProperty="label"/>

</html:select>

A variation of the html:options tag specifies a single collection with a collection attribute. Then, it specifies an attribute that will contain the value property, and an attribute that specifies the label property. The tag above will iterate over each item in the options collection and call item.getValue() for the value and item.getLabel() fo the label. The property names can be any property names that the beans in the collection support.

Typically when you're accessing a bean in a certain scope in Struts, then you always use three attributes, namely name, property, and scope (more on this when you cover the bean taglib). The html:options tag breaks all thrules when it comes to dealing with collection. However, the html:optionsCollection uses the standard trinity o

attributes as follows:

<html:optionsCollection name="testbean"

                        property="beanCollection"

                        scope="session"

                        label="label"

                        value="value"

                       

                        />

The code above uses the trinity of attributes to grab the test bean out of session scope and uses its collection property called beanCollection. The collection has a list of JavaBeans of a certain type. The JavaBean has a labe property and a value property, which are used by the label and value attributes to extract the label and values

(The property of the JavaBean does not have to be called label and value.)

html:password

The html:password tag renders a password field. The user registration from Chapter 1 has an example of using the html:password tag.

html:radio

The html:radio tag renders a radio check box.

html:reset

The html:reset tag renders a Reset button.

html:rewrite

The html:rewrite tag generates a URL that is encoded similar to what html:link does, except that this tag does not generate an anchor tag—just a URL. This tag is useful for client-side JavaScript function string constants. You can also specify transaction tokens with this tag. For more information, look at the html:link tag discussed earlier in this chapter, as they share a lot of the same attributes.

html:submit

The html:submit tag renders a Submit button. There was an example of this in Chapter 1, and just about every example in this book uses the html:submit tag.

html:text

The html:text tag renders a text input field. This tag has a read-only attribute that makes it a display only tag (i.e., not editable). You can also use the size attribute to limit how much of the field displays. You can use the maxlength attribute to limit how many characters the end user can enter into the field.

html:textarea

The html:textarea tag renders a text area field. You can specify the width of the text area by using the cols attribute. Similarly, you can specify the number of rows with the rows attribute.

html:xhtml

The html:xhtml tag tells the rest of tags in the page to render xhtml elements instead of html elements.

Bean Custom Tag Lib

The Bean tag library provides a group of tags to work with JavaBeans and define JavaBeans.

Before you can start this section, it needs to be clear that if you are working on green field applications, skip this section. (Green field applications are a new type of application without baggage.) Don't use this custom tag library on new projects. You should use JSTL on new projects. See Chapter 8 for more details.

Remember, once the tag library is available to the web application classloader, using a tag library is a two-step process. The first step is declaring that you are going to use the tag library in your web.xml file as follows:

<taglib>

  <taglib-uri>struts-bean</taglib-uri>

  <taglib-location>

      /WEB-INF/struts-bean.tld

  </taglib-location>

</taglib>

The second step is to declare that you’re using the tag library in your JSP page as follows:

<%@ taglib uri="struts-bean" prefix="bean" %>

bean:cookie, bean:header, and bean:parameter

The bean:cookie, bean:header, and bean:parameter tags are used to retrieve the cookies, request headers, and request parameters. The bean:header and bean:parameter tags have an id attribute, so you can define a string attribute in page scope. The bean:cookie tag defines a Cookie object (from the Servlet API). You can specify a default value with the value attribute. If you're expecting multiple values to be returned (i.e., an array), then you set the multiple attribute to true. When you set the multiple attribute to true with bean:header and

bean:parameter, a String[]will be defined instead of just a String. When you set the multiple attribute to true with bean:cookie, a Cookie[] will be defined instead of just a single Cookie object.

Tip:JSTL has an expression language that can access cookies, headers, and parameters; therefore, you do not need these tags if you are using JSTL. All new projects should use JSTL. Existing projects should migrate to JSTL.

<bean:cookie id="sessionID" name="JSESSIONID" value="JSESSIONID-IS-

UNDEFINED"/>

The code above defines a scriptlet variable called sessionID. The value of the sessionID scriptlet variable will be set to “JSESSIONID-IS-UNDEFINED” if the request does not have a cookie called JSESSIONID.

The following code would print out the properties of the Cookie object as follows:

<jsp:getProperty name="sessionID " property="comment"/> …

<jsp:getProperty name="sessionID" property="domain"/> …

<jsp:getProperty name="sessionID" property="maxAge"/> …

<jsp:getProperty name="sessionID" property="path"/> …

<jsp:getProperty name="sessionID" property="value"/> …

<jsp:getProperty name="sessionID" property="version"/> …

Here is an example that prints out all of the headers in the request:

<%

   java.util.Enumeration names =

     ((HttpServletRequest) request).getHeaderNames();

%>

<%

  while (names.hasMoreElements()) {

    String name = (String) names.nextElement();

%>

    <bean:header id="head" name="<%= name %>"/>

    … <%= name %>

    … <%= head %>

    …

<%

  }

%>

Here are some bean:parameter examples:

<bean:parameter id="param1" name="param1"/>

<bean:parameter id="param2" name="param2" multiple="true"/>

<bean:parameter id="param3"

                name="param3" value="UNKNOWN VALUE"/>

The first example grabs a parameter called param1 and defines a scriptlet variable called param1 of type string.

The second example grabs a parameter called param2 and defines a scriptlet variable called param2 of type string array. The third example grabs a parameter called param3, and if the parameter isn't present, it uses the default that is specified by the value entered.

bean:define

The bean:define tag allows you to copy a bean’s property from any scope into a bean in any scope. The bean:define tag uses the trinity of attributes defined in the section earlier in this chapter. It copies the object specified by the trinity of attributes to the scope specified by the toScope attribute. The name of the new attribute is specified by the id attribute.

Tip:Don't use bean define if you are your using JSTL. There's no point. It is better to use core:set. It’s the suggestion of the Struts developers that where a tag overlaps with the JSTL, the tag is consider a future deprecated tag (Struts 1.2 or greater).

bean:include

The bean:include tag is similar to the jsp:include tag with the exception that it defines a scriptlet variable that you can reuse. The name of the new scriptlet variable is specified by the id attribute. The bean:include tag supports four other attributes: forward, href, page, and transaction. The attributes have the same meaning as they do in the html:link. (See the html:link section from earlier in this section for more details.)

Here's an example of how you can use the bean:include tag:

<bean:include id="footerSpacer"

             page="/long/path/footerSpacer.jsp"/>

Then you could use the footerSpacer in several places with the bean:write tag as follows:

<bean:write name="footerSpacer" />

bean:message

The bean:message tag is used to grab messages from the resource bundle. The key attribute specifies the key of the message in the resource bundle. The tag can pass up to four arguments to the message with parameters arg0 through arg3. (See the Java API docs for java.text.MessageFormat for more details about what the argument attributes do). You can also specify a new resource bundle using the bundle attribute. You can override the locale that is in session scope by using the locale attribute. See Chapter 14 for more details on how to use this tag for internationalization.

bean:page

The bean:page tag allows you define JSP implicit objects as scriptlet variables.

Here is a simple example that defines the request object as a scriptlet variable:

<bean:page id="requestObj" property="request"/>

The example above retrieves the implicit request object and stores its reference in the scriptlet variable called requestObj.

bean:resource

The bean:resource tag grabs the raw value of resources in the web application context directory. This concept is best illustrated with an example:

<bean:resource id="webxml" name="/WEB-INF/web.xml"/>

The code above defines a scriptlet variable called webxml based on the value of your web.xml deployment descriptor.

Now, to display the code above, you could use the bean:write tag as follows:

<pre>

<bean:write name="webxml" filter="true"/>

</pre>

bean:size

The bean:size tag gets the count of items stored in an array, collection, or map, and stores the count in a scriptlet variable defined by the id attribute.

<bean:size id="count" name="employees" />

The above would define a scriptlet variable called count based on the number of employees in the employees collection.

bean:struts

The bean:struts tag copies Struts objects into a paged, scoped scriptlet variable. This tag can retrieve ActionForms, ActionForward, or an ActionMapping object with the formbean, forward, or mapping attributes respectively.

Here's an example using a bean:struts tag:

<bean:struts id="userRegistrationForm"

  formBean="UserRegistrationForm"/>

The code above grabs the UserRegistrationForm from the Struts config file.

bean:write

The bean:write tag gets the value of a named bean property. If the format or formatKey attribute is encountered, then the value being written will be formatted based upon the format attribute value for the form value that is stored in the resource bundle. You can specify a particular resource bundle with the bundle attribute. You can also specify a particular locale with the locale attribute. The filter attribute, if true, turn HTML reserved characters into entities (i.e., “<” becomes &lt;). This tag uses the trinity of attributes, namely, name, property, and scope. To learn more about the trinity of attributes, see the trinity of attributes section earlier in this chapter. The value specified by the trinity of attributes will be output to the JSPWriter. The ignore attribute states that if the object is missing, don't throw an exception (the default is false).

<bean:write name="userRegistration"

        property="email"

            scope="request"/>

The code above retrieves the e-mail attribute of the user registration object, which is in request scope.

The Logic Tag Lib

Logic Tag Library

The focus of the logic tag is to provide presentation layer focus. The logic tag library is on its way out.

Note:The JSTL core:if tag does almost everything the logic tag library does in one tag. Try to use JSTL first on new projects. See Chapter 8 on JSTL for more details.

Remember, once the tag library is available to the web application classloader, using a tag library is a two-step process. The first step is declaring that you are going to use the tag library in your web.xml file as follows:

<taglib>

  <taglib-uri>struts-logic</taglib-uri>

  <taglib-location>

      /WEB-INF/struts-logic.tld

  </taglib-location>

</taglib>

The second step is to declare that you are using the tag library in your JSP page as follows:

<%@ taglib uri="struts-logic" prefix="logic" %>

logic:empty and logic:notEmpty The logic:empty tag checks to see if a scriptlet variable is null, an empty string, collection, or map. The logic:notEmpty tag does the opposite (i.e., it checks to see if a scriptlet variable is not null, if it is a string, collection, or map). The logic:notEmpty tag also checks to see if it is not empty:

<logic:empty name="myBean">

  The bean is missing

</logic:empty>

<logic:notEmpty name="myBean">

  The bean is not missing

</logic:notEmpty>

The code above would print out “The bean is missing” if the bean named myBean is not in any scope. Conversely, it would print out “The bean is not missing” if the bean is found in any scope. Both of these tags use the trinity of attributes to access the object (name, property, and scope).

Tip:JSTL EL has an empty operator that functions much like this tag.

logic:equal, logic:notEqual, logic:lessThan, logic:greaterThan, logic:lessEqual, and logic:greaterEqual

The logic:*equal* tags do just what their names state. These tags are a bit cumbersome to use. They all use the trinity of attributes (name, property, and scope).

Here is an example using some of the tags above:

<logic:equal name="bean" property="doubleProperty"

       value="<%= doub1 %>">

  equal

</logic:equal>

<logic:greaterEqual name="bean" property="doubleProperty"

       value="<%= doub1 %>">

  greaterEqual

</logic:greaterEqual>

logic:forward

The logic:forward tag  is similar to a jsp:forward tag except it uses an ActionForward from the global forwards section of the Struts config file. It specifies the name of the forward with the name attribute. Example as follows

<logic:forward name="login" />

The code above refers to a forward in the global forwards area demonstrate of the Struts config file as follows:

<global-forwards>

  <forward name="login" path="/loginForm.jsp"/>

</global-forwards>

Tip:If you are following the Model 2/MVC architecture, the important thing to remember about logic:forward is to never use it. If you are following the Model 2/MVC architecture, then you always select the next View from the controller, not from the View. If you are not following the Model 2/MVC architecture, go back to the Model 1 world.

logic:redirect

The logic:redirect tag is similar to the last tag except by default it does a response.sendRedirect() instead of a requestDispatcher.forward(). Another key difference is it supports all the same attributes as the html:link, so you can pass request parameters and such. Here is an example using the logic:redirect tag and passing a request parameter:

<logic:redirect name="login"

                paramId="employeeId"

                paramName="employee" property="id" />

The code above redirects to the global forward login, which is defined in the global-forwards section of the Struts config file.

Tip:Again, if you are following the Model 2/MVC architecture, do not use the logic:redirect tag. If you are following the Model 2/MVC architecture, then you always select the next View from the controller, not from the View. If you’re not following the Model 2/MVC architecture, you're losing some of the benefits of Struts.

logic:iterate

The logic:iterate tag iterates over a collection, enumerator, iterator, map, or arrayIt evaluates its body for each item in the collection. Here is an example:

<logic:iterate id="employee"

               name="department"

               property="employees"

               scope= "request">

      <bean:write name="employee" property="username" />

      <bean:write name="employee" property="name" />

      <bean:write name="employee" property="phone" />

</logic:iterate>

The code above iterates over a collection of employees. The collection of employees is based on the employees property of the department, which is a request scope. The id attribute specifies a scriptlet variable that is assigned the current item at the start of each iteration, namely employee.

To print out the fifth through the tenth employee, you would use the length and offset attributes as follows:

<logic:iterate id="employee"

               name="department"

               property="employees"

               scope= "request"

               length="10"

               offset="5">

      <bean:write name="employee" property="username" />

      <bean:write name="employee" property="name" />

      <bean:write name="employee" property="phone" />

</logic:iterate>

You may want to define a variable that holds the current iteration. Here is an example:

<ol>

<logic:iterate id="element"

               name="bean"

               property="stringArray"

               indexId="index">

   

       <li>

           <em>

            <bean:write name="element"/>

           </em>&nbsp;

           [<bean:write name="index"/>]</li>

</logic:iterate>

</ol>

The indexId attribute specifies a scriptlet variable called index, which holds that current index number of the loop. This is useful if you want to generate row numbers for long listings.

logic:match and logic:notMatch

The logic:match and logic:notMatch tags check to see if two strings have equal parts at the start of the string, at the end the string, or if any parts of the strings are equal. You can specify the string, which can be a cookie, header, request parameter, or bean property by using the attribute’s cookie, header, parameter, or name and property. The location attribute specifies where the match occurs (start or end). If the location attribute is missing, then the match can occur anywhere in the string.

Here is an example that checks browser type:

<logic:match header="User-Agent" value="Mozilla">

    Mozilla!

  </logic:match>

  <logic:notMatch header="User-Agent" value="Mozilla">

    Not Mozilla :(

  </logic:notMatch>

</logic:present>

Here is another example that checks to see if a bean property matches the string “hello world”:

<logic:match name="bean"

             property="stringProperty"

             value="hello world">

  Hello World!

</logic:match>

<logic:notMatch name="bean"

                property="stringProperty"

                value="hello world">

  I'm so sad and lonely.

</logic:notMatch>

Tip:There's nothing in the JSTL library that is similar to the match or notMatch tags. Therefore, you may use this tag with reckless abandon. Remember, don't put too much application logic in your JSP page.

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载