MyFaces Oracle大数据表分页封装

本文介绍了一种基于MyFaces框架的大数据表分页封装方法,通过自定义组件实现了DataTable和DataScroller的封装,便于快速构建高效的数据展示界面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MyFaces Oracle大数据表分页封装

这里将整个DataTableDataScrollerdataModel等全部封装,使用时只需要继承基类BasePageBean和页面使用binding PanelGird即可。<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

其中DataPagePagedListDataModel类来自于网络,目前仍然存在重复查询的问题。

package commons.jsf;

import java.util.List;

/**

* A simple class that represents a "page" of data out of a longer set, ie a list of objects together with info to indicate the starting row and the full size of the dataset. EJBs

* can return instances of this type when returning subsets of available data.

*/

public class DataPage<T> {

private int datasetSize;

private int startRow;

private List<T> data;

/**

* Create an object representing a sublist of a dataset.

*

* @param datasetSize

* is the total number of matching rows available.

*

* @param startRow

* is the index within the complete dataset of the first element in the data list.

*

* @param data

* is a list of consecutive objects from the dataset.

*/

public DataPage(int datasetSize, int startRow, List<T> data) {

this.datasetSize = datasetSize;

this.startRow = startRow;

this.data = data;

}

/**

* Return the number of items in the full dataset.

*/

public int getDatasetSize() {

return datasetSize;

}

* Return the offset within the full dataset of the first element in the list held by this object.

*/

public int getStartRow() {

return startRow;

}

/**

* Return the list of objects held by this object, which is a continuous subset of the full dataset.

*/

public List<T> getData() {

return data;

}

public void setStartRow(int startRow) {

this.startRow = startRow;

}

}

package commons.jsf;

import java.util.ArrayList;

import java.util.List;

import javax.faces.model.DataModel;

/**

* A special type of JSF DataModel to allow a datatable and datascroller to page through a large set of data without having to hold the entire set of data in memory at once.

* <p>

* Any time a managed bean wants to avoid holding an entire dataset, the managed bean should declare an inner class which extends this class and implements the fetchData method.

* This method is called as needed when the table requires data that isn&apos;t available in the current data page held by this object.

* <p>

* This does require the managed bean (and in general the business method that the managed bean uses) to provide the data wrapped in a DataPage object that provides info on the

* full size of the dataset.

*/

