KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > struts > taglib > html > JavascriptValidatorTag


1 /*
2  * $Id: JavascriptValidatorTag.java 165208 2005-04-28 21:41:45Z mrdon $
3  *
4  * Copyright 2001-2005 The Apache Software Foundation.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18
19 package org.apache.struts.taglib.html;
20
21 import java.io.IOException JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.Collections JavaDoc;
24 import java.util.Comparator JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.List JavaDoc;
27 import java.util.Locale JavaDoc;
28 import java.util.Map JavaDoc;
29 import java.util.StringTokenizer JavaDoc;
30
31 import javax.servlet.ServletContext JavaDoc;
32 import javax.servlet.http.HttpServletRequest JavaDoc;
33 import javax.servlet.jsp.JspException JavaDoc;
34 import javax.servlet.jsp.JspWriter JavaDoc;
35 import javax.servlet.jsp.PageContext JavaDoc;
36 import javax.servlet.jsp.tagext.BodyTagSupport JavaDoc;
37
38 import org.apache.commons.validator.Field;
39 import org.apache.commons.validator.Form;
40 import org.apache.commons.validator.ValidatorAction;
41 import org.apache.commons.validator.ValidatorResources;
42 import org.apache.commons.validator.Var;
43 import org.apache.commons.validator.util.ValidatorUtils;
44 import org.apache.struts.Globals;
45 import org.apache.struts.action.ActionMapping;
46 import org.apache.struts.config.ModuleConfig;
47 import org.apache.struts.taglib.TagUtils;
48 import org.apache.struts.util.MessageResources;
49 import org.apache.struts.validator.Resources;
50 import org.apache.struts.validator.ValidatorPlugIn;
51
52 /**
53  * Custom tag that generates JavaScript for client side validation based
54  * on the validation rules loaded by the <code>ValidatorPlugIn</code>
55  * defined in the struts-config.xml file.
56  *
57  * @version $Rev: 165208 $ $Date: 2005-04-28 22:41:45 +0100 (Thu, 28 Apr 2005) $
58  * @since Struts 1.1
59  */

