KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > appfuse > webapp > taglib > LabelTag


1 package org.appfuse.webapp.taglib;
2
3 import java.util.Iterator JavaDoc;
4 import java.util.Locale JavaDoc;
5
6 import javax.servlet.http.HttpServletRequest JavaDoc;
7 import javax.servlet.jsp.JspException JavaDoc;
8 import javax.servlet.jsp.PageContext JavaDoc;
9 import javax.servlet.jsp.jstl.fmt.LocaleSupport;
10 import javax.servlet.jsp.tagext.TagSupport JavaDoc;
11
12 import org.apache.commons.logging.Log;
13 import org.apache.commons.logging.LogFactory;
14 import org.apache.commons.validator.Field;
15 import org.apache.commons.validator.Form;
16 import org.apache.commons.validator.ValidatorResources;
17 import org.apache.struts.Globals;
18 import org.apache.struts.action.ActionMessage;
19 import org.apache.struts.action.ActionMessages;
20 import org.apache.struts.taglib.TagUtils;
21 import org.apache.struts.taglib.html.Constants;
22 import org.apache.struts.taglib.html.FormTag;
23 import org.apache.struts.validator.ValidatorPlugIn;
24
25 /**
26  * <p>This class is designed to render a <label> tag for labeling your forms and
27  * adds an asterik (*) for required fields. It was originally written by Erik
28  * Hatcher (http://www.ehatchersolutions.com/JavaDevWithAnt/).
29  *
30  * <p>It is designed to be used as follows:
31  * <pre>&lt;tag:label key="user.username"/&gt;</pre>
32  *
33  * @jsp.tag name="label" bodycontent="empty"
34  */

35 public class LabelTag extends TagSupport JavaDoc {
36     private static final long serialVersionUID = 3256442512435721011L;
37     protected final transient Log log = LogFactory.getLog(LabelTag.class);
38     protected String JavaDoc key = null;
39     protected String JavaDoc styleClass = null;
40     protected String JavaDoc errorClass = null;
41     protected boolean colon = false;
42
43     public int doStartTag() throws JspException JavaDoc {
44         // Look up this key to see if its a field of the current form
45
boolean requiredField = false;
46         boolean validationError = false;
47         TagUtils tagUtils = TagUtils.getInstance();
48
49         ValidatorResources resources =
50             (ValidatorResources) pageContext.getServletContext()
51                 .getAttribute(ValidatorPlugIn.VALIDATOR_KEY);
52         
53         Locale JavaDoc locale = (Locale JavaDoc) pageContext.findAttribute(Globals.LOCALE_KEY);
54
55         if (locale == null) {
56             locale = Locale.getDefault();
57         }
58         
59         FormTag formTag =
60             (FormTag) pageContext.getAttribute(Constants.FORM_KEY,
61                                                PageContext.REQUEST_SCOPE);
62
63         String JavaDoc formName = formTag.getBeanName();
64         String JavaDoc fieldName = key.substring(key.indexOf('.') + 1);
65
66         if (resources != null) {
67             Form form = resources.getForm(locale, formName);
68
69             if (form != null) {
70                 Field field = form.getField(fieldName);
71
72                 if (field != null) {
73                     if (field.isDependency("required") || field.isDependency("validwhen")) {
74                         requiredField = true;
75                     }
76                 }
77             }
78         }
79
80         ActionMessages errors =
81             tagUtils.getActionMessages(pageContext, Globals.ERROR_KEY);
82
83         StringBuffer JavaDoc valMessage = new StringBuffer JavaDoc();
84
85         if (errors != null) {
86             // check for errors from the validator
87
Iterator JavaDoc valIterator = errors.get(fieldName);
88
89             while (valIterator.hasNext()) {
90                 validationError = true;
91
92                 ActionMessage error = (ActionMessage) valIterator.next();
93
94                 // Retrieve the message string we are looking for
95
valMessage.append(tagUtils.message(pageContext,
96                                                    Globals.MESSAGES_KEY,
97                                                    locale.getDisplayName(),
98                                                    error.getKey(),
99                                                    error.getValues()));
100             }
101         }
102
103         // Retrieve the message string we are looking for
104
String JavaDoc message =
105             tagUtils.message(pageContext, Globals.MESSAGES_KEY,
106                              locale.getDisplayName(), key);
107
108         StringBuffer JavaDoc valError = new StringBuffer JavaDoc();
109
110         if (message == null) {
111             // try using JSTL's fallback locale
112
message = LocaleSupport.getLocalizedMessage(pageContext, key);
113         } else if (validationError) {
114             valError.append(valMessage);
115         }
116         
117         String JavaDoc cssClass = null;
118         if (styleClass != null) {
119             cssClass = styleClass;
120         } else if (requiredField) {
121             cssClass = "required";
122         }
123
124         String JavaDoc cssErrorClass = (errorClass != null) ? errorClass : "error";
125         StringBuffer JavaDoc label = new StringBuffer JavaDoc();
126
127         if ((message == null) || "".equals(message.trim())) {
128             label.append("");
129         } else {
130             label.append("<label for=\"").append(fieldName).append("\"");
131
132             if (validationError) {
133                 label.append(" class=\"").append(cssErrorClass).append("\"");
134             } else if (cssClass != null) {
135                 label.append(" class=\"").append(cssClass).append("\"");
136             }
137
138             label.append(">").append(message);
139             label.append((requiredField) ? " <span class=\"req\">*</span>" : "");
140             label.append((colon) ? ":" : "");
141             label.append("</label>");
142
143             if (valError.length() > 0) {
144                 label.append("<img class=\"validationWarning\" alt=\"");
145                 label.append(tagUtils.message(pageContext,
146                                               Globals.MESSAGES_KEY,
147                                               locale.getDisplayName(),
148                                               "icon.warning"));
149                 label.append("\" ");
150
151                 String JavaDoc context = ((HttpServletRequest JavaDoc) pageContext.getRequest()).getContextPath();
152
153                 label.append("src=\"").append(context);
154                 label.append(tagUtils.message(pageContext,
155                                               Globals.MESSAGES_KEY,
156                                               locale.getDisplayName(),
157                                               "icon.warning.img"));
158                 label.append("\" />");
159             }
160         }
161
162         // Print the retrieved message to our output writer
163
tagUtils.write(pageContext, label.toString());
164
165         // Continue processing this page
166
return (SKIP_BODY);
167     }
168
169     /**
170      * @jsp.attribute required="true" rtexprvalue="true"
171      */

172     public void setKey(String JavaDoc key) {
173         this.key = key;
174     }
175
176     /**
177      * Setter for specifying whether to include colon
178      *
179      * @jsp.attribute required="false" rtexprvalue="true"
180      */

181     public void setColon(boolean colon) {
182         this.colon = colon;
183     }
184
185     /**
186      * Setter for assigning a CSS class, default is label.
187      *
188      * @jsp.attribute required="false" rtexprvalue="true"
189      */

190     public void setStyleClass(String JavaDoc styleClass) {
191         this.styleClass = styleClass;
192     }
193
194     /**
195      * Setter for assigning a CSS class when errors occur,
196      * defaults to labelError.
197      *
198      * @jsp.attribute required="false" rtexprvalue="true"
199      */

200     public void setErrorClass(String JavaDoc errorClass) {
201         this.errorClass = errorClass;
202     }
203
204     /**
205      * Release all allocated resources.
206      */

207     public void release() {
208         super.release();
209         key = null;
210         colon = false;
211         styleClass = null;
212         errorClass = null;
213     }
214 }
215
Popular Tags