public abstract class PagedListDataModel<T> extends DataModel {

int pageSize;

int rowIndex;

DataPage<T> page;

/** */

/**

* Create a datamodel that pages through the data showing the specified number of rows on each page.

*/

public PagedListDataModel(int pageSize) {

super();

this.pageSize = pageSize;

this.rowIndex = -1;

this.page = null;

}

/** */

/**

* Not used in this class; data is fetched via a callback to the fetchData method rather than by explicitly assigning a list.

*/

public void setWrappedData(Object o) {

if (o instanceof DataPage) {

this.page = (DataPage) o;

} else {

throw new UnsupportedOperationException(" setWrappedData ");

}

}

public int getRowIndex() {

return rowIndex;

}

/** */

/**

* Specify what the "current row" within the dataset is. Note that the UIData component will repeatedly call this method followed by getRowData to obtain the objects to render

* in the table.

*/

public void setRowIndex(int index) {

rowIndex = index;

// if (page != null )

// {

// page.setStartRow(rowIndex);

// }

}

/** */

/**

* Return the total number of rows of data available (not just the number of rows in the current page!).

*/

public int getRowCount() {

return getPage().getDatasetSize();

}

/** */

/**

* Return a DataPage object; if one is not currently available then fetch one. Note that this doesn&apos;t ensure that the datapage returned includes the current rowIndex row; see

* getRowData.

*/

public DataPage<T> getPage() {

if (page != null) {

return page;

}

int rowIndex = getRowIndex();

int startRow = rowIndex;

if (rowIndex == -1) {

// even when no row is selected, we still need a page

// object so that we know the amount of data available.

startRow = 0;

}

// invoke method on enclosing class

page = fetchPage(startRow, pageSize);

return page;

}

/** */

/**

* Return the object corresponding to the current rowIndex. If the DataPage object currently cached doesn&apos;t include that index then fetchPage is called to retrieve the

* appropriate page.

*/

public Object getRowData() {

if (rowIndex < 0) {

throw new IllegalArgumentException(" Invalid rowIndex for PagedListDataModel; not within page ");

}

// ensure page exists; if rowIndex is beyond dataset size, then

// we should still get back a DataPage object with the dataset size

// in it

if (page == null) {

page = fetchPage(rowIndex, pageSize);

}

// Check if rowIndex is equal to startRow,

// useful for dynamic sorting on pages

/*

* if (rowIndex == page.getStartRow()){ page = fetchPage(rowIndex, pageSize); }

*/

int datasetSize = page.getDatasetSize();

int startRow = page.getStartRow();

int nRows = page.getData().size();

int endRow = startRow + nRows;

if (rowIndex >= datasetSize) {

throw new IllegalArgumentException(" Invalid rowIndex ");

}

if (rowIndex < startRow) {

page = fetchPage(rowIndex, pageSize);

startRow = page.getStartRow();

} else if (rowIndex >= endRow) {

page = fetchPage(rowIndex, pageSize);

startRow = page.getStartRow();

}

// System.out.println("rowIndex:" + rowIndex + ",pageSize:" + pageSize + ",startRow:" + startRow + ",endRow:" + endRow);

try {

List list = page.getData();

if (list != null && list.size() > 0) {

if (rowIndex >= startRow) {

return page.getData().get(rowIndex - startRow);

} else {

return new ArrayList(0);

}

} else {

return new ArrayList(0);

}

} catch (Exception e) {

//添加catch屏蔽连续点击的索引溢出异常

return new ArrayList(0);

}

}

public Object getWrappedData() {

return page.getData();

}

/**

* Return true if the rowIndex value is currently set to a value that matches some element in the dataset. Note that it may match a row that is not in the currently cached

* DataPage; if so then when getRowData is called the required DataPage will be fetched by calling fetchData.

*/

public boolean isRowAvailable() {

DataPage<T> page = getPage();

if (page == null) {

return false;

}

int rowIndex = getRowIndex();

if (rowIndex < 0) {

return false;

} else if (rowIndex >= page.getDatasetSize()) {

return false;

} else {

return true;

}

}

/** */

/**

* Method which must be implemented in cooperation with the managed bean class to fetch data on demand.

*/

public abstract DataPage<T> fetchPage(int startRow, int pageSize);

}

package commons.jsf;

import javax.faces.application.Application;

import javax.faces.component.UIColumn;

import org.apache.myfaces.custom.crosstable.UIColumns;

public interface CellCallBack {

UIColumn doCell(int index, Application app, String rowVar);

}

package commons.jsf;

import java.util.Iterator;

import java.util.List;

import javax.faces.application.Application;

import javax.faces.component.UIColumn;

import javax.faces.component.UIComponent;

import javax.faces.component.UIParameter;

import javax.faces.component.html.HtmlDataTable;

import javax.faces.component.html.HtmlOutputFormat;

import javax.faces.component.html.HtmlOutputLink;

import javax.faces.context.FacesContext;

import javax.faces.el.ValueBinding;

import org.apache.myfaces.component.html.ext.HtmlOutputText;

import org.apache.myfaces.component.html.ext.HtmlPanelGrid;

import org.apache.myfaces.component.html.ext.HtmlPanelGroup;

import org.apache.myfaces.custom.datascroller.HtmlDataScroller;

import commons.FacesUtils;

