⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tagutils.java

📁 structs源码
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/*
 * $Id: TagUtils.java 471754 2006-11-06 14:55:09Z husted $
 *
 * 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.
 */
package org.apache.struts.taglib;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.config.ForwardConfig;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.taglib.html.Constants;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.ModuleUtils;
import org.apache.struts.util.RequestUtils;
import org.apache.struts.util.ResponseUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyContent;

import java.io.IOException;

import java.lang.reflect.InvocationTargetException;

import java.net.MalformedURLException;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

/**
 * Provides helper methods for JSP tags.
 *
 * @version $Rev: 471754 $
 * @since Struts 1.2
 */
public class TagUtils {
    /**
     * The Singleton instance.
     * @since 1.3.5 Changed to non-final so it may be overridden, use at your own risk (you've been warned!!)
     */
    private static TagUtils instance = new TagUtils();

    /**
     * Commons logging instance.
     */
    private static final Log log = LogFactory.getLog(TagUtils.class);

    /**
     * The message resources for this package. TODO We need to move the
     * relevant messages out of this properties file.
     */
    private static final MessageResources messages =
        MessageResources.getMessageResources(
            "org.apache.struts.taglib.LocalStrings");

    /**
     * Maps lowercase JSP scope names to their PageContext integer constant
     * values.
     */
    private static final Map scopes = new HashMap();

    /**
     * Initialize the scope names map and the encode variable with the
     * Java 1.4 method if available.
     */
    static {
        scopes.put("page", new Integer(PageContext.PAGE_SCOPE));
        scopes.put("request", new Integer(PageContext.REQUEST_SCOPE));
        scopes.put("session", new Integer(PageContext.SESSION_SCOPE));
        scopes.put("application", new Integer(PageContext.APPLICATION_SCOPE));
    }

    /**
     * Constructor for TagUtils.
     */
    protected TagUtils() {
        super();
    }

    /**
     * Returns the Singleton instance of TagUtils.
     */
    public static TagUtils getInstance() {
        return instance;
    }

    /**
     * Set the instance.
     * This blatently violates the Singleton pattern, but then some say Singletons are an anti-pattern.
     * @since 1.3.5 Changed to non-final and added setInstance() so TagUtils may be overridden, use at your own risk (you've been warned!!)
     * @param instance The instance to set.
     */
    public static void setInstance(TagUtils instance){
      TagUtils.instance = instance;
    }

    /**
     * Compute a set of query parameters that will be dynamically added to a
     * generated URL.  The returned Map is keyed by parameter name, and the
     * values are either null (no value specified), a String (single value
     * specified), or a String[] array (multiple values specified).  Parameter
     * names correspond to the corresponding attributes of the
     * <code>&lt;html:link&gt;</code> tag.  If no query parameters are
     * identified, return <code>null</code>.
     *
     * @param pageContext   PageContext we are operating in
     * @param paramId       Single-value request parameter name (if any)
     * @param paramName     Bean containing single-value parameter value
     * @param paramProperty Property (of bean named by <code>paramName</code>
     *                      containing single-value parameter value
     * @param paramScope    Scope containing bean named by <code>paramName</code>
     * @param name          Bean containing multi-value parameters Map (if
     *                      any)
     * @param property      Property (of bean named by <code>name</code>
     *                      containing multi-value parameters Map
     * @param scope         Scope containing bean named by <code>name</code>
     * @param transaction   Should we add our transaction control token?
     * @return Map of query parameters
     * @throws JspException if we cannot look up the required beans
     * @throws JspException if a class cast exception occurs on a looked-up
     *                      bean or property
     */
    public Map computeParameters(PageContext pageContext, String paramId,
        String paramName, String paramProperty, String paramScope, String name,
        String property, String scope, boolean transaction)
        throws JspException {
        // Short circuit if no parameters are specified
        if ((paramId == null) && (name == null) && !transaction) {
            return (null);
        }

        // Locate the Map containing our multi-value parameters map
        Map map = null;

        try {
            if (name != null) {
                map = (Map) getInstance().lookup(pageContext, name, property,
                        scope);
            }

            // @TODO - remove this - it is never thrown
            //        } catch (ClassCastException e) {
            //            saveException(pageContext, e);
            //            throw new JspException(
            //                    messages.getMessage("parameters.multi", name, property, scope));
        } catch (JspException e) {
            saveException(pageContext, e);
            throw e;
        }

        // Create a Map to contain our results from the multi-value parameters
        Map results = null;

        if (map != null) {
            results = new HashMap(map);
        } else {
            results = new HashMap();
        }

        // Add the single-value parameter (if any)
        if ((paramId != null) && (paramName != null)) {
            Object paramValue = null;

            try {
                paramValue =
                    TagUtils.getInstance().lookup(pageContext, paramName,
                        paramProperty, paramScope);
            } catch (JspException e) {
                saveException(pageContext, e);
                throw e;
            }

            if (paramValue != null) {
                String paramString = null;

                if (paramValue instanceof String) {
                    paramString = (String) paramValue;
                } else {
                    paramString = paramValue.toString();
                }

                Object mapValue = results.get(paramId);

                if (mapValue == null) {
                    results.put(paramId, paramString);
                } else if (mapValue instanceof String[]) {
                    String[] oldValues = (String[]) mapValue;
                    String[] newValues = new String[oldValues.length + 1];

                    System.arraycopy(oldValues, 0, newValues, 0,
                        oldValues.length);
                    newValues[oldValues.length] = paramString;
                    results.put(paramId, newValues);
                } else {
                    String[] newValues = new String[2];

                    newValues[0] = mapValue.toString();
                    newValues[1] = paramString;
                    results.put(paramId, newValues);
                }
            }
        }

        // Add our transaction control token (if requested)
        if (transaction) {
            HttpSession session = pageContext.getSession();
            String token = null;

            if (session != null) {
                token =
                    (String) session.getAttribute(Globals.TRANSACTION_TOKEN_KEY);
            }

            if (token != null) {
                results.put(Constants.TOKEN_KEY, token);
            }
        }

        // Return the completed Map
        return (results);
    }

