Struts Tag Libraries
- Tag Library Overview
- The Bean Tag Library
- The Html Tag Library
- The Logic Tag Library
- Example with Struts Tags
| Tag Library Overview |
The Struts Taglib component provides a set of JSP custom tag libraries that help developers create interactive form-based applications. The Struts framework takes advantage of the tag library feature of JSP to include several different categories of tags that help to make the presentation layer more manageable and reusable. Using the Struts custom tag libraries, developers are able to interact with the framework without including Java code in the JSP pages. This chapter provides an overview of the different categories of tags available in the Struts framework and how they can make developing applications even easier.
There are many benefits of using custom tags instead of scriptlets and Java code in your JSP pages
- Tags are reusable, which saves precious development and testing time.
- Tags have access to all of the objects available to the JSP page, including request, response, and output variables.
- Tags can be nested, which allows for more complex interactions within a JSP page.
- Tags simplify the readability of a JSP page.
A tag library is made up of the following components
- Tag handler: It is a Java class that gets invoked at runtime and that performs some predefined behavior.
- The TLD file: The tag library descriptor (TLD) file is an XML file that contains meta-information about the tags within a library. Information such as the tag name, the attributes that are required, and the tag handler class name are all contained in this file and read in by the JSP container.
- The web.xml file: Web.xml is a Web application deployment descriptors. Within this descriptor, you must define what tag libraries are being used in the Web application and which TLD files should be used to describe each tag library.
- The JSP page: The JSP page is a key component. It contains the include directives for one or more tag libraries, as well as the needed calls to the tag libraries within the JSP page.
Struts Taglib is composed of four distinct tag libraries: Bean, HTML, Logic, and Nested.
| The Bean Tag Library |
The Bean tag library provides a group of tags that encapsulate the logic necessary to access and manipulate JavaBeans, HTTP cookies, and HTTP headers using scripting variables.
To use the Bean tag library in a Web application, you must complete the following steps
- Copy the TLD packaged with this tag library, struts-bean.tld, to the /WEB-INF/ directory.
- Make sure that the struts.jar file is in the /WEB-INF/lib directory.
- Add the following <taglib> subelement to the Web.xml file of the Web application:
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
You must add the following taglib directive to each JSP that will leverage the Bean tag library:
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
This directive identifies the URI defined in the previously listed <taglib> element and states that all Bean tags should be prefixed with the string bean.
There are currently 11 custom tags in the Bean tag library. These tags can be used to do the following:
- Create a JSP scripting variable from an HTTP header, request parameter, cookie, or any existing object in any scope.
- Create a new bean from the response to another request (include), from an application resource, or from a Struts configuration object.
- Determine the number of elements in a collection or a map. Automatically write a localized message for the current user from an application resource.
- Write the value of a given property on any available bean.
Bean Tag Library
| Tag Name | Description |
|---|---|
| Cookie | Defines a scripting variable based on the value(s) of the specified request cookie |
| define | Defines a scripting variable based on the value(s) of the specified bean property |
| header | Defines a scripting variable based on the value(s) of the specified request header |
| include | Loads the response from a dynamic application request and makes it available as a bean |
| message | Renders an internationalized message string |
| page | Exposes a specified item from the page context as a bean |
| parameter | Defines a scripting variable based on the value(s) of the specified request parameter |
| resource | Loads a Web application resource and makes it available as a bean |
| size | Defines a bean containing the number of elements in a Collection or Map |
| struts | Exposes a Struts internal configuration object as a bean |
| write | Renders the value of the specified bean property |
The <bean:message />
The <bean:message /> tag is a very useful tag that we can employ to retrieve keyed values from a previously defined resource bundle. It also supports the ability to include parameters that can be substituted for defined placeholders in the retrieved string. The <bean:message /> tag has no body
Example
<html>
<head>
<title>
<bean:message key="app.title"/>
</title>
</head>
<body>
</body>
</html>
In this example, we are retrieving the value stored in the resource bundle that is referenced by the keyapp.title. This retrieved value will be substituted for the occurrence of this <bean:message /> tag. The result is a JSP that will have an HTML <title> that matches the locale of the requesting client.
<bean:write />
The <bean:write /> tag is used to retrieve and print the value of a named bean property. If the format attribute is encountered, then the value being written will be formatted based upon the format string represented by the format attribute. The <bean:write /> tag has no body and supports nine attributes.
<bean:write name="employee" property="username" />
In this example, we retrieve and print the username property of the employee scripting variable. Here, because the scope attribute is not set, the tag will search for the bean in the scopes-in the order of page, request, session, and application.
| The Html Tag Library |
The HTML tags are used to create input forms, as well as other tags generally useful in the creation of HTML-based user interfaces. The output is HTML 4.01 compliant or XHTML 1.0 when in XHTML mode.
To use the Html tag library in a Web application, you must complete the following steps:
- Copy the TLD packaged with this tag library, struts-html.tld, to the /WEB-INF/ directory.
Make sure that the struts.jar file is in the /WEB-INF/lib directory.
Add the following <taglib> subelement to the web.xml file of the Web application:
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
You must add the following taglib directive to each JSP that will leverage the Html tag library:
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
This directive identifies the URI defined in the previously listed <taglib> element and states that all Html tags should be prefixed with the string html.
The Struts html taglib provides a set of more than 20 tags to help you pre populate HTML controls and related elements.
How Struts html tags correspond to HTML elements
| Struts html Tag | Corresponding HTML TAG | Struts html Tag | Corresponding HTML TAG |
|---|---|---|---|
| base | <base> | link | <a> |
| button | <input type="button"> | messages | Nonedisplays a set of accumulated error message |
| cancel | <input type="cancel"> | Options option, | <option> |
| checkbox, multibox | <input type="checkbox"> | password | <input type="password"> |
| errors | Nonedisplays a set of accumulated error messages | radio | <input type="radio"> |
| file | <input type="file"> | reset | <input type="reset"> |
| form | <form> | rewrite | Noneoutputs a URL-encoded path |
| hidden | <input type="hidden"> | select | <select> |
| html | <html> | submit | <input type="submit"> |
| image | <input type="image> | text | <input type="text"> |
| img | <img> | textarea | <input type="textarea"> |
This one-to-one correspondence makes converting existing HTML or JSP pages to Struts a very straightforward process. For example, wherever an HTML element like <input type=”text” name=”username”> is found, it can be replaced with the corresponding Struts html tag: <html:text property=”username”/>
Common properties
Like the Struts tags overall, the Struts html tags share a number of common properties as shown as follows:
Struts html taglibs use a consistent set of property names
| Property | Purpose |
|---|---|
| name | The name of the ActionForm, or other JavaBean, that provides the data for this control.If not specified, the ActionForm bean associated with the enclosing form tag is used. |
| on* | Each of the html tags includes the appropriate JavaScript event handlers [Netscape], including onblur, onchange, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onreset, and onsubmit. These are all rendered in lowercase for compatibility with XML. |
| accesskey | Accessibility key character (ignored by some browsers). Pressing an access key assigned to an element gives focus to the element. |
| tabindex | An attribute that specifies the position of the current element in the tabbing order for the current document. The tabbing order defines the order in which elements will receive focus when navigated by the user through the keyboard. |
| style | CSS styles [W3C, CSS] to be applied to this HTML element. |
| StyleClass | CSS style sheet class [W3C, CSS] to be applied to this HTML element. |
Example 1
An example of using the <html:button /> tag is shown here:
<html:button property="itemId">Add</html:button>
When this snippet is evaluated, it will result in an HTML snippet similar to the following:
<input type="button" name="itemId" value="Add">
In this example, you are creating a simple HTML <button> that will use its body as the label of the button. It will also be named using the value of the property attribute.
Example 2
An example of using the <html:select/> tag is shown here:
Note: For this example, it is assumed that the parent <html:form /> contains a reference to an ActionForm that contains the String property, userName, set to the value Bob.
<html:select property="userName">
<html:option value="Robert">Robert</html:option>
<html:option value="Bob">Bob</html:option>
<html:option value="Roberto">Roberto</html:option>
<html:option value="Bobby">Bobby</html:option>
</html:select>
When this snippet is evaluated, it will result in an HTML snippet similar to the following:
<select name="userName">
<option value="Robert">Robert</option>
<option value="Bob" selected="selected">Bob</option>
<option value="Roberto">Roberto</option>
<option value="Bobby">Bobby</option>
</select>
In this example, we are creating a <html:select /> tag with a single attribute property, which maps to the ActionForm bean property userName. This property is used to determine the currently selected <option> of the <select> element, which will be demonstrated in the <html:option /> and <html:options /> tags.
Example 3
An example of using the <html:checkbox /> tag is shown here:
<html:checkbox property="deleteItem">Delete<html:checkbox />
When this snippet is evaluated, it will result in an HTML snippet similar to the following:
<input type="checkbox" name="deleteItem" value="on">Delete
This example assumes that there is an ActionForm bean, named by the <action> element associated with this form, with a property of deleteItem. In this example, we are creating a simple HTML checkbox, with a name of deleteItem and a label of Delete. This will result in the creation of a checkbox with the value of the ActionForm’s deleteItem property.
| The Logic Tag Library |
The Logic tags those are useful in managing conditional generation of output text, looping over object collections for repetitive generation of output text, and application flow management.
To use the logic tag library in a Web application, you must complete the following steps:
- Copy the TLD packaged with this tag library, struts-logic.tld, to the /WEB-INF/ directory.
- Make sure that the struts.jar file is in the /WEB-INF/lib directory.
- Add the following <taglib> subelement to the web.xml file of the Web application:
<taglib>
<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld<taglib-location>
</taglib>
You must add the following taglib directive to each JSP that will leverage the Logic tag library:
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
This directive identifies the URI defined in the previously listed <taglib> element and states that all Logic tags should be prefixed with the string logic.
Struts offers three flavors of logic tags: evaluation tags, control-flow tags, and a repeat tag
| Tag | Purpose |
|---|---|
| Evaluation tags | For testing if values are equal, less than, greater than, empty (blank or null), or even present |
| Control-flow tags | For redirecting or forwarding the request |
| Repeat tag | For iterating over any type of collection |
Evaluation tags
The Struts logic tags are often used to provide alternative versions of the same presentation page. Depending on the existence or value of an object or property, a given block of markup is selected and presented to the user:
<logic:notPresent name="logonForm">
<html:link forward="logon">Sign in here</html:link>
</logic:notPresent>
<logic:present name="logonForm">
<html:link forward="logoff">Sign out</html:link>
</logic:present>
Many pages will differ slightly depending on certain circumstances, such as whether a user is logged in. Logged-in users may see a dialog box offering them the chance to log out. Logged-out users may see a dialog box offering them the chance to log in. When users are logged in, they may also have access to administrative controls. In addition, users may have access to different controls based on their security role. Often, most of the page remains the same, the only difference being a line or two of markup.
Evaluation tags-common properties
Struts provide a full complement of evaluation tags: empty notEmpty equal, notEqual, greaterEqual, lessEqual, greaterThan, lessThan, match, notMatch, present, and notPresent. All of these tags require a value property upon which to base the evaluation. Of course, the value property can be determined by runtime expression if needed:
<bean:define id="value2" name="bean2" property="value"/>
<logic:equal value="<%=(String) value2 %>" name="bean1" property="value">
<%-- markup for when bean1.value equals bean2.value --%>
HIT!
</logic:equal>
<logic:present />
The <logic:present /> tag evaluates its body if the variable specified by any one of the cookie, header, name, parameter, or property attributes is present in the applicable scope.
An example of using the <logic:present /> tag is shown here:
<logic:present parameter="username">
Hello <%= username %>!!!
</logic:present />
In this example, you test for the existence of the request parameter username. If the username parameter is part of the request, then the tag’s body will be evaluated.
<logic:empty />
The <logic:empty /> tag evaluates its body if either the scripting variable identified by the name attribute or a property of the named scripting variable is equal to null or an empty string.
An example of using the <logic:empty /> tag is shown here:
<logic:empty name="user">
<forward name="login" />
</logic:empty />
In this example, you test the scripting variable user. If this variable is null or an empty string, then the body will be evaluated, which will result in the user being forwarded to the global forward login.
Control-flow tags
Redirect and forward tags are used as contol-flow Tags. A very good use of the redirect or forward tag is to send control from a default welcome page to an Action.
<logic:forward />
The <logic:forward /> tag is used to forward control of the current request to a previously identified global forward element. The <logic:forward /> tag has no body and supports a single attribute name, which identifies the name of the global element that will receive control of the request.
An example of using the <logic:forward /> tag is shown here:
<logic:forward name=”login” />
In this example, you forward the current request to the global forward login. This resource must be defined in the <global-forwards /> section of the struts-config.xml file.
<global-forwards>
<forward name="login" path="/login.jsp"/>
</global-forwards>
<logic:redirect />
The <logic:redirect /> tag uses the HttpServletResponse.sendRedirect() method to redirect the current request to a resource identified by either the forward, href, or page attributes.
An example of using the <logic:redirect /> tag is shown here:
<logic:redirect name="login" paramclass="ncompanyId" paramName="company" />
In this example, we perform a redirect to the global forward login. This resource must be defined in the <global-forwards /> section of the struts-config.xml file. The <logic:redirect /> tag differs from the <logic:forward /> tag in that the <logic:redirect /> tag allows you to dynamically augment the request with parameters.
The repeat tag
The <logic:iterate/> tag is used to iterate over a named collection-which contains a Collection, Enumerator, Iterator, Map, or Array-and evaluates its body for each Object in the collection. We can identify the collection being iterated over by using a request-time expression or a scripting variable.
An example of using the <logic:iterate /> tag is shown here:
<logic:iterate id="employee" name="employees">
<tr align="left">
<td> <bean:write name="employee" property="username" /> </td>
<td> <bean:write name="employee" property="name" /> </td>
<td> <bean:write name="employee" property="phone" /> </td>
</tr>
</logic:iterate>
In this example, we are iterating over the collection referenced by the employee’s scripting variable. As the <logic:iterate /> tag iterates over the named collection, it exposes each object in the collection in the employee scripting variable. The result of this iteration is an HTML table row for each object in the named collection.
| Example with Struts Tags |
Create a employee self update page (emp.jsp) using struts tags which displays Employee Name,Id,Address,Phone Number, gender, and Qualification. Create Corresponding Action Form and ApplicationResources.properties files.
web.xml
<!-- Struts Tag Library Descriptors -->
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
employee.jsp
<%@ taglib prefix="html" uri="/WEB-INF/struts-html.tld" %>
<%@ taglib prefix="logic" uri="/WEB-INF/struts-logic.tld" %>
<%@ taglib prefix="bean" uri="/WEB-INF/struts-bean.tld" %>
<html:html>
<html:form action="update.do" >
<table>
<tr>
<td><bean:message key="update.name"/> </td>
<td><bean:write property="name"/></td>
<td><bean:message key="update.associateid"/></td>
<td><bean:write property ="id"/></td>
<td> </td>
</tr>
<tr>
<td><bean:message key="update.address"/></td>
<td><html:textarea property="address" /></td>
<td> </td>
</tr>
<tr>
<td><bean:message key="update.phoneno"/></td>
<td><html:text property="phone"></td>
<td> </td>
</tr>
<tr>
<td><bean:message key="update.gender"/> </td>
<td><bean:message key="gender.male"/>
<html:radio property="gender"/>
<bean:message key="gender.female"/>
<html:radio property="gender"/></td>
</tr>
<tr>
<td><bean:message key="update.qualification"/></td>
<td><html:select property="qualification">
<html:option value="1">B.SC</html:option>
<html:option value="2">B.Tech</html:option>
<html:option value="3">M.SC</html:option>
</html:select> </td>
</tr>
<tr> <html:submit>Update</html:submit>
</tr>
</html:form>
</html:html>
EmployeeForm.java
import org.apache.struts.action.*;
import org.apache.struts.validator.*;
public class EmpForm extends ValidatorForm
{
private String name;
private String id;
private String phone;
private String address;
private boolean gender;
private String qualification;
/**
* @return Returns the address.
*/
public String getAddress() {
return address;
}
/**
* @param address The address to set.
*/
public void setAddress(String address) {
this.address = address;
}
/**
* @return Returns the gender.
*/
public boolean isGender() {
return gender;
}
/**
* @param gender The gender to set.
*/
public void setGender(boolean gender) {
this.gender = gender;
}
/**
* @return Returns the id.
*/
public String getId() {
return id;
}
/**
* @param id The id to set.
*/
public void setId(String id) {
this.id = id;
}
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
/**
* @return Returns the phone.
*/
public String getPhone() {
return phone;
}
/**
* @param phone The phone to set.
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* @return Returns the qualification.
*/
public String getQualification() {
return qualification;
}
/**
* @param qualification The qualification to set.
*/
public void setQualification(String qualification) {
this.qualification = qualification;
}
}
ApplicationResources.properties
update.name = Name
update.associateid = Associate ID
update.address= Current address
update.phoneno = Phone Number
update.gender =Gender
gender.male=Male
gender.female=Female
update.qualification=Qualification
Organize files as Below
- Keep struts-html.tld, struts-bean.tld and struts-logic.tld in \WEB-INF folder
- Keep ApplicationResources.properties in \WEB-INF\classes folder
- All tag libraries are defined in Web.xml deployment descriptor. <bean:message key=”update.name”/> access the value of the key “update.name” from ApplicationResources.properties and write it in to jsp. bean:write property=”name”/> access the value of the property “name” from EmpForm (ActionForm) and write in to jsp. <html:submit> creates a corresponding HTML submit button .Similarly for other bean and html tags.
Recent Comments