public class DataGird {

private HtmlPanelGrid dynamicGrid;

private HtmlDataTable dataTable;

private HtmlDataScroller ds1;

private HtmlDataScroller ds2;

/**

* 创建翻页

*

* @return

*/

private HtmlDataScroller newDataScroller1(String dataId, int step, int maxPage) {

// 数据滚动

ds1 = new HtmlDataScroller();

ds1.setFor(dataId);

ds1.setFastStep(step);

ds1.setPageCountVar("pageCount");

ds1.setPageIndexVar("pageIndex");

ds1.setRowsCountVar("rowsCount");

ds1.setDisplayedRowsCountVar("displayedRowsCountVar");

ds1.setFirstRowIndexVar("firstRowIndexVar");

ds1.setLastRowIndexVar("lastRowIndexVar");

if (maxPage > 0) {

ds1.setPaginator(true);

ds1.setPaginatorMaxPages(maxPage);

} else {

ds1.setPaginator(false);

}

//

ds1.setPaginatorActiveColumnStyle("font-weight:bold;");

ds1.setPaginatorTableClass("paginator");

ds1.setStyleClass("scroller");

ds1.setRendered(true);

final HtmlOutputText output1 = new HtmlOutputText();

output1.setValue("首页");

final HtmlOutputText output2 = new HtmlOutputText();

output2.setValue("末页");

final HtmlOutputText output3 = new HtmlOutputText();

output3.setValue("上一页");

final HtmlOutputText output4 = new HtmlOutputText();

output4.setValue("下一页");

ds1.setFirst(output1);

ds1.setLast(output2);

ds1.setPrevious(output3);

ds1.setNext(output4);

if (step > 0) {

final HtmlOutputText output5 = new HtmlOutputText();

output5.setValue("" + step + "");

final HtmlOutputText output6 = new HtmlOutputText();

output6.setValue("" + step + "");

ds1.setFastForward(output5);

ds1.setFastRewind(output6);

}

// //

// Application app = FacesContext.getCurrentInstance().getApplication();

// final HtmlOutputFormat format = new HtmlOutputFormat();

// format.setValue("总记录数{0},{1}/{2}");

// final UIParameter p1 = new UIParameter();

// final UIParameter p2 = new UIParameter();

// final UIParameter p3 = new UIParameter();

// p1.setValueBinding("value", app.createValueBinding("#{rowsCount}"));

// p2.setValueBinding("value", app.createValueBinding("#{pageIndex}"));

// p3.setValueBinding("value", app.createValueBinding("#{pageCount}"));

// format.getChildren().add(p1);

// format.getChildren().add(p2);

// format.getChildren().add(p3);

// ds1.getChildren().add(format);

return ds1;

}

/**

* 创建数据输出

*

* @return

*/

private HtmlDataScroller newDataScroller2(String dataId, int step, int maxPage) {

Application app = FacesContext.getCurrentInstance().getApplication();

// 数据滚动

ds1 = new HtmlDataScroller();

ds1.setFor(dataId);

ds1.setFastStep(step);

ds1.setPageCountVar("pageCount");

ds1.setPageIndexVar("pageIndex");

ds1.setRowsCountVar("rowsCount");

ds1.setDisplayedRowsCountVar("displayedRowsCountVar");

ds1.setFirstRowIndexVar("firstRowIndexVar");

ds1.setLastRowIndexVar("lastRowIndexVar");

ds1.setPaginator(false);

//

ds1.setPaginatorActiveColumnStyle("font-weight:bold;");

ds1.setPaginatorTableClass("paginator");

ds1.setStyleClass("scroller");

final HtmlOutputFormat format = new HtmlOutputFormat();

format.setValue("总记录数{0},{1}/{2}");

final UIParameter p1 = new UIParameter();

final UIParameter p2 = new UIParameter();

final UIParameter p3 = new UIParameter();

p1.setValueBinding("value", app.createValueBinding("#{rowsCount}"));

p2.setValueBinding("value", app.createValueBinding("#{pageIndex}"));

p3.setValueBinding("value", app.createValueBinding("#{pageCount}"));

format.getChildren().add(p1);

format.getChildren().add(p2);

format.getChildren().add(p3);

ds1.getChildren().add(format);

ds1.setRendered(true);

return ds1;

}

/**

* 新建一个数据表格

*

* @return

*/

private void createDataTable(DataGirdBean girdBean, CellCallBack call) {

Application app = FacesContext.getCurrentInstance().getApplication();

final UIComponent c = FacesUtils.findComponentInRoot(girdBean.getGirdId());

if (c == null) {

dynamicGrid = (HtmlPanelGrid) app.createComponent(HtmlPanelGrid.COMPONENT_TYPE);

dynamicGrid.setId(girdBean.getGirdId());

} else {

dynamicGrid = (HtmlPanelGrid) c;

}

dynamicGrid.getChildren().clear(); // clear old stuff

dynamicGrid.setWidth(girdBean.getGirdWidth());

dataTable = new HtmlDataTable();

dataTable.setId(girdBean.getDataTableId());

dataTable.setRendered(true);

dataTable.setWidth(girdBean.getDataTableWidth());

// final List list = dataTable.getChildren();

// list.clear();

// Setup data bindings

dataTable.setVar("list");

dataTable.setValueBinding("value", (ValueBinding) app.createValueBinding(girdBean.getDataTableValueBinding()));

dataTable.setBorder(0);

dataTable.setCellpadding(girdBean.getDataTableCellpadding());

dataTable.setCellspacing(girdBean.getDataTableCellspacing());

dataTable.setStyleClass(girdBean.getDataTableStyleClass());

dataTable.setRows(girdBean.getDataTableRows());

String[] header = girdBean.getDataTableHeader();

for (int i = 0; i < header.length; i++) {

UIColumn column = new UIColumn();

HtmlOutputText output = new HtmlOutputText();

output.setValueBinding("value", app.createValueBinding("#{list[" + i + "]}"));

column.getChildren().add(output);

if (call != null) {

column = call.doCell(i,app, "list");

}

final HtmlOutputText headerComponent = new HtmlOutputText();

headerComponent.setValue(header[i]);

column.setHeader(headerComponent);

dataTable.getChildren().add(column);

}

HtmlPanelGroup pg = new HtmlPanelGroup();

pg.getChildren().add(this.newDataScroller1(girdBean.getDataTableId(), girdBean.getDsStep(), girdBean.getDsMaxPage()));

pg.getChildren().add(this.newDataScroller2(girdBean.getDataTableId(), girdBean.getDsStep(), girdBean.getDsMaxPage()));

dynamicGrid.getChildren().add(dataTable);

dynamicGrid.getChildren().add(pg);

}

public HtmlPanelGrid createDataPanel(DataGirdBean girdBean, CellCallBack call) {

this.createDataTable(girdBean, call);

return dynamicGrid;

}

public HtmlPanelGrid createDataPanel(DataGirdBean girdBean) {

this.createDataTable(girdBean, null);

return dynamicGrid;

}

}

