动态生成不同对象的表

时间:2012-12-13 09:23:30

标签: java oop jsp

对于我在Java / jsp中制作的东西,我将会有很多看起来相似的视觉表,但是对于不同的对象。每个对象具有不同数量的字段,但至少共享id,其链接通过对象的更详细页面。

因此,无论对象有多少个字段,我都在考虑制作一些我可以重复使用的东西的可能性。

这是我想要实现的一个例子

Object A
-id
-name
-address

Object B
-id
-field2
-field3

想将其翻译为:

Table for Object A's
id -- name -- address
1     Bert    Street
2     Jeff    Lane

Table for Object B's
id  -- field2  -- field3
1        AB         5
2        Foo        Bar

实现这一目标的最佳方法是什么?我正在考虑(除了id之外),向所有字段的两个对象添加一个可枚举的getter,然后循环遍历它以生成表。

有更好的方法吗?

2 个答案:

答案 0 :(得分:2)

您可以在主要类中添加一个Map<String,Object>字段,其中Map的键将是您的媒体资源的名称。

或者,如果您的字段始终是字符串,则可以使用Properties,它们基本上是Map<String,String>,但有一些小的扭曲(例如默认值)

答案 1 :(得分:1)

我通常做的是创建一个这样的类作为我的表模型:

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

import com.tricode.mrc.ui.web.messages.Messages;

/**
 * 
 * @author Sinisa
 *
 * @param <T> the entity type
 */
public abstract class AbstractCrudForm<T extends Serializable> {

        private List<T> data;

        public AbstractCrudForm(List<T> data) {
                this.data = data;
        }

        /**
         * @param record
         * @return the value of the id field of the given record
         */
        protected abstract String getId(T record);

        /**
         * @return ui name of the entity that is displayed <br>i.e. for DataValidationConfiguration will return "Data Validation Configuration"
         */
        public abstract String getUserFriendlyTypeName();

        /**
         * @return the number of fields of the columns (fields)
         */
        public abstract int getNumberOfFields();

        /**
         * Return the column names as seen in the header of the crud table
         * @return
         */
        public abstract String[] getArrayOfColumnNames();

        /**
         * @param record
         * @param column
         * @return
         */
        protected abstract String getDataAtColumn(T record, int column);

        /**
         * Returns the data at the specified position
         * @param row
         * @param column
         * @return the data at the specified position
         */
        public String getDataAt(int row, int column) {
                return getDataAtColumn(data.get(row), column);
        }

        /**
         * @return a list of the data
         */
        protected List<T> getData() {
                return this.data;
        }

        /**
         * @return the user friendly name for the title of the ui form for editing
         */
        public String getUserFriendlyEditTypeName() {
                return Messages.getString("AbstractCrudForm.Edit") + getUserFriendlyTypeName(); //$NON-NLS-1$
        }

        /**
         * @return the user friendly name for the title of the ui form for editing
         */
        public String getUserFriendlySaveTypeName() {
                return Messages.getString("AbstractCrudForm.New") + getUserFriendlyTypeName(); //$NON-NLS-1$
        }

        /**
         * @return a list of the column names
         */
        public List<String> getColumns() {
                return Arrays.asList(getArrayOfColumnNames());
        }

        /**
         * @param position
         * @return the column name at a given position
         */
        public String getColumnNameAt(int position) {
                return getArrayOfColumnNames()[position];
        }

        /**
         * The result size
         * @return
         */
        public int resultsSize() {
                return data.size();
        }

        /**
         * @param row
         * @return the value of the id field for the given record
         */
        public String getId(int row) {
                return getId(data.get(row));
        }

}

对于我想要实现的每个类(在您的情况下,对象A和对象B),我重写此抽象模型,如:

import java.util.List;

import com.tricode.misterchameleon.model.DataValidationConfiguration;
import com.tricode.mrc.ui.web.AbstractCrudForm;
import com.tricode.mrc.ui.web.messages.Messages;

public class DataValidationConfigurationCrudForm extends AbstractCrudForm<DataValidationConfiguration> {

