JSP custom tag displays the date

2011-01-02  来源:本站原创  分类:Java  人气:160 

Brother Fucai, recently made a date displayed on the JSP custom tags, the specific function: to customize the display start and end time, you can pass initialization parameters, the file can be a display of a load.

Specific documentation as follows:

SelectDateTag  Help  :
      Features  :  The date of custom tags to fill the drop-down list, including three drop-down list  , Years, respectively on, you can customize the drop-down list to set the start and end times  .
      Use  :  Copy com.sjdd.tag package under  BaseTag.class  And SelectDateTag.class, will  WEB-INF/taglib  Under
SelectDateTag.tld  Stored in the same directory you need to configure the project  .
      The need to add the custom tag by adding the following code in JSP file  :
    "
        <%@ taglib uri="/tagslib/SelectDate" prefix="SelectDate" %>
        <SelectDate:SelectDate name="begin" begin="20000101" end="20201231" init="20101231"/>
    "
      Parameter Description  :"name"  Part of the drop-down list to use the name and  id(  Optional  ),  Specific shape, such as "begin_year", "begin_month", "begin_day", the default is  "_year","_month","_day":
                  "begin"  Start time for the drop-down list  (  Optional  ),  If you do not configure "init" for the default time  ,  The default is  "19900101":
              "end"  End time for the drop-down list  (  Optional  ),  The default is  "20201231":
              "init"  The initialization time  (  Optional  ),  The default is the current date  .
      See Example  :WebRoot/testSelectDate.jsp

      Another  :  If you need to add more components, you need to set different  name  Properties  .

This is the parent tag for the output:

package com.sjdd.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
/**
 *
 * @Description:  Basic tab
 * @author:bao
 * @date:Dec 19, 2010
 */
public class BaseTag extends TagSupport {

        private static final long serialVersionUID = 1L;

        public int outPrint(StringBuffer content) throws JspException {

                if(content==null){
                        return EVAL_PAGE;
                }

                try {
                        this.pageContext.getOut().write(content.toString());
                } catch (Exception e) {
                        e.printStackTrace();
                        throw new JspException();
                }

                return EVAL_PAGE;
        }
}

This is the deal with the main label categories:

package com.sjdd.tag;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspException;

import com.sjdd.tag.datebean.DateHandler;
import com.sjdd.tag.datebean.Option;

public class SelectDateTag extends BaseTag {

        private static final long serialVersionUID = 1L;

        //   Drop-down list the name of the form  "begin_year","_year"
        private String name;
        //   Start Date
        private int begin = 19900101;
        //   End Date
        private int end = 20201231;
        //   Initialization date, the default is the current date
        private int init;

        public String getName() {
                if(this.name==null){
                        name="";
                }
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }

        public int getBegin() {
                return begin;
        }

        public void setBegin(int begin) {
                int initBegin = DateHandler.varifyAsInit(begin, 19900101);
                this.begin = initBegin;
        }

        public int getEnd() {
                return end;
        }

        public void setEnd(int end) {
                int initEnd = DateHandler.varifyAsInit(end, 20201231);
                this.end = initEnd;
        }

        public int getInit() {
                if(init==0){
                        init = DateHandler.getCurrentShortDate();
                }
                return init;
        }

        public void setInit(int init) {
                int initial = DateHandler.varifyAsInit(init, DateHandler.getCurrentShortDate());
                this.init = initial;
        }

        /**
         * @Description:  Create drop-down list on
         * @return List<Option>
         */
        public List<Option> buildYearOptions() {
                List<Integer> yearList = new ArrayList<Integer>();

                int beginYear = DateHandler.getYear(begin);
                int endYear = DateHandler.getYear(end);

                for (int i = beginYear; i <= endYear; i++) {
                        yearList.add(i);
                }

                return Option.buildOptions(yearList);
        }

        public List<Option> buildMonthOptions() {
                List<Integer> monthList = new ArrayList<Integer>();

                for (int i = 1; i <= 12; i++) {
                        monthList.add(i);
                }

                return Option.buildOptions(monthList);
        }

        public List<Option> buildDayOptions(int year, int month) {
                List<Integer> yearList = new ArrayList<Integer>();
                int maxDay = DateHandler.getMaxDayValue(year, month);

                for (int i = 1; i <= maxDay; i++) {
                        yearList.add(i);
                }

                return Option.buildOptions(yearList);
        }

        @Override
        public int doEndTag() throws JspException {

                int yearValue = 2010;
                int monthValue = 1;

                StringBuffer content = new StringBuffer();
                content.append("<select name=\"").append(getName()).append("_year\"\"").append(name).append(
                                "_year\"\"select\" onchange='"+getName()+"changeDay();'>\n");
                for (Option year : buildYearOptions()) {
                        content.append("    <option value=\"").append(year.getValue()).append("\"");
                        if (DateHandler.getYear(getInit()) == year.getValue()) {

                                content.append(" selected=\"selected\"");
                                yearValue = year.getValue();
                        }
                        content.append(">").append(year.getLabel()).append("</option>\n");
                }
                content.append("</select>\n");

                content.append("<select name=\"").append(getName()).append("_month\"\"").append(name)
                                .append("_month\"\"select\" onchange='"+getName()+"changeDay();'>\n");
                for (Option month : buildMonthOptions()) {
                        content.append("    <option value=\"").append(month.getValue()).append("\"");
                        if (DateHandler.getMonth(getInit()) == month.getValue()) {
                                content.append(" selected=\"selected\"");
                                monthValue = month.getValue();
                        }
                        content.append(">").append(month.getLabel()).append("</option>\n");
                }
                content.append("</select>\n");

                content.append("<select name=\"").append(getName()).append("_day\"\"").append(name).append(
                                "_day\"\"select\">\n");
                for (Option day : buildDayOptions(yearValue, monthValue)) {
                        content.append("    <option value=\"").append(day.getValue()).append("\"");
                        if (DateHandler.getDay(getInit()) == day.getValue()) {
                                content.append(" selected=\"selected\"");
                        }
                        content.append(">").append(day.getLabel()).append("</option>\n");
                }
                content.append("</select>\n");

                content.append("<script type=\"text/javascript\">\n");
                content.append("    function "+getName()+"changeDay() {\n");
                content.append("        var year = document.getElementById(\"" + getName() + "_year\").value;\n");
                content.append("        var month = document.getElementById(\"" + getName() + "_month\").value;\n");
                content.append("        var dayObj = document.getElementById(\"" + getName() + "_day\");\n");
                content.append("        fillDayOptions(dayObj,getMaxDayInMonth(year,month));\n");
                content.append("    }\n");

                content.append("    function getMaxDayInMonth(year, month) {\n");
                content.append("        var month = parseInt(month, 10) + 1;\n");
                content.append("        var d = new Date(year + '/' + month + '/' + 0);\n");
                content.append("        return d.getDate();\n");
                content.append("    }\n");

                content.append("    function fillDayOptions(obj, maxDay) {\n");
                content.append("        obj.innerHTML = '';\n");
                content.append("        for (i = 1; i <= maxDay; i++) {\n");
                content.append("            var varItem = new Option(i, i);\n");
                content.append("            obj.options.add(varItem);\n");
                content.append("        }\n");
                content.append("    }\n");
                content.append("</script>\n");

                return this.outPrint(content);
        }

}

Also includes two entities bean:

package com.sjdd.tag.datebean;

import java.util.Calendar;

/**
 * @Description:  Date handling classes
 * @author:bao
 * @date:Jan 1, 2011
 */
public class DateHandler {

        private int year;
        private int month;
        private int day;

        public int getYear() {
                return year;
        }

        public void setYear(int year) {
                this.year = year;
        }

        public int getMonth() {
                return month;
        }

        public void setMonth(int month) {
                this.month = month;
        }

        public int getDay() {
                return day;
        }

        public void setDay(int day) {
                this.day = day;
        }

        public DateHandler() {
                super();
        }

        /**
         * @Description:  Get the biggest days in mid-parameter values
         * @param year
         * @param month
         * @return int
         */
        public static int getMaxDayValue(int year, int month) {
                Calendar time = Calendar.getInstance();
                time.clear();
                time.set(Calendar.YEAR, year); // year   As  int
                time.set(Calendar.MONTH, month - 1);//   Note, Calendar, January is the default object  0
                int max = time.getActualMaximum(Calendar.DAY_OF_MONTH);//   The number of days this month  

                return max;
        }