package commons.jsf;

public class DataGirdBean {

private String girdId = "dynamicGrid";

private String girdWidth = "100%";

private String dataTableStyleClass;

private String dataTableId = "dynamicTable";

private String dataTableValueBinding;

private String dataTableCellpadding = "0";

private String dataTableCellspacing = "0";

private String dataTableWidth = "100%";

private int dataTableRows = 13;

private String[] dataTableHeader;

private int dsStep = 10;

private int dsMaxPage = 10;

public String getDataTableCellpadding() {

return dataTableCellpadding;

}

public void setDataTableCellpadding(String dataTableCellpadding) {

this.dataTableCellpadding = dataTableCellpadding;

}

public String getDataTableCellspacing() {

return dataTableCellspacing;

}

public void setDataTableCellspacing(String dataTableCellspacing) {

this.dataTableCellspacing = dataTableCellspacing;

}

public String[] getDataTableHeader() {

return dataTableHeader;

}

public void setDataTableHeader(String[] dataTableHeader) {

this.dataTableHeader = dataTableHeader;

}

public String getDataTableId() {

return dataTableId;

}

public void setDataTableId(String dataTableId) {

this.dataTableId = dataTableId;

}

public int getDataTableRows() {

return dataTableRows;

}

public void setDataTableRows(int dataTableRows) {

this.dataTableRows = dataTableRows;

}

public String getDataTableStyleClass() {

return dataTableStyleClass;

}

public void setDataTableStyleClass(String dataTableStyleClass) {

this.dataTableStyleClass = dataTableStyleClass;

}

public String getDataTableValueBinding() {

return dataTableValueBinding;

}

public void setDataTableValueBinding(String dataTableValueBinding) {

this.dataTableValueBinding = dataTableValueBinding;

}

public String getGirdId() {

return girdId;

}

public void setGirdId(String girdId) {

this.girdId = girdId;

}

public String getGirdWidth() {

return girdWidth;

}

public void setGirdWidth(String girdWidth) {

this.girdWidth = girdWidth;

}

public String getDataTableWidth() {

return dataTableWidth;

}

public void setDataTableWidth(String dataTableWidth) {

this.dataTableWidth = dataTableWidth;

}

public int getDsMaxPage() {

return dsMaxPage;

}

public void setDsMaxPage(int dsMaxPage) {

this.dsMaxPage = dsMaxPage;

}

public int getDsStep() {

return dsStep;

}

public void setDsStep(int dsStep) {

this.dsStep = dsStep;

}

}