    public String computeURL(PageContext pageContext, String forward,
        String href, String page, String action, String module, Map params,
        String anchor, boolean redirect)
        throws MalformedURLException {
        return this.computeURLWithCharEncoding(pageContext, forward, href,
            page, action, module, params, anchor, redirect, false);
    }

    /**
     * Compute a hyperlink URL based on the <code>forward</code>,
     * <code>href</code>, <code>action</code> or <code>page</code> parameter
     * that is not null. The returned URL will have already been passed to
     * <code>response.encodeURL()</code> for adding a session identifier.
     *
     * @param pageContext PageContext for the tag making this call
     * @param forward     Logical forward name for which to look up the
     *                    context-relative URI (if specified)
     * @param href        URL to be utilized unmodified (if specified)
     * @param page        Module-relative page for which a URL should be
     *                    created (if specified)
     * @param action      Logical action name for which to look up the
     *                    context-relative URI (if specified)
     * @param params      Map of parameters to be dynamically included (if
     *                    any)
     * @param anchor      Anchor to be dynamically included (if any)
     * @param redirect    Is this URL for a <code>response.sendRedirect()</code>?
     * @return URL with session identifier
     * @throws java.net.MalformedURLException if a URL cannot be created for
     *                                        the specified parameters
     */
    public String computeURLWithCharEncoding(PageContext pageContext,
        String forward, String href, String page, String action, String module,
        Map params, String anchor, boolean redirect, boolean useLocalEncoding)
        throws MalformedURLException {
        return computeURLWithCharEncoding(pageContext, forward, href, page,
            action, module, params, anchor, redirect, true, useLocalEncoding);
    }

    public String computeURL(PageContext pageContext, String forward,
        String href, String page, String action, String module, Map params,
        String anchor, boolean redirect, boolean encodeSeparator)
        throws MalformedURLException {
        return computeURLWithCharEncoding(pageContext, forward, href, page,
            action, module, params, anchor, redirect, encodeSeparator, false);
    }

    /**
     * Compute a hyperlink URL based on the <code>forward</code>,
     * <code>href</code>, <code>action</code> or <code>page</code> parameter
     * that is not null. The returned URL will have already been passed to
     * <code>response.encodeURL()</code> for adding a session identifier.
     *
     * @param pageContext      PageContext for the tag making this call
     * @param forward          Logical forward name for which to look up the
     *                         context-relative URI (if specified)
     * @param href             URL to be utilized unmodified (if specified)
     * @param page             Module-relative page for which a URL should be
     *                         created (if specified)
     * @param action           Logical action name for which to look up the
     *                         context-relative URI (if specified)
     * @param params           Map of parameters to be dynamically included
     *                         (if any)
     * @param anchor           Anchor to be dynamically included (if any)
     * @param redirect         Is this URL for a <code>response.sendRedirect()</code>?
     * @param encodeSeparator  This is only checked if redirect is set to
     *                         false (never encoded for a redirect).  If true,
     *                         query string parameter separators are encoded
     *                         as &gt;amp;, else &amp; is used.
     * @param useLocalEncoding If set to true, urlencoding is done on the
     *                         bytes of character encoding from
     *                         ServletResponse#getCharacterEncoding. Use UTF-8
     *                         otherwise.
     * @return URL with session identifier
     * @throws java.net.MalformedURLException if a URL cannot be created for
     *                                        the specified parameters
     */
    public String computeURLWithCharEncoding(PageContext pageContext,
        String forward, String href, String page, String action, String module,
        Map params, String anchor, boolean redirect, boolean encodeSeparator,
        boolean useLocalEncoding)
        throws MalformedURLException {
        String charEncoding = "UTF-8";

        if (useLocalEncoding) {
            charEncoding = pageContext.getResponse().getCharacterEncoding();
        }

        // TODO All the computeURL() methods need refactoring!
        // Validate that exactly one specifier was included
        int n = 0;

        if (forward != null) {
            n++;
        }

        if (href != null) {
            n++;
        }

        if (page != null) {
            n++;
        }

        if (action != null) {
            n++;
        }

        if (n != 1) {
            throw new MalformedURLException(messages.getMessage(
                    "computeURL.specifier"));
        }

        // Look up the module configuration for this request
        ModuleConfig moduleConfig = getModuleConfig(module, pageContext);

        // Calculate the appropriate URL
        StringBuffer url = new StringBuffer();
        HttpServletRequest request =
            (HttpServletRequest) pageContext.getRequest();

        if (forward != null) {
            ForwardConfig forwardConfig =
                moduleConfig.findForwardConfig(forward);

            if (forwardConfig == null) {
                throw new MalformedURLException(messages.getMessage(
                        "computeURL.forward", forward));
            }

            // **** removed - see bug 37817 ****
            //  if (forwardConfig.getRedirect()) {
            //      redirect = true;
            //  }

            if (forwardConfig.getPath().startsWith("/")) {
                url.append(request.getContextPath());
                url.append(RequestUtils.forwardURL(request, forwardConfig,
                        moduleConfig));
            } else {
                url.append(forwardConfig.getPath());
            }
        } else if (href != null) {
            url.append(href);
        } else if (action != null) {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -