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

📄 tabletag.java

📁 一个比较不错的java分页标签,有源代码,开发者 可以学习学习
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
        {
            // first time initialization
            rhf = this.properties.getRequestHelperFactoryInstance();
        }

        String fullName = getFullObjectName();

        // only evaluate if needed, else use list attribute
        if (fullName != null)
        {
            this.list = evaluateExpression(fullName);
        }
        else if (this.list == null)
        {
            // needed to allow removing the collection of objects if not set directly
            this.list = this.listAttribute;
        }

        if (this.list instanceof PaginatedList)
        {
            this.paginatedList = (PaginatedList) this.list;
            this.list = this.paginatedList.getList();
        }

        // set the table model to perform in memory local sorting
        this.tableModel.setLocalSort(this.localSort && (this.paginatedList == null));

        RequestHelper requestHelper = rhf.getRequestHelperInstance(this.pageContext);

        initHref(requestHelper);

        Integer pageNumberParameter = requestHelper.getIntParameter(encodeParameter(TableTagParameters.PARAMETER_PAGE));
        this.pageNumber = (pageNumberParameter == null) ? 1 : pageNumberParameter.intValue();

        int sortColumn = -1;
        if (!this.tableModel.isLocalSort())
        {
            // our sort column parameter may be a string, check that first
            String sortColumnName = requestHelper.getParameter(encodeParameter(TableTagParameters.PARAMETER_SORT));

            // if usename is not null, sortColumnName is the name, if not is the column index
            String usename = requestHelper.getParameter(encodeParameter(TableTagParameters.PARAMETER_SORTUSINGNAME));

            if (sortColumnName == null)
            {
                this.tableModel.setSortedColumnNumber(this.defaultSortedColumn);
            }
            else
            {
                if (usename != null)
                {

                    this.tableModel.setSortedColumnName(sortColumnName); // its a string, set as string
                }
                else if (NumberUtils.isNumber(sortColumnName))
                {
                    sortColumn = Integer.parseInt(sortColumnName);
                    this.tableModel.setSortedColumnNumber(sortColumn); // its an int set as normal
                }
            }
        }
        else if (this.paginatedList == null)
        {
            Integer sortColumnParameter = requestHelper
                .getIntParameter(encodeParameter(TableTagParameters.PARAMETER_SORT));
            sortColumn = (sortColumnParameter == null) ? this.defaultSortedColumn : sortColumnParameter.intValue();
            this.tableModel.setSortedColumnNumber(sortColumn);
        }
        else
        {
            sortColumn = defaultSortedColumn;
        }

        // default value
        boolean finalSortFull = this.properties.getSortFullList();

        // user value for this single table
        if (this.sortFullTable != null)
        {
            finalSortFull = this.sortFullTable.booleanValue();
        }

        // if a partial list is used and sort="list" is specified, assume the partial list is already sorted
        if (!this.partialList || !finalSortFull)
        {
            this.tableModel.setSortFullTable(finalSortFull);
        }

        if (this.paginatedList == null)
        {
            SortOrderEnum paramOrder = SortOrderEnum.fromCode(requestHelper
                .getIntParameter(encodeParameter(TableTagParameters.PARAMETER_ORDER)));

            // if no order parameter is set use default
            if (paramOrder == null)
            {
                paramOrder = this.defaultSortOrder;
            }

            boolean order = SortOrderEnum.DESCENDING != paramOrder;
            this.tableModel.setSortOrderAscending(order);
        }
        else
        {
            SortOrderEnum direction = paginatedList.getSortDirection();
            this.tableModel.setSortOrderAscending(direction == SortOrderEnum.ASCENDING);
        }

        Integer exportTypeParameter = requestHelper
            .getIntParameter(encodeParameter(TableTagParameters.PARAMETER_EXPORTTYPE));

        this.currentMediaType = (MediaTypeEnum) ObjectUtils.defaultIfNull(
            MediaTypeEnum.fromCode(exportTypeParameter),
            MediaTypeEnum.HTML);

        // if we are doing partialLists then ensure we have our size object
        if (this.partialList)
        {
            if ((this.sizeObjectName == null) && (this.size == null))
            {
                // ?
            }
            if (this.sizeObjectName != null)
            {
                // retrieve the object from scope
                this.size = evaluateExpression(this.sizeObjectName);
            }
            if (size == null)
            {
                throw new JspTagException(Messages.getString("MissingAttributeException.msg", new Object[]{"size"}));
            }
            else if (!(size instanceof Integer))
            {
                throw new JspTagException(Messages.getString(
                    "InvalidTypeException.msg",
                    new Object[]{"size", "Integer"}));
            }
        }

        // do we really need to skip any row?
        boolean wishOptimizedIteration = ((this.pagesize > 0 // we are paging
            || this.offset > 0 // or we are skipping some records using offset
        || this.length > 0 // or we are limiting the records using length
        ) && !partialList); // only optimize if we have the full list

        // can we actually skip any row?
        if (wishOptimizedIteration && (this.list instanceof Collection) // we need to know the size
            && ((sortColumn == -1 // and we are not sorting
            || !finalSortFull // or we are sorting with the "page" behaviour
            ) && (this.currentMediaType == MediaTypeEnum.HTML // and we are not exporting
            || !this.properties.getExportFullList()) // or we are exporting a single page
            ))
        {
            int start = 0;
            int end = 0;
            if (this.offset > 0)
            {
                start = this.offset;
            }
            if (length > 0)
            {
                end = start + this.length;
            }

            if (this.pagesize > 0)
            {
                int fullSize = ((Collection) this.list).size();
                start = (this.pageNumber - 1) * this.pagesize;

                // invalid page requested, go back to last page
                if (start > fullSize)
                {
                    int div = fullSize / this.pagesize;
                    start = (fullSize % this.pagesize == 0) ? div : div + 1;
                }

                end = start + this.pagesize;
            }

            // rowNumber starts from 1
            filteredRows = new LongRange(start + 1, end);
        }
        else
        {
            filteredRows = new LongRange(1, Long.MAX_VALUE);
        }

        this.tableIterator = IteratorUtils.getIterator(this.list);
    }

    /**
     * Is the current row included in the "to-be-evaluated" range? Called by nested ColumnTags. If <code>false</code>
     * column body is skipped.
     * @return <code>true</code> if the current row must be evaluated because is included in output or because is
     * included in sorting.
     */
    protected boolean isIncludedRow()
    {
        return ((Range) filteredRows).containsLong(this.rowNumber);
    }

    /**
     * Create a complete string for compatibility with previous version before expression evaluation. This approach is
     * optimized for new expressions, not for previous property/scope parameters.
     * @return Expression composed by scope + name + property
     */
    private String getFullObjectName()
    {
        // only evaluate if needed, else preserve original list
        if (this.name == null)
        {
            return null;
        }

        return this.name;
    }

    /**
     * init the href object used to generate all the links for pagination, sorting, exporting.
     * @param requestHelper request helper used to extract the base Href
     */
    protected void initHref(RequestHelper requestHelper)
    {
        // get the href for this request
        this.baseHref = requestHelper.getHref();

        if (this.excludedParams != null)
        {
            String[] splittedExcludedParams = StringUtils.split(this.excludedParams);

            // handle * keyword
            if (splittedExcludedParams.length == 1 && "*".equals(splittedExcludedParams[0]))
            {
                // @todo cleanup: paramEncoder initialization should not be done here
                if (this.paramEncoder == null)
                {
                    this.paramEncoder = new ParamEncoder(getUid());
                }

                Iterator paramsIterator = baseHref.getParameterMap().keySet().iterator();
                while (paramsIterator.hasNext())
                {
                    String key = (String) paramsIterator.next();

                    // don't remove parameters added by the table tag
                    if (!this.paramEncoder.isParameterEncoded(key))
                    {
                        baseHref.removeParameter(key);
                    }
                }
            }
            else
            {
                for (int j = 0; j < splittedExcludedParams.length; j++)
                {
                    baseHref.removeParameter(splittedExcludedParams[j]);
                }
            }
        }

        if (this.requestUri != null)
        {
            // if user has added a requestURI create a new href
            String fullURI = requestUri;
            if (!this.dontAppendContext)
            {
                String contextPath = ((HttpServletRequest) this.pageContext.getRequest()).getContextPath();

                // prepend the context path if any.
                // actually checks if context path is already there for people which manually add it
                if (!StringUtils.isEmpty(contextPath)
                    && requestUri != null
                    && requestUri.startsWith("/")
                    && !requestUri.startsWith(contextPath))
                {
                    fullURI = contextPath + this.requestUri;
                }
            }

            // call encodeURL to preserve session id when cookies are disabled
            fullURI = ((HttpServletResponse) this.pageContext.getResponse()).encodeURL(fullURI);

            baseHref.setFullUrl(fullURI);

            // // ... and copy parameters from the current request
            // Map parameterMap = normalHref.getParameterMap();
            // this.baseHref.addParameterMap(parameterMap);
        }

    }

    /**
     * Draw the table. This is where everything happens, we figure out what values we are supposed to be showing, we
     * figure out how we are supposed to be showing them, then we draw them.
     * @return int
     * @throws JspException generic exception
     * @see javax.servlet.jsp.tagext.Tag#doEndTag()
     */
    public int doEndTag() throws JspException
    {

        if (log.isDebugEnabled())
        {
            log.debug("[" + getUid() + "] doEndTag called");
        }

        if (!this.doAfterBodyExecuted)
        {
            if (log.isDebugEnabled())
            {
                log.debug("[" + getUid() + "] tag body is empty.");
            }

            // first row (created in doStartTag)
            if (this.currentRow != null)
            {
                // if yes add to table model and remove
                this.tableModel.addRow(this.currentRow);
            }

            // other rows
            while (this.tableIterator.hasNext())
            {
                Object iteratedObject = this.tableIterator.next();
                this.rowNumber++;

                // Row object for Cell values
                this.currentRow = new Row(iteratedObject, this.rowNumber);

                this.tableModel.addRow(this.currentRow);
            }
        }

        // if no rows are defined automatically get all properties from bean
        if (this.tableModel.isEmpty())
        {
            describeEmptyTable();
        }

        // TableDecorator tableDecorator = DecoratorFactory.loadTableDecorator(this.decoratorName);
        String tableDecoratorName = null;
        Object previousMediaType = this.pageContext.getAttribute(PAGE_ATTRIBUTE_MEDIA);
        if (MediaTypeEnum.HTML.equals(this.currentMediaType)
            && (previousMediaType == null || MediaTypeEnum.HTML.equals(previousMediaType)))
        {
            tableDecoratorName = this.decoratorName;
        }
        else if (!MediaTypeEnum.HTML.equals(this.currentMediaType))
        {
            tableDecoratorName = this.properties.getExportDecoratorName(this.currentMediaType);
        }
        TableDecorator tableDecorator = this.properties.getDecoratorFactoryInstance().loadTableDecorator(
            this.pageContext,
            tableDecoratorName);

        if (tableDecorator != null)
        {
            tableDecorator.init(this.pageContext, this.list, this.tableModel);
            this.tableModel.setTableDecorator(tableDecorator);
        }

        setupViewableData();

        // Figure out how we should sort this data, typically we just sort
        // the data being shown, but the programmer can override this behavior
        if (this.paginatedList == null && this.tableModel.isLocalSort())
        {
            if (!this.tableModel.isSortFullTable())
            {
                this.tableModel.sortPageList();
            }
        }

        // Get the data back in the representation that the user is after, do they want HTML/XML/CSV/EXCEL/etc...
        int returnValue = EVAL_PAGE;

        // check for nested tables
        // Object previousMediaType = this.pageContext.getAttribute(PAGE_ATTRIBUTE_MEDIA);
        if (MediaTypeEnum.HTML.equals(this.currentMediaType)
            && (previousMediaType == null || MediaTypeEnum.HTML.equals(previousMediaType)))
        {
            writeHTMLData();
        }
        else if (!MediaTypeEnum.HTML.equals(this.currentMediaType))
        {
            if (log.isDebugEnabled())
            {
                log.debug("[" + getUid() + "] doEndTag - exporting");
            }

            returnValue = doExport();
        }

        // do not remove media attribute! if the table is nested in other tables this is still needed
        // this.pageContext.removeAttribute(PAGE_ATTRIBUTE_MEDIA);

        if (log.isDebugEnabled())
        {
            log.debug("[" + getUid() + "] doEndTag - end");
        }

        cleanUp();
        return returnValue;
    }

    /**
     * clean up instance variables, but not the ones representing tag attributes.
     */
    private void cleanUp()
    {
        // reset instance variables (non attributes)
        this.currentMediaType = null;
        this.baseHref = null;
        this.caption = null;
        this.captionTag = null;
        this.currentRow = null;
        this.doAfterBodyExecuted = false;
        this.footer = null;

⌨️ 快捷键说明

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