package commons.jsf;

import java.util.List;

import javax.faces.model.DataModel;

import org.apache.myfaces.component.html.ext.HtmlPanelGrid;

public abstract class BasePageBean {

protected DataModel dataModel;

protected HtmlPanelGrid dynamicGrid;

protected String[] header;

public static final int PAGESIZE = 15;

public DataModel getDataModel() {

if (dataModel == null) {

dataModel = new LocalDataModel(PAGESIZE);

dataModel.setWrappedData(getDataPage(0, PAGESIZE));

}

return dataModel;

}

private class LocalDataModel extends PagedListDataModel {

public LocalDataModel(int pageSize) {

super(pageSize);

}

public DataPage fetchPage(int startRow, int pageSize) {

System.out.println(startRow + "====" + pageSize);

return getDataPage(startRow, pageSize);

}

}

protected abstract DataPage getDataPage(int startRow, int pageSize);

public abstract void createDataTable();

// {

// List<Object[]> list = null;// ReadCount1Service.getInstance().count(this.condition, , startRow, pageSize);

// int dataSetSize = 0;// ReadCount1Service.getInstance().countCt();

// // System.out.println("-------" + this.dataList.size() + "--" + dataSetSize);

// return new DataPage(dataSetSize, startRow, list);

// }

public void setDataModel(DataModel dataModel) {

this.dataModel = dataModel;

}

public HtmlPanelGrid getDynamicGrid() {

createDataTable();

return dynamicGrid;

}

public void setDynamicGrid(HtmlPanelGrid dynamicGrid) {

this.dynamicGrid = dynamicGrid;

}

public String[] getHeader() {

return header;

}

public void setHeader(String[] header) {

this.header = header;

}

}

package commons;

import javax.faces.FactoryFinder;

import javax.faces.application.Application;

import javax.faces.application.ApplicationFactory;

import javax.faces.application.FacesMessage;

import javax.faces.component.UIComponent;

import javax.faces.context.FacesContext;

import javax.faces.context.ExternalContext;

import javax.faces.el.ValueBinding;

import javax.faces.webapp.UIComponentTag;

import javax.servlet.ServletContext;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import java.util.Iterator;

import java.util.Locale;

import java.util.MissingResourceException;

import java.util.ResourceBundle;

/**

* Util class for JSF.

*

* @author Sergey Aleksandrov

*/

