📄 validatortool.java
字号:
package org.apache.velocity.tools.struts;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.Form;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorResources;
import org.apache.commons.validator.Var;
import org.apache.struts.Globals;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.ModuleUtils;
import org.apache.struts.validator.Resources;
import org.apache.struts.validator.ValidatorPlugIn;
import org.apache.velocity.tools.view.context.ViewContext;
/**
* <p>View tool that works with Struts Validator to
* produce client side javascript validation for your forms.</p>
* <p>Usage:
* <pre>
* Template example:
*
* $validator.getJavascript("nameOfYourForm")
*
* Toolbox configuration:
* <tool>
* <key>validator</key>
* <scope>request</scope>
* <class>org.apache.velocity.tools.struts.ValidatorTool</class>
* </tool>
* </pre>
* </p>
* <p>This is an adaptation of the JavascriptValidatorTag
* from the Struts 1.1 validator library.</p>
*
* @author David Winterfeldt
* @author David Graham
* @author <a href="mailto:marinoj@centrum.is">Marino A. Jonsson</a>
* @author Nathan Bubna
* @since VelocityTools 1.1
* @version $Revision: 497643 $ $Date: 2007-01-18 15:54:14 -0800 (Thu, 18 Jan 2007) $
*/
public class ValidatorTool
{
/** A reference to the ViewContext */
protected ViewContext context;
/** A reference to the ServletContext */
protected ServletContext app;
/** A reference to the HttpServletRequest. */
protected HttpServletRequest request;
/** A reference to the HttpSession. */
protected HttpSession session;
/** A reference to the ValidatorResources. */
protected ValidatorResources resources;
private static final String HTML_BEGIN_COMMENT = "\n<!-- Begin \n";
private static final String HTML_END_COMMENT = "//End --> \n";
private boolean xhtml = false;
private boolean htmlComment = true;
private boolean cdata = true;
private String formName = null;
private String methodName = null;
private String src = null;
private int page = 0;
/**
* formName is used for both Javascript and non-javascript validations.
* For the javascript validations, there is the possibility that we will
* be rewriting the formName (if it is a ValidatorActionForm instead of just
* a ValidatorForm) so we need another variable to hold the formName just for
* javascript usage.
*/
protected String jsFormName = null;
/**
* A Comparator to use when sorting ValidatorAction objects.
*/
private static final Comparator actionComparator = new Comparator() {
public int compare(Object o1, Object o2) {
ValidatorAction va1 = (ValidatorAction) o1;
ValidatorAction va2 = (ValidatorAction) o2;
if ((va1.getDepends() == null || va1.getDepends().length() == 0)
&& (va2.getDepends() == null || va2.getDepends().length() == 0)) {
return 0;
} else if (
(va1.getDepends() != null && va1.getDepends().length() > 0)
&& (va2.getDepends() == null || va2.getDepends().length() == 0)) {
return 1;
} else if (
(va1.getDepends() == null || va1.getDepends().length() == 0)
&& (va2.getDepends() != null && va2.getDepends().length() > 0)) {
return -1;
} else {
return va1.getDependencyList().size() - va2.getDependencyList().size();
}
}
};
/**
* Default constructor. Tool must be initialized before use.
*/
public ValidatorTool() {}
/**
* Initializes this tool.
*
* @param obj the current ViewContext
* @throws IllegalArgumentException if the param is not a ViewContext
*/
public void init(Object obj)
{
if (!(obj instanceof ViewContext))
{
throw new IllegalArgumentException(
"Tool can only be initialized with a ViewContext");
}
this.context = (ViewContext)obj;
this.request = context.getRequest();
this.session = request.getSession(false);
this.app = context.getServletContext();
Boolean b = (Boolean)context.getAttribute(ViewContext.XHTML);
if (b != null)
{
this.xhtml = b.booleanValue();
}
/* Is there a mapping associated with this request? */
ActionConfig config =
(ActionConfig)request.getAttribute(Globals.MAPPING_KEY);
if (config != null)
{
/* Is there a form bean associated with this mapping? */
this.formName = config.getAttribute();
}
ModuleConfig mconfig = ModuleUtils.getInstance().getModuleConfig(request, app);
this.resources = (ValidatorResources)app.getAttribute(ValidatorPlugIn.
VALIDATOR_KEY +
mconfig.getPrefix());
}
/****************** get/set accessors ***************/
/**
* Gets the current page number of a multi-part form.
* Only field validations with a matching page number
* will be generated that match the current page number.
* Only valid when the formName attribute is set.
*
* @return the current page number of a multi-part form
*/
public int getPage()
{
return page;
}
/**
* Sets the current page number of a multi-part form.
* Only field validations with a matching page number
* will be generated that match the current page number.
*
* @param page the current page number of a multi-part form
*/
public void setPage(int page)
{
this.page = page;
}
/**
* Gets the method name that will be used for the Javascript
* validation method name if it has a value. This overrides
* the auto-generated method name based on the key (form name)
* passed in.
*
* @return the method name that will be used for the Javascript validation method
*/
public String getMethod()
{
return methodName;
}
/**
* Sets the method name that will be used for the Javascript
* validation method name if it has a value. This overrides
* the auto-generated method name based on the key (form name)
* passed in.
*
* @param methodName the method name that will be used for the Javascript validation method name
*/
public void setMethod(String methodName)
{
this.methodName = methodName;
}
/**
* Gets whether or not to delimit the
* JavaScript with html comments. If this is set to 'true', which
* is the default, html comments will surround the JavaScript.
*
* @return true if the JavaScript should be delimited with html comments
*/
public boolean getHtmlComment()
{
return this.htmlComment;
}
/**
* Sets whether or not to delimit the
* JavaScript with html comments. If this is set to 'true', which
* is the default, html comments will surround the JavaScript.
*
* @param htmlComment whether or not to delimit the JavaScript with html comments
*/
public void setHtmlComment(boolean htmlComment)
{
this.htmlComment = htmlComment;
}
/**
* Gets the src attribute's value when defining
* the html script element.
*
* @return the src attribute's value
*/
public String getSrc()
{
return src;
}
/**
* Sets the src attribute's value (used to include
* an external script resource) when defining
* the html script element. The src attribute is only recognized
* when the formName attribute is specified.
*
* @param src the src attribute's value
*/
public void setSrc(String src)
{
this.src = src;
}
/**
* Returns the cdata setting "true" or "false".
*
* @return boolean - "true" if JavaScript will be hidden in a CDATA section
*/
public boolean getCdata()
{
return cdata;
}
/**
* Sets the cdata status.
* @param cdata The cdata to set
*/
public void setCdata(boolean cdata)
{
this.cdata = cdata;
}
/****************** methods that aren't just accessors ***************/
/**
* Render both dynamic and static JavaScript to perform
* validations based on the form name attribute of the action
* mapping associated with the current request (if such exists).
*
* @return the javascript for the current form
* @throws Exception
*/
public String getJavascript() throws Exception
{
return getJavascript(this.formName);
}
/**
* Render both dynamic and static JavaScript to perform
* validations based on the supplied form name.
*
* @param formName the key (form name)
* @return the Javascript for the specified form
* @throws Exception
*/
public String getJavascript(String formName) throws Exception
{
this.formName = formName;
return getJavascript(formName, true);
}
/**
* Render just the dynamic JavaScript to perform validations based
* on the form name attribute of the action mapping associated
* with the current request (if such exists). Useful i.e. if the static
* parts are located in a seperate .js file.
*
* @return the javascript for the current form
* @throws Exception
*/
public String getDynamicJavascript() throws Exception
{
return getDynamicJavascript(this.formName);
}
/**
* Render just the static JavaScript methods. Useful i.e. if the static
* parts should be located in a seperate .js file.
*
* @return all static Javascript methods
* @throws Exception
*/
public String getStaticJavascript() throws Exception
{
StringBuffer results = new StringBuffer();
results.append(getStartElement());
if (this.htmlComment)
{
results.append(HTML_BEGIN_COMMENT);
}
results.append(getJavascriptStaticMethods(resources));
results.append(getJavascriptEnd());
return results.toString();
}
/**
* Render just the dynamic JavaScript to perform validations based
* on the supplied form name. Useful i.e. if the static
* parts are located in a seperate .js file.
*
* @param formName the key (form name)
* @return the dynamic Javascript for the specified form
* @throws Exception
*/
public String getDynamicJavascript(String formName) throws Exception
{
this.formName = formName;
return getJavascript(formName, false);
}
/**
* Render both dynamic and static JavaScript to perform
* validations based on the supplied form name.
*
* @param formName the key (form name)
* @param getStatic indicates if the static methods should be rendered
* @return the Javascript for the specified form
* @throws Exception
*/
protected String getJavascript(String formName, boolean getStatic) throws Exception
{
StringBuffer results = new StringBuffer();
Locale locale = StrutsUtils.getLocale(request, session);
Form form = resources.getForm(locale, formName);
if (form != null)
{
results.append(getDynamicJavascript(resources, locale, form));
}
if(getStatic)
{
results.append(getJavascriptStaticMethods(resources));
}
if (form != null)
{
results.append(getJavascriptEnd());
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -