parsetag.java

来自「jakarta-taglibs」· Java 代码 · 共 255 行

JAVA
255
字号
/*
 * Copyright 1999,2004 The Apache Software Foundation.
 * 
 * Licensed 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.taglibs.datetime;

import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

/**
 * JSP Tag <b>parse</b>, used to parse a Date string and output
 * the time in ms.
 * <p>
 * The Date as a string is obtained from the body of the tag.
 * <p>
 * Uses the optional attribute <b>pattern</b> as the pattern
 * to use when parsing the Date string.
 * <p>
 * The optional attribute <b>timeZone</b> can be set to the id of
 * a timeZone script varaible so that the Date if adjusted for
 * that timeZone.
 * <p>
 * If the optional attribute <b>locale</b> is true, the Date
 * is parsed for the clients locale if known.
 * <p>                                                        
 * The optional attribute <b>localeRef</b> can be used to specify
 * the name of a page, session, application, or request scope attribute
 * of type java.util.Locale to use.
 * <p>
 * If the date string can not be parsed, 0 is returned.
 * <p>
 * JSP Tag Lib Descriptor
 * <p><pre>
 * &lt;name&gt;parse&lt;/name&gt;
 * &lt;tagclass&gt;org.apache.taglibs.datetime.ParseTag&lt;/tagclass&gt;
 * &lt;bodycontent&gt;JSP&lt;/bodycontent&gt;
 * &lt;info&gt;Parses a date string and outputs the time in milliseconds since Jan 1, 1970 GMT.&lt;/info&gt;
 *   &lt;attribute&gt;
 *     &lt;name&gt;pattern&lt;/name&gt;
 *     &lt;required&gt;false&lt;/required&gt;
 *     &lt;rtexprvalue&gt;false&lt;/rtexprvalue&gt;
 *   &lt;/attribute&gt;
 *   &lt;attribute&gt;
 *     &lt;name&gt;patternId&lt;/name&gt;
 *     &lt;required&gt;false&lt;/required&gt;
 *     &lt;rtexprvalue&gt;false&lt;/rtexprvalue&gt;
 *   &lt;/attribute&gt;
 *   &lt;attribute&gt;
 *     &lt;name&gt;timeZone&lt;/name&gt;
 *     &lt;required&gt;false&lt;/required&gt;
 *     &lt;rtexprvalue&gt;false&lt;/rtexprvalue&gt;
 *   &lt;/attribute&gt;
 *   &lt;attribute&gt;
 *     &lt;name&gt;locale&lt;/name&gt;
 *     &lt;required&gt;false&lt;/required&gt;
 *     &lt;rtexprvalue&gt;false&lt;/rtexprvalue&gt;
 *   &lt;/attribute&gt;
 *   &lt;attribute&gt;                             
 *     &lt;name&gt;localeRef&lt;/name&gt;
 *     &lt;required&gt;false&lt;/required&gt;
 *     &lt;rtexprvalue&gt;false&lt;/rtexprvalue&gt;
 *   &lt;/attribute&gt;
 * </pre>
 *
 * @author Glenn Nielsen
 */

public class ParseTag extends BodyTagSupport
{
    // Optional attribute, use users locale if known when formatting date
    private boolean locale_flag = false;
    // Optional attribute, time pattern string to use when formatting date
    private String pattern = null;
    // Optional attribute, name of script variable to use as pattern
    private String patternid = null;
    // Optional attribute, timeZone script variable id to use when
    // formatting date
    private String timeZone_string;
    // Optional attribute, the name of an attribute which contains the Locale            
    private String localeRef = null;                                         
                                                                             
    // format tag invocation variables
    private TimeZone timeZone = null;
    // Date after parsing tag body
    private Date date = null;

    /**
     * Method called at start of tag, always returns EVAL_BODY_TAG
     *
     * @return EVAL_BODY_TAG
     */
    public final int doStartTag() throws JspException
    {
	return EVAL_BODY_TAG;
    }

    /**
     * Method called at end of parse tag body.
     *
     * @return SKIP_BODY
     */
    public final int doAfterBody() throws JspException
    {
	// Use the body of the tag as input for the date
	BodyContent body = getBodyContent();
	String s = body.getString().trim();  
	// Clear the body since we will output only the parseted date
	body.clearBody();

        // Get the pattern to use
        SimpleDateFormat sdf;    
        String pat = pattern; 
 
        if( pat == null && patternid != null ) {
          Object attr = pageContext.findAttribute(patternid);
          if( attr != null )    
            pat = attr.toString();
        }
        
        if( pat == null ) {
            sdf = new SimpleDateFormat(); 
            pat = sdf.toPattern();
        }

	// Get a SimpleDateFormat using locale if necessary
        if( localeRef != null ) {                          
            Locale locale = (Locale)pageContext.findAttribute(localeRef);
            if( locale == null ) {                                       
                throw new JspException(                                  
                    "datetime parse tag could not find locale for localeRef \"" +
                    localeRef + "\".");                                           
            }                                                                     
                                       
            sdf = new SimpleDateFormat(pat,locale);
        } else if( locale_flag ) {                 
            sdf = new SimpleDateFormat(pat,        
                      (Locale)pageContext.getRequest().getLocale());
        } else {                                                    
            sdf = new SimpleDateFormat(pat);                        
        }

	// See if there is a timeZone
        if( timeZone_string != null ) {
            timeZone =
                (TimeZone)pageContext.getAttribute(timeZone_string,
                                                   PageContext.SESSION_SCOPE);
	    if( timeZone == null )
                throw new JspTagException("Datetime parse tag timeZone " +
                    "script variable \"" + timeZone_string +
                    " \" does not exist");
            sdf.setTimeZone(timeZone);
        }

	// Parse the string and create the date.
	try {
            date = null;
	    date = sdf.parse(s);
	} catch(ParseException e) {
	}
	return SKIP_BODY;
    }

    /**
     * Method called at end of Tag
     *
     * @return EVAL_PAGE
     */
    public final int doEndTag() throws JspException
    {
	long time = 0;
	if( date != null )
	    time = date.getTime();
	try {
	    pageContext.getOut().write("" + time);
	} catch(Exception e) {
	    throw new JspException("IO Error: " + e.getMessage());
	}

	return EVAL_PAGE;
    }

    /**
     * Locale flag, if set to true, date format is for
     * client's preferred locale if known.
     *
     * @param boolean use users locale, true or false
     */
    public final void setLocale(boolean flag)
    {
        locale_flag = flag;
    }
 
    /**
     * Set the time zone to use when parsing date.
     *
     * Value must be the name of a <b>timeZone</b> tag script
     * variable ID.
     *
     * @param String name of timeZone to use
     */
    public final void setTimeZone(String tz)
    { 
        timeZone_string = tz;
    } 
 
    /**   
     * Set the pattern to use when parsing Date.
     *
     * @param String SimpleDateFormat style time pattern format string
     */
    public final void setPattern(String str)
    { 
        pattern = str;
    }

    /**
     * Set the pattern to use when parsing Date using a script variable
     * attribute.
     *
     * @param String name of script variable attribute id
     */
    public final void setPatternId(String str)
    {
        patternid = str;
    }

    /**
     * Provides a key to search the page context for in order to get the
     * java.util.Locale to use.
     *
     * @param String name of locale attribute to use
     */
    public void setLocaleRef(String value)
    {
        localeRef = value;
    }

}

⌨️ 快捷键说明

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