public class FacesUtils {

private static final Log log = LogFactory.getLog(FacesUtils.class);

private static final String DEFAULT_BUNDLE = "javax.faces.Messages";

/**

* Get servlet context.

*

* @return the servlet context

*/

public static ServletContext getServletContext() {

return getServletContext(FacesContext.getCurrentInstance());

}

/**

* Get servlet context.

*

* @param facesContext

* FacesContext

* @return the servlet context

*/

public static ServletContext getServletContext(FacesContext facesContext) {

return (ServletContext) facesContext.getExternalContext().getContext();

}

public static Object getManagedBean(FacesContext ctx, String beanName) {

return ctx.getApplication().getVariableResolver().resolveVariable(ctx, beanName);

}

/**

* Get managed bean based on the bean name.

*

* @param beanName

* the bean name

* @return the managed bean associated with the bean name

*/

public static Object getManagedBean(String beanName) {

return getManagedBean(FacesContext.getCurrentInstance(), beanName);

}

/**

* Get managed bean based on the bean name.

*

* @param facesContext

* FacesContext

* @param beanName

* the bean name

* @return the managed bean associated with the bean name

*/

// public static Object getManagedBean(FacesContext facesContext, String beanName) {

// Object o = getValueBinding(getJsfEl(beanName)).getValue(facesContext);

// return o;

// }

/**

* Remove the managed bean based on the bean name.

*

* @param beanName

* the bean name of the managed bean to be removed

*/

public static void resetManagedBean(String beanName) {

resetManagedBean(FacesContext.getCurrentInstance(), beanName);

}

/**

* Remove the managed bean based on the bean name.

*

* @param facesContext

* FacesContext

* @param beanName

* the bean name of the managed bean to be removed

*/

public static void resetManagedBean(FacesContext facesContext, String beanName) {

getValueBinding(getJsfEl(beanName)).setValue(facesContext, null);

}

/**

* Store the managed bean inside the session scope.

*

* @param beanName

* the name of the managed bean to be stored

* @param managedBean

* the managed bean to be stored

*/

public static void setManagedBeanInSession(String beanName, Object managedBean) {

setManagedBeanInSession(FacesContext.getCurrentInstance(), beanName, managedBean);

}

/**

* Store the managed bean inside the session scope.

*

* @param beanName

* the name of the managed bean to be stored

* @param managedBean

* the managed bean to be stored

*/

public static void setManagedBeanInSession(FacesContext facesContext, String beanName, Object managedBean) {

facesContext.getExternalContext().getSessionMap().put(beanName, managedBean);

}

/**

* Get parameter value from request scope.

*

* @param name

* the name of the parameter

* @return the parameter value

*/

public static String getRequestParameter(String name) {

return getRequestParameter(FacesContext.getCurrentInstance(), name);

}

/**

* Get parameter value from request scope.

*

* @param name

* the name of the parameter

* @return the parameter value

*/

public static String getRequestParameter(FacesContext facesContext, String name) {

return (String) facesContext.getExternalContext().getRequestParameterMap().get(name);

}

/**

*

* @param locale

* @return

*/

public static ResourceBundle getApplicationBundle(Locale locale) {

return getApplicationBundle(FacesContext.getCurrentInstance(), locale);

}

/**

* get application bundle

*

* @param facesContext

* @param locale

* @return

*/

public static ResourceBundle getApplicationBundle(FacesContext facesContext, Locale locale) {

String bundleName = facesContext.getApplication().getMessageBundle();

if (bundleName != null) {

try {

return ResourceBundle.getBundle(bundleName, locale, Thread.currentThread().getContextClassLoader());

} catch (MissingResourceException e) {

log.error("Resource bundle " + bundleName + " could not be found.");

return null;

}

} else {

return null;

}

}

/**

* get default bundle

*

* @param locale

* @return

*/

public static ResourceBundle getDefaultBundle(Locale locale) {

try {

return ResourceBundle.getBundle(DEFAULT_BUNDLE, locale, FacesContext.class.getClassLoader());

} catch (MissingResourceException e) {

log.error("Resource bundle " + DEFAULT_BUNDLE + " could not be found.");

return null;

}

}

/**

* get current instance of Application

*

* @return current instance of Application

*/

public static Application getApplication() {

ApplicationFactory appFactory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);

return appFactory.getApplication();

}

/**

* get ValueBinding by an EL expression which like "#{expression}"

*

* @param el

* @return

*/

public static ValueBinding getValueBinding(String el) {

return getApplication().createValueBinding(el);

}

/**

* get the instanceof of HttpServletRequest

*

* @return

*/

public static HttpServletRequest getServletRequest() {

return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();

}

public static Object getElValue(String el) {

return getValueBinding(el).getValue(FacesContext.getCurrentInstance());

}

private static String getJsfEl(String value) {

return "#{" + value + "}";

}

/**

* Add error message to a sepcific client.

*

* @param clientId

* the client id

* @param msg

* the error message

*/

public static String getMessageByKey(String key) {

String messageBundleName = FacesContext.getCurrentInstance().getApplication().getMessageBundle();

ResourceBundle resourceBundle = ResourceBundle.getBundle(messageBundleName);

try {

return resourceBundle.getString(key);

} catch (Exception e) {

return key;

}

}

/**

* Add error message.

*

* @param msg

* the error message

*/

public static void addErrorMessage(String msg) {

addErrorMessage(null, msg);

}

/**

* Add error message to a sepcific client.

*

* @param clientId

* the client id

* @param msg

* the error message

*/

public static void addErrorMessage(String clientId, String msg) {

FacesContext.getCurrentInstance().addMessage(clientId, new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg));

}

/**

* find Component In Root By ID

*

* @param id

* @return

*/