60 public class JavascriptValidatorTag extends BodyTagSupport JavaDoc {
61
62     /**
63      * A Comparator to use when sorting ValidatorAction objects.
64      */

65     private static final Comparator JavaDoc actionComparator = new Comparator JavaDoc() {
66         public int compare(Object JavaDoc o1, Object JavaDoc o2) {
67
68             ValidatorAction va1 = (ValidatorAction) o1;
69             ValidatorAction va2 = (ValidatorAction) o2;
70
71             if ((va1.getDepends() == null || va1.getDepends().length() == 0)
72                 && (va2.getDepends() == null || va2.getDepends().length() == 0)) {
73                 return 0;
74
75             } else if (
76                 (va1.getDepends() != null && va1.getDepends().length() > 0)
77                     && (va2.getDepends() == null || va2.getDepends().length() == 0)) {
78                 return 1;
79
80             } else if (
81                 (va1.getDepends() == null || va1.getDepends().length() == 0)
82                     && (va2.getDepends() != null && va2.getDepends().length() > 0)) {
83                 return -1;
84
85             } else {
86                 return va1.getDependencyList().size() - va2.getDependencyList().size();
87             }
88         }
89     };
90
91     /**
92      * The start of the HTML comment hiding JavaScript from old browsers.
93      * @since Struts 1.2
94      */

95     protected static final String JavaDoc HTML_BEGIN_COMMENT = "\n<!-- Begin \n";
96
97     /**
98      * The end of the HTML comment hiding JavaScript from old browsers.
99      * @since Struts 1.2
100      */

101     protected static final String JavaDoc HTML_END_COMMENT = "//End --> \n";
102
103     // ----------------------------------------------------------- Properties
104

105     /**
106      * The servlet context attribute key for our resources.
107      */

108     protected String JavaDoc bundle = Globals.MESSAGES_KEY;
109
110     /**
111      * The default locale on our server.
112      * @deprecated This variable is no longer used.
113      */

114     protected static Locale JavaDoc defaultLocale = Locale.getDefault();
115
116     /**
117      * The name of the form that corresponds with the action name
118      * in struts-config.xml. Specifying a form name places a
119      * &lt;script&gt; &lt;/script&gt; around the javascript.
120      */

121     protected String JavaDoc formName = null;
122     
123     /**
124      * formName is used for both Javascript and non-javascript validations.
125      * For the javascript validations, there is the possibility that we will
126      * be rewriting the formName (if it is a ValidatorActionForm instead of just
127      * a ValidatorForm) so we need another variable to hold the formName just for
128      * javascript usage.
129      */

130     protected String JavaDoc jsFormName = null;
131
132     /**
133      * The line ending string.
134      */

135     protected static String JavaDoc lineEnd = System.getProperty("line.separator");
136
137     /**
138      * The current page number of a multi-part form.
139      * Only valid when the formName attribute is set.
140      */

141     protected int page = 0;
142
143     /**
144      * This will be used as is for the JavaScript validation method name if it has a value. This is
145      * the method name of the main JavaScript method that the form calls to perform validations.
146      */

147     protected String JavaDoc methodName = null;
148
149     /**
150      * Include language attribute in the &lt;script&gt; element. This property is
151      * ignored in XHTML mode.
152      * @since Struts 1.2
153      */

154     protected boolean scriptLanguage = true;
155
156     /**
157      * The static JavaScript methods will only be printed if this is set to "true".
158      */

159     protected String JavaDoc staticJavascript = "true";
160
161     /**
162      * The dynamic JavaScript objects will only be generated if this is set to "true".
163      */

164     protected String JavaDoc dynamicJavascript = "true";
165
166     /**
167      * The src attribute for html script element (used to include an external script
168      * resource). The src attribute is only recognized
169      * when the formName attribute is specified.
170      */

171     protected String JavaDoc src = null;
172
173     /**
174      * The JavaScript methods will enclosed with html comments if this is set to "true".
175      */

176     protected String JavaDoc htmlComment = "true";
177
178     /**
179      * Hide JavaScript methods in a CDATA section for XHTML when "true".
180      */

181     protected String JavaDoc cdata = "true";
182
183     /**
184      * Gets the key (form name) that will be used
185      * to retrieve a set of validation rules to be
186      * performed on the bean passed in for validation.
187      */

188     public String JavaDoc getFormName() {
189         return formName;
190     }
191
192     /**
193      * Sets the key (form name) that will be used
194      * to retrieve a set of validation rules to be
195      * performed on the bean passed in for validation.
196      * Specifying a form name places a
197      * &lt;script&gt; &lt;/script&gt; tag around the javascript.
198      */

199     public void setFormName(String JavaDoc formName) {
200         this.formName = formName;
201     }
202
203     /**
204      * @return Returns the jsFormName.
205      */

206     public String JavaDoc getJsFormName() {
207         return jsFormName;
208     }
209     /**
210      * @param jsFormName The jsFormName to set.
211      */

212     public void setJsFormName(String JavaDoc jsFormName) {
213         this.jsFormName = jsFormName;
214     }
215     /**
216      * Gets the current page number of a multi-part form.
217      * Only field validations with a matching page numer
218      * will be generated that match the current page number.
219      * Only valid when the formName attribute is set.
220      */

221     public int getPage() {
222         return page;
223     }
224
225     /**
226      * Sets the current page number of a multi-part form.
227      * Only field validations with a matching page numer
228      * will be generated that match the current page number.
229      * Only valid when the formName attribute is set.
230      */

231     public void setPage(int page) {
232         this.page = page;
233     }
234
235     /**
236      * Gets the method name that will be used for the Javascript
237      * validation method name if it has a value. This overrides
238      * the auto-generated method name based on the key (form name)
239      * passed in.
240      */

241     public String JavaDoc getMethod() {
242         return methodName;
243     }
244
245     /**
246      * Sets the method name that will be used for the Javascript
247      * validation method name if it has a value. This overrides
248      * the auto-generated method name based on the key (form name)
249      * passed in.
250      */

251     public void setMethod(String JavaDoc methodName) {
252         this.methodName = methodName;
253     }
254
255     /**
256      * Gets whether or not to generate the static
257      * JavaScript. If this is set to 'true', which
258      * is the default, the static JavaScript will be generated.
259      */

260     public String JavaDoc getStaticJavascript() {
261         return staticJavascript;
262     }
263
264     /**
265      * Sets whether or not to generate the static
266      * JavaScript. If this is set to 'true', which
267      * is the default, the static JavaScript will be generated.
268      */

269     public void setStaticJavascript(String JavaDoc staticJavascript) {
270         this.staticJavascript = staticJavascript;
271     }
272
273     /**
274      * Gets whether or not to generate the dynamic
275      * JavaScript. If this is set to 'true', which
276      * is the default, the dynamic JavaScript will be generated.
277      */

278     public String JavaDoc getDynamicJavascript() {
279         return dynamicJavascript;
280     }
281
282     /**
283      * Sets whether or not to generate the dynamic
284      * JavaScript. If this is set to 'true', which
285      * is the default, the dynamic JavaScript will be generated.
286      */

287     public void setDynamicJavascript(String JavaDoc dynamicJavascript) {
288         this.dynamicJavascript = dynamicJavascript;
289     }
290
291     /**
292       * Gets whether or not to delimit the
293       * JavaScript with html comments. If this is set to 'true', which
294       * is the default, the htmlComment will be surround the JavaScript.
295       */

296     public String JavaDoc getHtmlComment() {
297         return htmlComment;
298     }
299
300     /**
301      * Sets whether or not to delimit the
302      * JavaScript with html comments. If this is set to 'true', which
303      * is the default, the htmlComment will be surround the JavaScript.
304      */

305     public void setHtmlComment(String JavaDoc htmlComment) {
306         this.htmlComment = htmlComment;
307     }
308
309     /**
310      * Gets the src attribute's value when defining
311      * the html script element.
312      */

313     public String JavaDoc getSrc() {
314         return src;
315     }
316
317     /**
318      * Sets the src attribute's value when defining
319      * the html script element. The src attribute is only recognized
320      * when the formName attribute is specified.
321      */

322     public void setSrc(String JavaDoc src) {
323         this.src = src;
324     }
325
326     /**
327      * Sets the servlet context attribute key for our resources.
328      */

329     public String JavaDoc getBundle() {
330         return bundle;
331     }
332
333     /**
334      * Gets the servlet context attribute key for our resources.
335      */

336     public void setBundle(String JavaDoc bundle) {
337         this.bundle = bundle;
338     }
339
340     /**
341      * Render the JavaScript for to perform validations based on the form name.
342      *
343      * @exception JspException if a JSP exception has occurred
344      */

345     public int doStartTag() throws JspException JavaDoc {
346
347         JspWriter JavaDoc writer = pageContext.getOut();
348         try {
349             writer.print(this.renderJavascript());
350
351         } catch (IOException JavaDoc e) {
352             throw new JspException JavaDoc(e.getMessage());
353         }
354
355         return EVAL_BODY_TAG;
356
357     }
358
359     /**
360      * Returns fully rendered JavaScript.
361      * @since Struts 1.2
362      */

363     protected String JavaDoc renderJavascript() throws JspException JavaDoc {
364         StringBuffer JavaDoc results = new StringBuffer JavaDoc();
365
366         ModuleConfig config = TagUtils.getInstance().getModuleConfig(pageContext);
367         ValidatorResources resources =
368             (ValidatorResources) pageContext.getAttribute(
369                 ValidatorPlugIn.VALIDATOR_KEY + config.getPrefix(),
370                 PageContext.APPLICATION_SCOPE);
371
372         if (resources == null) {
373             throw new JspException JavaDoc(
374                 "ValidatorResources not found in application scope under key \""
375                 + ValidatorPlugIn.VALIDATOR_KEY + config.getPrefix() + "\"");
376         }
377
378         Locale JavaDoc locale = TagUtils.getInstance().getUserLocale(this.pageContext, null);
379
380         Form form = resources.getForm(locale, formName);
381
382         if ("true".equalsIgnoreCase(dynamicJavascript) && form == null)
383         {
384             throw new JspException JavaDoc("No form found under '"
385                                    + formName
386                                    + "' in locale '"
387                                    + locale
388                                    + "'");
389         }
390
391         if (form != null) {
392             if ("true".equalsIgnoreCase(dynamicJavascript)) {
393                 results.append(
394                         this.createDynamicJavascript(config, resources, locale, form));
395
396             } else if ("true".equalsIgnoreCase(staticJavascript)) {
397                 results.append(this.renderStartElement());
398                 if ("true".equalsIgnoreCase(htmlComment)) {
399                     results.append(HTML_BEGIN_COMMENT);
400                 }
401             }
402         }
403
404         if ("true".equalsIgnoreCase(staticJavascript)) {
405             results.append(getJavascriptStaticMethods(resources));
406         }
407
408         if (form != null
409             && ("true".equalsIgnoreCase(dynamicJavascript)
410                 || "true".equalsIgnoreCase(staticJavascript))) {
411
412             results.append(getJavascriptEnd());
413         }
414
415         return results.toString();
416     }
417
418     /**
419      * Generates the dynamic JavaScript for the form.
420      * @param config
421      * @param resources
422      * @param locale
423      * @param form
424      */

425     private String JavaDoc createDynamicJavascript(
426         ModuleConfig config,
427         ValidatorResources resources,
428         Locale JavaDoc locale,
429         Form form) throws JspException JavaDoc {
430
431         StringBuffer JavaDoc results = new StringBuffer JavaDoc();
432
433         MessageResources messages =
434             TagUtils.getInstance().retrieveMessageResources(pageContext, bundle, true);
435  
436         HttpServletRequest JavaDoc request = (HttpServletRequest JavaDoc)pageContext.getRequest();
437         ServletContext JavaDoc application = pageContext.getServletContext();
438
439         List JavaDoc actions = this.createActionList(resources, form);
440
441         final String JavaDoc methods = this.createMethods(actions, this.stopOnError(config));
442
443         String JavaDoc formName = form.getName();
444         jsFormName = formName;
445                 if(jsFormName.charAt(0) == '/') {
446                     String JavaDoc mappingName = TagUtils.getInstance().getActionMappingName(jsFormName);
447                     ActionMapping mapping = (ActionMapping) config.findActionConfig(mappingName);
448                     if (mapping == null) {
449                         JspException JavaDoc e = new JspException JavaDoc(messages.getMessage("formTag.mapping", mappingName));
450                         pageContext.setAttribute(Globals.EXCEPTION_KEY, e, PageContext.REQUEST_SCOPE);
451                         throw e;
452                     }
453                     jsFormName = mapping.getAttribute();
454                 }
455         
456         results.append(this.getJavascriptBegin(methods));
457
458         for (Iterator JavaDoc i = actions.iterator(); i.hasNext();) {
459             ValidatorAction va = (ValidatorAction) i.next();
460             int jscriptVar = 0;
461             String JavaDoc functionName = null;
462
463
464             if (va.getJsFunctionName() != null
465                 && va.getJsFunctionName().length() > 0) {
466                 functionName = va.getJsFunctionName();
467             } else {
468                 functionName = va.getName();
469             }
470
471             
472             results.append(" function " + jsFormName + "_" + functionName + " () { \n");
473             for (Iterator JavaDoc x = form.getFields().iterator(); x.hasNext();) {
474                 Field field = (Field) x.next();
475
476                 // Skip indexed fields for now until there is a good way to handle
477
// error messages (and the length of the list (could retrieve from scope?))
478
if (field.isIndexed()
479                     || field.getPage() != page
480                     || !field.isDependency(va.getName())) {
481
482                     continue;
483                 }
484
485                 String JavaDoc message = Resources.getMessage(application,
486                                                        request,
487                                                        messages,
488                                                        locale,
489                                                        va,
490                                                        field);
491
492                 message = (message != null) ? message : "";
493
494                 // prefix variable with 'a' to make it a legal identifier
495
results.append(
496                     " this.a"
497                         + jscriptVar++
498                         + " = new Array(\""
499                         + field.getKey()
500                         + "\", \""
501                         + escapeQuotes(message)
502                         + "\", ");
503
504                 results.append("new Function (\"varName\", \"");
505
506                 Map JavaDoc vars = field.getVars();
507                 // Loop through the field's variables.
508
Iterator JavaDoc varsIterator = vars.keySet().iterator();
509                 while (varsIterator.hasNext()) {
510                     String JavaDoc varName = (String JavaDoc) varsIterator.next();
511                     Var var = (Var) vars.get(varName);
512                     String JavaDoc varValue = var.getValue();
513                     String JavaDoc jsType = var.getJsType();
514
515                     // skip requiredif variables field, fieldIndexed, fieldTest, fieldValue
516
if (varName.startsWith("field")) {
517                         continue;
518                     }
519
520                     String JavaDoc varValueEscaped = ValidatorUtils.replace(varValue, "\\", "\\\\");
521                     varValueEscaped = ValidatorUtils.replace(varValueEscaped, "\"", "\\\"");
522
523                     if (Var.JSTYPE_INT.equalsIgnoreCase(jsType)) {
524                         results.append(
525                             "this."
526                                 + varName
527                                 + "="
528                                 + varValueEscaped
529                                 + "; ");
530                     } else if (Var.JSTYPE_REGEXP.equalsIgnoreCase(jsType)) {
531                         results.append(
532                             "this."
533                                 + varName
534                                 + "=/"
535                                 + varValueEscaped
536                                 + "/; ");
537                     } else if (Var.JSTYPE_STRING.equalsIgnoreCase(jsType)) {
538                         results.append(
539                             "this."
540                                 + varName
541                                 + "='"
542                                 + varValueEscaped
543                                 + "'; ");
544                         // So everyone using the latest format doesn't need to change their xml files immediately.
545
} else if ("mask".equalsIgnoreCase(varName)) {
546                         results.append(
547                             "this."
548                                 + varName
549                                 + "=/"
550                                 + varValueEscaped
551                                 + "/; ");
552                     } else {
553                         results.append(
554                             "this."
555                                 + varName
556                                 + "='"
557                                 + varValueEscaped
558                                 + "'; ");
559                     }
560                 }
561
562                 results.append(" return this[varName];\"));\n");
563             }
564             results.append(" } \n\n");
565         }
566
567         return results.toString();
568     }
569
570     private String JavaDoc escapeQuotes(String JavaDoc in)
571     {
572         if (in == null || in.indexOf("\"") == -1)
573         {
574             return in;
575         }
576         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
577         StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(in, "\"", true);
578
579         while (tokenizer.hasMoreTokens())
580         {
581             String JavaDoc token = tokenizer.nextToken();
582             if (token.equals("\""))
583             {
584                 buffer.append("\\");
585             }
586             buffer.append(token);
587         }
588
589         return buffer.toString();
590     }
591
592     /**
593      * Determines if validations should stop on an error.
594      * @param config The <code>ModuleConfig</code> used to lookup the
595      * stopOnError setting.
596      * @return <code>true</code> if validations should stop on errors.
597      */

598     private boolean stopOnError(ModuleConfig config) {
599         Object JavaDoc stopOnErrorObj =
600             pageContext.getAttribute(
601                 ValidatorPlugIn.STOP_ON_ERROR_KEY + '.' + config.getPrefix(),
602                 PageContext.APPLICATION_SCOPE);
603
604         boolean stopOnError = true;
605
606         if (stopOnErrorObj instanceof Boolean JavaDoc) {
607             stopOnError = ((Boolean JavaDoc) stopOnErrorObj).booleanValue();
608         }
609
610         return stopOnError;
611     }
612
613     /**
614      * Creates the JavaScript methods list from the given actions.
615      * @param actions A List of ValidatorAction objects.
616      * @param stopOnError If true, behaves like released version of struts 1.1
617      * and stops after first error. If false, evaluates all validations.
618      * @return JavaScript methods.
619      */

620     private String JavaDoc createMethods(List JavaDoc actions, boolean stopOnError) {
621         StringBuffer JavaDoc methods = new StringBuffer JavaDoc();
622         final String JavaDoc methodOperator = stopOnError ? " && " : " & ";
623
624         Iterator JavaDoc iter = actions.iterator();
625         while (iter.hasNext()) {
626             ValidatorAction va = (ValidatorAction) iter.next();
627
628             if (methods.length() > 0) {
629                 methods.append(methodOperator);
630             }
631             methods.append(va.getMethod())
632                    .append("(form)");
633         }
634
635         return methods.toString();
636     }
637
638     /**
639      * Get List of actions for the given Form.
640      * @param resources
641      * @param form
642      * @return A sorted List of ValidatorAction objects.
643      */

644     private List JavaDoc createActionList(ValidatorResources resources, Form form) {
645
646         List JavaDoc actionMethods = new ArrayList JavaDoc();
647
648         Iterator JavaDoc iterator = form.getFields().iterator();
649         while (iterator.hasNext()) {
650             Field field = (Field) iterator.next();
651
652             for (Iterator JavaDoc x = field.getDependencyList().iterator(); x.hasNext();) {
653                 Object JavaDoc o = x.next();
654
655                 if (o != null && !actionMethods.contains(o)) {
656                     actionMethods.add(o);
657                 }
658             }
659         }
660
661         List JavaDoc actions = new ArrayList JavaDoc();
662
663         // Create list of ValidatorActions based on actionMethods
664
iterator = actionMethods.iterator();
665         while (iterator.hasNext()) {
666             String JavaDoc depends = (String JavaDoc) iterator.next();
667             ValidatorAction va = resources.getValidatorAction(depends);
668
669             // throw nicer NPE for easier debugging
670
if (va == null) {
671                 throw new NullPointerException JavaDoc(
672                     "Depends string \""
673                         + depends
674                         + "\" was not found in validator-rules.xml.");
675             }
676
677             if (va.getJavascript() != null && va.getJavascript().length() > 0) {
678                 actions.add(va);
679             } else {
680                 iterator.remove();
681             }
682         }
683
684         Collections.sort(actions, actionComparator);
685
686         return actions;
687     }
688
689     /**
690      * Release any acquired resources.
691      */

692     public void release() {
693         super.release();
694         bundle = Globals.MESSAGES_KEY;
695         formName = null;
696         jsFormName = null;
697         page = 0;
698         methodName = null;
699         staticJavascript = "true";
700         dynamicJavascript = "true";
701         htmlComment = "true";
702         cdata = "true";
703         src = null;
704     }
705
706     /**
707      * Returns the opening script element and some initial javascript.
708      */

709     protected String JavaDoc getJavascriptBegin(String JavaDoc methods) {
710         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
711         String JavaDoc name = jsFormName.replace('/', '_'); // remove any '/' characters
712
name =
713             jsFormName.substring(0, 1).toUpperCase()
714                 + jsFormName.substring(1, jsFormName.length());
715
716         sb.append(this.renderStartElement());
717
718         if (this.isXhtml() && "true".equalsIgnoreCase(this.cdata)) {
719             sb.append("//<![CDATA[\r\n");
720         }
721
722         if (!this.isXhtml() && "true".equals(htmlComment)) {
723             sb.append(HTML_BEGIN_COMMENT);
724         }
725         sb.append("\n var bCancel = false; \n\n");
726
727         if (methodName == null || methodName.length() == 0) {
728             sb.append(
729                 " function validate"
730                     + name
731                     + "(form) { \n");
732         } else {
733             sb.append(
734                 " function "
735                     + methodName
736                     + "(form) { \n");
737         }
738         sb.append(" if (bCancel) \n");
739         sb.append(" return true; \n");
740         sb.append(" else \n");
741
742         // Always return true if there aren't any Javascript validation methods
743
if (methods == null || methods.length() == 0) {
744             sb.append(" return true; \n");
745         } else {
746             //Making Sure that Bitwise operator works:
747
sb.append(" var formValidationResult;\n");
748             sb.append(" formValidationResult = " + methods + "; \n");
749             sb.append(" return (formValidationResult == 1);\n");
750         }
751
752         sb.append(" } \n\n");
753
754         return sb.toString();
755     }
756
757     protected String JavaDoc getJavascriptStaticMethods(ValidatorResources resources) {
758         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
759
760         sb.append("\n\n");
761
762         Iterator JavaDoc actions = resources.getValidatorActions().values().iterator();
763         while (actions.hasNext()) {
764             ValidatorAction va = (ValidatorAction) actions.next();
765             if (va != null) {
766                 String JavaDoc javascript = va.getJavascript();
767                 if (javascript != null && javascript.length() > 0) {
768                     sb.append(javascript + "\n");
769                 }
770             }
771         }
772
773         return sb.toString();
774     }
775
776     /**
777      * Returns the closing script element.
778      */

779     protected String JavaDoc getJavascriptEnd() {
780         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
781
782         sb.append("\n");
783         if (!this.isXhtml() && "true".equals(htmlComment)){
784             sb.append(HTML_END_COMMENT);
785         }
786
787         if (this.isXhtml() && "true".equalsIgnoreCase(this.cdata)) {
788             sb.append("//]]>\r\n");
789         }
790
791         sb.append("</script>\n\n");
792
793         return sb.toString();
794     }
795
796     /**
797      * Constructs the beginning &lt;script&gt; element depending on XHTML
798      * status.
799      * @since Struts 1.2
800      */

801     protected String JavaDoc renderStartElement() {
802         StringBuffer JavaDoc start = new StringBuffer JavaDoc("<script type=\"text/javascript\"");
803
804         // there is no language attribute in XHTML
805
if (!this.isXhtml() && this.scriptLanguage) {
806             start.append(" language=\"Javascript1.1\"");
807         }
808
809         if (this.src != null) {
810             start.append(" SRC=\"" + src + "\"");
811         }
812
813         start.append("> \n");
814         return start.toString();
815     }
816
817     /**
818      * Returns true if this is an xhtml page.
819      */

820     private boolean isXhtml() {
821         return TagUtils.getInstance().isXhtml(this.pageContext);
822     }
823
824     /**
825      * Returns the cdata setting "true" or "false".
826      * @return String - "true" if JavaScript will be hidden in a CDATA section
827      */

828     public String JavaDoc getCdata() {
829         return cdata;
830     }
831
832     /**
833      * Sets the cdata status.
834      * @param cdata The cdata to set
835      */

836     public void setCdata(String JavaDoc cdata) {
837         this.cdata = cdata;
838     }
839
840     /**
841      * Gets whether or not the &lt;script&gt; element will include the
842      * language attribute.
843      * @return true if language attribute will be included.
844      * @since Struts 1.2
845      */

846     public boolean getScriptLanguage() {
847         return this.scriptLanguage;
848     }
849
850     /**
851      * Sets whether or not the &lt;script&gt; element will include the
852      * language attribute.
853      * @since Struts 1.2
854      */

855     public void setScriptLanguage(boolean scriptLanguage) {
856         this.scriptLanguage = scriptLanguage;
857     }
858
859 }
860
Popular Tags