        /**
         * @Description:  Get the current date, and is converted to the form  "20101231"  Integer format
         * @return int
         */
        public static int getCurrentShortDate() {
                Calendar cal = Calendar.getInstance();
                int date = cal.get(Calendar.YEAR) * 10000 + (cal.get(Calendar.MONTH) + 1) * 100
                                + cal.get(Calendar.DAY_OF_MONTH);
                return date;
        }

        /**
         * @Description:  Verify whether the date of the form  "20100101"  Format, the return date format best meets the requirements of
         * @param date
         * @return int
         */
        public static int varifyAsInit(int date, int defaultValue) {

                String dateStr = Integer.toString(date);

                //   If the input number is not 8-bit  ,  The default number is used
                if (dateStr.length() != 8) {
                        return defaultValue;
                }

                //  Back to the closest date
                return getYear(date) * 10000 + getMonth(date) * 100 + getDay(date);
        }

        /**
         * @Description:  The number of days to obtain legal
         * @param date
         * @return int
         */
        public static int getDay(int date) {
                int day = date % 100;
                int maxDay = getMaxDayValue(getYear(date), getMonth(date));

                if (day > maxDay) {
                        day = maxDay;
                }

                return day;
        }

        /**
         * @Description:  The number of months to get legal
         * @param date
         * @return int
         */
        public static int getMonth(int date) {
                int month = date / 100 % 100;

                if (month > 12) {
                        month = 12;
                } else if (month < 1) {
                        month = 1;
                }

                return month;
        }

        /**
         * @Description:  The number of years to get legal
         * @param date
         * @return int
         */
        public static int getYear(int date) {
                return date / 10000;
        }
}
package com.sjdd.tag.datebean;

import java.util.ArrayList;
import java.util.List;
/**
 * @Description:  Save drop-down list the value of each value and display
 * @author:bao
 * @date:Jan 1, 2011
 */
public class Option {

        private String label;
        private int value;

        public String getLabel() {
                return label;
        }

        public void setLabel(String label) {
                this.label = label;
        }

        public int getValue() {
                return value;
        }

        public void setValue(int value) {
                this.value = value;
        }

        public Option(String label, int value) {
                super();
                this.label = label;
                this.value = value;
        }

        public static List<Option> buildOptions(List<Integer> options){
                List<Option> buildList = new ArrayList<Option>();

                for(int option:options){
                        buildList.add(new Option(Integer.toString(option),option));
                }

                return buildList;
        }

}

Here tld file:

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">

        <tlib-version>1.0</tlib-version>
        <short-name>SelectDate</short-name>
        <uri>/tagslib/SelectDate</uri>

        <tag>
                <name>SelectDate</name>
                <tag-class>com.sjdd.tag.SelectDateTag</tag-class>
                <body-content>empty</body-content>
                <attribute>
                        <name>name</name>
                        <required>false</required>
                </attribute>
                <attribute>
                        <name>begin</name>
                        <required>false</required>
                </attribute>
                <attribute>
                        <name>end</name>
                        <required>false</required>
                </attribute>
                <attribute>
                        <name>init</name>
                        <required>false</required>
                </attribute>
        </tag>
</taglib>

This is a test file:

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="/tagslib/SelectDate" prefix="SelectDate" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'testSelectDate.jsp' starting page</title>

        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->

  </head>

  <body>
    This is my JSP page. <br>
      Start Time  :<SelectDate:SelectDate name="begin" begin="20001010" end="21251231" init="20100102"/><br>
      Start Time  :<SelectDate:SelectDate/><br>
</body>
</html>

The function of the bottom cabinet, and if my colleagues found that where there are problems, leave a message, look forward to your progress together.