public static UIComponent findComponentInRoot(String id) {

UIComponent ret = null;

FacesContext context = FacesContext.getCurrentInstance();

if (context != null) {

UIComponent root = context.getViewRoot();

ret = findComponent(root, id);

}

return ret;

}

private static UIComponent findComponent(UIComponent base, String id) {

// Is the base component itself the match we are looking for?

if (id.equals(base.getId())) {

return base;

}

// Search through our facets and children

UIComponent kid = null;

UIComponent result = null;

Iterator kids = base.getFacetsAndChildren();

while (kids.hasNext() && (result == null)) {

kid = (UIComponent) kids.next();

if (id.equals(kid.getId())) {

result = kid;

break;

}

result = findComponent(kid, id);

if (result != null) {

break;

}

}

return result;

}

}

例子程序:

package dwr;

import java.util.List;

import javax.faces.application.Application;

import javax.faces.component.UIColumn;

import org.apache.myfaces.component.html.ext.HtmlOutputText;

import org.apache.myfaces.custom.checkbox.HtmlCheckbox;

import commons.jsf.BasePageBean;

import commons.jsf.CellCallBack;

import commons.jsf.DataGird;

import commons.jsf.DataGirdBean;

import commons.jsf.DataPage;

public class TestBean extends BasePageBean {

@Override

public void createDataTable() {

DataGirdBean girdBean = new DataGirdBean();

String[] header =

{ "cust_no", "cust_name", "cust_addr", "linkman " };

girdBean.setDataTableHeader(header);

girdBean.setDataTableValueBinding("#{TestBean.dataModel}");

DataGird gird = new DataGird();

this.dynamicGrid = gird.createDataPanel(girdBean);

this.dynamicGrid = gird.createDataPanel(girdBean, new CellCallBack() {

public UIColumn doCell(int index, Application app, String rowVar) {

UIColumn column = new UIColumn();

HtmlOutputText o = new HtmlOutputText();

o.setValueBinding("value", app.createValueBinding("#{list[" + index + "]}"));

return column;

}

});

}

@Override

protected DataPage getDataPage(int startRow, int pageSize) {

List<Object[]> list = TestService.getInstance().getList(startRow, pageSize);

int dataSetSize = TestService.getInstance().getCt();

// System.out.println("-------" + this.dataList.size() + "--" + dataSetSize);

return new DataPage(dataSetSize, startRow, list);

}

}

package dwr;

import java.util.ArrayList;

import java.util.List;

import commons.DbUtil;

public class TestService {

private static TestService instance = new TestService();

private String ctSQL = "";

private TestService() {

}

public List<Object[]> getList(int startRow, int endRow) {

String sql = "select t.cust_no,t.cust_name,t.cust_addr,t.linkman from cust_info t";

this.ctSQL = "select count(*) from cust_info";

return DbUtil.query(sql, startRow, endRow);

}

public int getCt() {

String ct = DbUtil.querySingleObj(ctSQL);

return Integer.parseInt(ct);

}

public static TestService getInstance() {

return instance;

}

}

package commons;

import java.sql.CallableStatement;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbutils.DbUtils;

import org.apache.commons.dbutils.QueryRunner;

import org.apache.commons.dbutils.ResultSetHandler;

import org.apache.commons.dbutils.handlers.ArrayListHandler;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.context.support.FileSystemXmlApplicationContext;

import org.springframework.dao.DataAccessException;

import org.springframework.jdbc.core.CallableStatementCreator;

import org.springframework.jdbc.core.ConnectionCallback;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.PreparedStatementCallback;

import org.springframework.jdbc.core.RowCallbackHandler;

import org.springframework.jdbc.core.RowMapper;

import org.springframework.jdbc.core.StatementCallback;

import plmt.DbParam;

import util.SpringFacesUtil;