        public DataValidationConfigurationCrudForm(List<DataValidationConfiguration> data) {
                super(data);
        }

        @Override
        public String getTypeName() {
                return DataValidationConfiguration.class.getSimpleName();
        }

        @Override
        public String getUserFriendlyTypeName() {
                return Messages.getString("DataValidationConfigurationCrudForm.DataValidationConfiguration"); //$NON-NLS-1$
        }

        @Override
        public int getNumberOfFields() {
                // TODO take it with generics
                return 8;
        }

        @Override
        public String[] getArrayOfColumnNames() {
                return new String[] {
                                Messages.getString("DataValidationConfigurationCrudForm.ID"), Messages.getString("DataValidationConfigurationCrudForm.DomainName"), Messages.getString("DataValidationConfigurationCrudForm.FormUrl"), Messages.getString("DataValidationConfigurationCrudForm.PostalCode"), Messages.getString("DataValidationConfigurationCrudForm.HouseNumber"), Messages.getString("DataValidationConfigurationCrudForm.Street"), Messages.getString("DataValidationConfigurationCrudForm.City"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
                                Messages.getString("DataValidationConfigurationCrudForm.Country") }; //$NON-NLS-1$
        }

        @Override
        protected String getDataAtColumn(DataValidationConfiguration config, int column) {
                switch (column) {
                case 0:
                        return config.getId().toString();
                case 1:
                        return config.getDomainName();
                case 2:
                        return config.getFormUrl();
                case 3:
                        return config.getPostalCode();
                case 4:
                        return config.getHouseNumber();
                case 5:
                        return config.getStreet();
                case 6:
                        return config.getCity();
                case 7:
                        return config.getCountry();
                default:
                        throw new IllegalArgumentException(Messages.getString("DataValidationConfigurationCrudForm.YouShouldntHaveGottenHere")); //$NON-NLS-1$
                }
        }

        @Override
        protected String getId(DataValidationConfiguration record) {
                return record.getId().toString();
        }

}

我将此对象传递给jsp,然后我有一个用于绘制表的通用jsp文件:

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<div class="row">
    <div class="twelve columns">
        <h1>${genForm.getUserFriendlyTypeName()}</h1>

        <a href="${genForm.getCreateLink()}" class="btn_styled">Create</a>
        <table class="border">
            <thead>
                <tr>
                    <c:forEach var="col" items="${genForm.getColumns()}">
                        <th>${col}</th>
                    </c:forEach>
                    <!-- Add two more for delete and edit -->
                    <th></th>
                    <th></th>
                </tr>
            </thead>
            <c:if test="${genForm.resultsSize() == 0}">
                <tr colspan="${genForm.getNumberOfFields()}">
                    <td><spring:message code="common.crud.norecords" text="common.crud.norecords"/></td>
                </tr>
            </c:if>
            <c:if test="${genForm.resultsSize() > 0}">
                <c:forEach var="row" begin="0" end="${genForm.resultsSize() - 1}">
                    <tr>
                        <c:set var="edit" value="?" />
                        <c:forEach var="column" begin="0"
                            end="${genForm.getNumberOfFields() - 1}">
                            <td>${genForm.getDataAt(row, column)}</td>
                            <c:set var="edit"
                                value="${edit}${genForm.getJavaFieldNameAt(column)}=${genForm.getDataAt(row, column)}&" />
                        </c:forEach>
                        <!-- Add delete and edit buttons -->
                        <th><a id="edit-row" class="btn_styled"
                            href="${genForm.getEditLink()}${edit}"><spring:message
                                    code="common.button.edit" text="common.button.edit" /></a></th>
                        <th><a id="delete-row" class="btn_styled"
                            href="${genForm.getDeleteLink()}?id=${genForm.getId(row)}"><spring:message
                                    code="common.button.delete" text="common.button.delete" /></a></th>
                    </tr>
                </c:forEach>
            </c:if>

        </table>
    </div>
</div>

我发布的所有代码都不应被视为复制/粘贴解决方案,因为它可能无法立即生效。它应该被视为一种想法,也是一种解决问题的简洁方法。