相关文章
  • JSP custom tag displays the date 2011-01-02

    Brother Fucai, recently made a date displayed on the JSP custom tags, the specific function: to customize the display start and end time, you can pass initialization parameters, the file can be a display of a load. Specific documentation as follows:

  • JSP custom tag - no body of the JSP custom tag implementation 2010-01-19

    package cn.com.chenlly.tag; import java.io.IOException; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.Tag; import javax.

  • jsp custom tag development 2010-03-29

    Tag handler Before you create a custom label, need to create a tag handler. Tag handler is an implementation of the custom label operated Java objects. When using a custom tag to import a tag library - that is, a set of labels / Tag handler right. Th

  • jsp custom tag taglib TagSupport & BodyTagSupport 2010-03-20

    jsp custom tag: http://www.blogjava.net/limq/archive/2005/03/03/1669.html jsp custom tag (taglib) prepared by the principle and the realization http://www.blogjava.net/gdufo/archive/2008/09/04/226974.html or: http://www.javaeye.com/topic/157737 TagSu

  • JSP custom tag (transfer) 2010-04-19

    1, JSP custom tag Description tag is an XML element, the tag can get simple JSP pages and easy to maintain, you can easily achieve the same JSP file to support multiple languages. As the label is the XML element, its name and attributes are case-sens

  • JSP custom tag Infinitus (data from the database) drop-down linkage 2010-05-03

    Description: The project's environmental needs: JSP Custom Tags, dwr, this case provides several examples of practical applications, including automatically selected when such changes. First look at the configuration of web.xml: 1 <?xml version="1

  • jsp custom tag library 2010-10-03

    1. Why should I use a custom label? Mainly to replace the ugly JSP script. Inserted in the HTML page has the following disadvantages of JSP scripts: JSP script is ugly, difficult to read. JSP scripts and HTML code for mixed and high maintenance costs

  • jsp custom tag self-notes (a) 2010-10-28

    jsp custom tag library has a better code reusability, and can make the entire page is simple and beautiful. Very convenient to use. Here's hands to implement a simple "hello world" label. 1, implement a custom tag can inherit javax.servlet.jsp.t

  • JSP custom tag - simple labels more 2010-12-09

    Simple labels more SimpleTag is: JSP 2.0 adds a new creation of self-labeled API javax.servlet.jsp.tagext.SimpleTag, the API defines the interface used to implement simple tag. SimpleTag advantages: (1) provides a simple doTag () method. This method

  • jsp custom tag development and application of 2010-03-29

    1, without labeling the body custom tag to write a class inherits from the class with properties TagSupport custom tag to be prepared for the property setter / getter methods. Override doStartTag () method doStartTag () return value is usually SKIP_B

  • JSP custom tag - no body but with the properties of JSP custom tag tag implementation 2009-06-09

    package cn.com.chenlly.tag; import java.io.IOException; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.Tag; import javax.

  • JSP custom tag instance 2010-03-27

    Definition: a custom tag is a very good component technology. By using a custom tag library, you can label the package in a simple complex Function; To understand: it will JSP page (complex, repetitive and uniform format) content package, instead of

  • JSP custom tag learning (basic) 2010-04-01

    The largest custom tag features: Using custom tags, software developers and page designers can work freely and independently. Page designers can focus on the use of tags (HTML, XML, or JSP) to create the site, and software developers can focus on ach

  • JSP custom tag basic Buju 2010-07-19

    In the "simple examples", we create a custom label demonstrates the complete process, this article will explain some explanation of this process, so that readers can create your own custom label to understand the basic process. Custom label is a

  • jsp custom tag entry 2010-07-20

    A tag is a normal java class, it is the only special feature is that it must carry TagSupport or BodyTagSupport class. These two classes provide a number of ways, for jsp pages and you write the interaction between classes, such as input and output.

  • jsp custom tag self notes (b) 2010-10-28

    Learned on a back custom tag library is written. But the "hello world" level of label is far from satisfying the curiosity of our Rulangsihu. This time, write the name of the input box with. (Knowledge is like beautiful women, brave flutter in t

  • JSP custom tag development process 2010-10-31

    I. Overview jsp (SUN enterprise application of choice) have an important technology: custom tag (Custom Tag), the last few days, Struts, it was found in the study used a lot of Struts custom tags, such as html, bean and so on. So I made a simple test

  • JSP custom tag implementation of the order 2010-10-31

    First, look at a simple tag interface method and its life cycle a, SimpleTag interface methods 1, doTag (): void 2, getParent (): JspTag 3, setJspBody (javax.servlet.jsp.tagext.JspFragment body): void 4, setJspContext (javax.servlet.jsp.JspContext pc

  • HF servelt & jsp custom tag development points summary 2010-11-13

    1. Markup files used to implement tagging a page, and mark the processor to use a java tag handler class to implement tagging. 2. Markup processor, there are two types: traditional and simple (in jsp 2.0). 3. To create a simple tag handler, you can e

  • JSP custom tag + dwr3.0 very drop in infinite linkage 2010-04-22

    In the regular development tasks, the drop-down linkage is also common thing, but before this thing is impossible to write to write to GM, and now with this custom tag, and this had become generic. First talk about the realization of the function of