public class DbUtil {

private static DataSource dataSource;

private static JdbcTemplate jdbcTemplate;

private static DbUtil instance = new DbUtil();

static {

dataSource = (DataSource) SpringFacesUtil.getBean("dataSource");

jdbcTemplate = new JdbcTemplate(dataSource);

}

private DbUtil() {

}

/**

* @return the dataSource

*/

public static DataSource getDataSource() {

return dataSource;

}

@SuppressWarnings("unchecked")

public static List<Object[]> query(String sql) {

// System.out.println("SQL:" + sql);

QueryRunner run = new QueryRunner(getDataSource());

List<Object[]> list = null;

try {

list = (List<Object[]>) run.query(sql, new ArrayListHandler());

} catch (SQLException e) {

e.printStackTrace();

}

return list;

}

@SuppressWarnings("unchecked")

public static List<Object[]> query(String sql, int startRow, int endRow) {

String sql1 = "select * from (select zx_page_table.*,rownum page_rownum from (" + sql + ") zx_page_table where rownum<=" + (endRow + startRow) + ") where page_rownum>="

+ startRow + "";

System.out.println("SQL:" + sql1);

return query(sql1);

}

public static String querySingleObj(String sql) {

List<Object[]> l = query(sql);

String v = null;

if (l != null && l.size() > 0) {

Object[] o = l.get(0);

v = o[0] == null ? null : o[0].toString();

}

return v;

}

/**

* 调用存储过程

*

* @param call

* @param lidt

*/

public static void procedure(final String call, final List<DbParam> params) {

getJdbcTemplate().execute(new ConnectionCallback() {

public Object doInConnection(Connection conn) throws SQLException, DataAccessException {

CallableStatement proc = null;

proc = conn.prepareCall(call);

int i = 1;

if (params != null) {

for (DbParam param : params) {

proc.setString(i, (String) param.getParamValue());

i++;

}

}

proc.execute();

return null;

}

});

}

/**

* 调用存储过程

*

* @param call

* @param lidt

*/

public static void procedure(final String call, final String[] params) {

getJdbcTemplate().execute(new ConnectionCallback() {

public Object doInConnection(Connection conn) throws SQLException, DataAccessException {

CallableStatement proc = conn.prepareCall(call);

int i = 1;

if (params != null) {

for (String param : params) {

proc.setString(i, param);

i++;

}

}

proc.execute();

return null;

}

});

}

public static void execute(String sql) {

// System.out.println("SQL:" + sql);

getJdbcTemplate().execute(sql);

}

public static void update(String sql) {

// System.out.println("SQL:" + sql);

getJdbcTemplate().execute(sql);

}

public static void update(final String[] sql) {

// for (String string : sql) {

// System.out.println("SQL:" + string);

// }

getJdbcTemplate().batchUpdate(sql);

}

public static Object[] toArray(ResultSet rs) throws SQLException {

ResultSetMetaData meta = rs.getMetaData();

int cols = meta.getColumnCount();

Object[] result = new Object[cols];

for (int i = 0; i < cols; i++) {

result[i] = rs.getObject(i + 1);

}

return result;

}

public static DbUtil getInstance() {

return instance;

}

public static JdbcTemplate getJdbcTemplate() {

return jdbcTemplate;

}

}

<%@ page language="java" contentType="text/html;charset=UTF-8"%>

<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%>

<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

<%@taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%>

<html>

<head>

</head>

<f:view>

<body>

<h:form id="form1">

<t:panelGrid binding="#{TestBean.dynamicGrid}"></t:panelGrid>

</h:form>

</body>

</f:view>

</html>

其中DbUtil可以根据自己所使用的持久化方案来调整。

源代码<?xml:namespace prefix = v ns = "urn:schemas-microsoft-com:vml" /><shapetype id="_x0000_t75" stroked="f" filled="f" path="m@4@5l@4@11@9@11@9@5xe" o:preferrelative="t" o:spt="75" coordsize="21600,21600"> :https://p-blog.youkuaiyun.com/images/p_blog_youkuaiyun.com/myloon/EntryImages/20080718/commons.jpg</shapetype>

<shapetype stroked="f" filled="f" path="m@4@5l@4@11@9@11@9@5xe" o:preferrelative="t" o:spt="75" coordsize="21600,21600">将jpg修改为zip</shapetype>

其中在backBean中可自定义实现每一个单元格填充的数据样式和修饰,如下:

this.dynamicGrid = gird.createDataPanel(girdBean, new CellCallBack() {

public UIColumn doCell(int index, Application app, String rowVar) {

UIColumn column = new UIColumn();

HtmlOutputText o = new HtmlOutputText();

o.setValueBinding("value", app.createValueBinding("#{list[" + index + "]}"));

return column;

}

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值