A
📖 知识库
🌐

动态表单与 Freemarker 渲染

📄 业务模块 35 分钟阅读 86 次浏览 更新于 2026-10-25

导读

「动态表单与 Freemarker 渲染」常被追问到细节层面,这里把结论、原因和易错点一次讲清楚。

OA 里每种公文需要填的字段都不一样:请假单要填"请假天数、事由",报销单要填"金额、票据",采购单要填"物品、数量、供应商"。为每种公文单独建表、单独写页面显然不现实,于是就有了动态表单。


一、问题分析

方案 做法 问题
每类公文一张表 T_LeaveForm、T_ExpenseForm … 新增流程就要建表、写代码
宽表预留字段 T_Document 加 field1~field30 字段含义靠约定,难维护
单列大字段存 JSON/XML 一个 content 存全部 无法按字段查询与校验
动态表单(本项目) 表单结构存元数据,值按类型分列存 结构复杂一点,但完全可扩展

本项目采用最后一种:表单的定义(元数据)与表单的值(实例数据)分离。


二、领域模型

FlowForm(流程表单)
   ├── workflow  ──> Workflow(一个流程对应一张表单)
   ├── template  ──> 整体布局模板(如 document_form.ftl)
   └── fields    ──> Set<FormField>(表单域集合)
                        ├── fieldLabel   显示标签,如 "报销金额"
                        ├── fieldName    存储名,如 "money"
                        ├── fieldInput ──> FieldInput(输入形式)
                        │                    ├── name       "文本输入框"
                        │                    └── template   "text.ftl"
                        ├── fieldType  ──> FieldType(数据类型)
                        │                    ├── name       "整数"
                        │                    └── type       "java.lang.Integer"
                        └── items      ──> List<FieldItem>(下拉/单选的候选项)
                                             ├── label  显示文本
                                             └── value  实际值
public class FlowForm {
    private int id;
    private Workflow workflow;
    private String template;   // 整体模板文件名
    private Set fields;        // 表单域集合
}

public class FormField {
    private int id;
    private String fieldLabel;    // 界面显示
    private String fieldName;     // 存储键名
    private FieldInput fieldInput;
    private FieldType fieldType;
    private List items;           // 候选项(select/radio/checkbox 用)
    private FlowForm flowForm;
}

public class FieldInput {
    private int id;
    private String name;        // "文本输入框"
    private String template;    // "text.ftl"
}

public class FieldType {
    private int id;
    private String name;        // "整数"
    private String type;        // "java.lang.Integer" / "java.lang.String" / "java.io.File"
}

初始化数据(init_datas.xml):

<FieldInputs>
    <FieldInput name="文本输入框"   template="text.ftl"/>
    <FieldInput name="复选框"       template="checkbox.ftl"/>
    <FieldInput name="单选框"       template="radio.ftl"/>
    <FieldInput name="下拉列表框"   template="select.ftl"/>
    <FieldInput name="文件输入框"   template="file.ftl"/>
</FieldInputs>
<FieldTypes>
    <FieldType name="字符串" type="java.lang.String"/>
    <FieldType name="整数"   type="java.lang.Integer"/>
    <FieldType name="文件"   type="java.io.File"/>
</FieldTypes>

输入形式(怎么显示)与数据类型(怎么存)是两个正交的维度,拆开设计后,想加一个"日期选择器"只需新增一条 FieldInput 记录 + 一个 date.ftl。


三、值的存储:类型分列 + Map 映射

表单的值有三个可能类型,不能塞进同一列。解法是一个 Map,值为复合元素,复合元素里按类型分三列:

public class DocumentProperty {
    private String   java_lang_String;   // 存字符串
    private Integer  java_lang_Integer;  // 存整数
    private byte[]   java_io_File;       // 存文件字节
}

Hibernate 映射(<map> + <composite-element>):

<class table="T_Document" name="com.oa.model.Document">
  ...
  <map table="T_Document_Properties" name="props">
    <key column="documentId"/>
    <map-key type="string" column="propertyName"/>
    <composite-element class="com.oa.model.DocumentProperty">
      <property name="java_lang_String"/>
      <property name="java_lang_Integer"/>
      <property name="java_io_File" length="99999999" type="binary"/>
    </composite-element>
  </map>
</class>

于是 document.getProps() 返回 Map<String, DocumentProperty>:

documentId propertyName java_lang_String java_lang_Integer java_io_File
12 title 差旅报销 NULL NULL
12 money NULL 50000 NULL
12 receipt NULL NULL [binary]

优点:值是强类型的,可以直接参与 SQL 计算与流程条件判断(如 #{money gt 10000})。 缺点:加一种新类型就要加一列。更通用的做法是加一个 value_type 列 + 一个 value 列,或用 JSON 字段。


四、表单定义界面

4.1 一次提交 N 个表单域

用 AutoArrayList 让 List 在被访问时自动补齐元素(见《呈现层:Struts 与 JSP》):

public class FlowFormActionForm extends ActionForm {
    private int workflowId;
    private String template;
    private List fields = new AutoArrayList(FormField.class);   // 自动扩容
    private List items  = new AutoArrayList(FieldItem.class);   // 候选项同样处理
}

页面按索引命名:

<form action="flowform.do?method=save" method="post">
  <input type="hidden" name="workflowId" value="${workflowId}">
  <table>
    <tr>
      <td><input name="fields[0].fieldLabel" value="报销金额"></td>
      <td><input name="fields[0].fieldName"  value="money"></td>
      <td>
        <select name="fields[0].fieldType.id">
          <option value="1">字符串</option><option value="2">整数</option><option value="3">文件</option>
        </select>
      </td>
      <td>
        <select name="fields[0].fieldInput.id">
          <option value="1">文本输入框</option><option value="4">下拉列表框</option>
        </select>
      </td>
    </tr>
    <!-- 再加一行就写 fields[1].xxx -->
  </table>
  <input type="submit" value="保存表单定义">
</form>

4.2 保存

public ActionForward save(ActionMapping mapping, ActionForm form, ...) {
    FlowFormActionForm ffaf = (FlowFormActionForm) form;
    formManager.saveForm(ffaf.getWorkflowId(), ffaf.getTemplate(), ffaf.getFields(), ffaf.getItems());
    return mapping.findForward("pub_add_success");
}

五、用 Freemarker 渲染表单

5.1 模板管理

public class FreemarkerManager {
    private static Configuration cfg = new Configuration();
    static {
        // 从类路径、相对 FreemarkerManager 所在包的 templates 目录加载模板
        cfg.setTemplateLoader(new ClassTemplateLoader(FreemarkerManager.class, "templates"));
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
    }
    public static Configuration getConfiguration() { return cfg; }
}

模板文件放在 com/oa/freemarker/templates/ 下,编译后随 class 一起进 WEB-INF/classes。

5.2 三个原子模板

text.ftl:

<input type="text" name="props(${field.fieldName})">

select.ftl:

<select name="props(${field.fieldName})">
    <#list field.items as item>
    <option value="${item.value}">${item.label}</option>
    </#list>
</select>

file.ftl:

<input type="file" name="props(${field.fieldName})">

三者的 name 都是 props(xxx)——这是 Struts 的 Map 属性绑定语法,表示把值放进 ActionForm 的 props Map 里,键为 xxx。

5.3 布局模板:两列一行

document_form.ftl:

<table class="tableEdit" style="width:580px;" cellspacing="0" border="0" cellpadding="0">
<#assign i = 0>
<#list form.fields as field>
    <#assign i = i + 1>
    <#if field_index % 2 = 0>
    <tr>
    </#if>
        <td class="tdEditLabel">${field.fieldLabel}</td>
        <td class="tdEditContent"><#include "${field.fieldInput.template}"></td>
    <#if i = 2 || !field_has_next>
    <#assign i = 0>
    </tr>
    </#if>
</#list>
</table>

要点:

  • <#include "${field.fieldInput.template}"> —— 模板名来自数据,这就是"动态"的关键:同一个布局模板,因为每个域的 fieldInput.template 不同,渲染出文本框/下拉框/文件上传。
  • field_index 是 Freemarker 的循环索引变量,field_has_next 判断是否最后一个,两者配合实现"每行两个字段"。

5.4 包装成 EL 函数供 JSP 使用

public class DynaFormFunction {
    private static FormManager formManager;

    public static String form(int workflowId) {
        FlowForm form = formManager.findForm(workflowId);
        if (form == null) return "";
        try {
            Template template = FreemarkerManager.getConfiguration().getTemplate(form.getTemplate());
            Map root = new HashMap();
            root.put("form", form);
            Writer out = new StringWriter();
            template.process(root, out);
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public void setFormManager(FormManager formManager) { DynaFormFunction.formManager = formManager; }
}

JSP 里一行搞定:

<form action="document.do?method=add" method="post" enctype="multipart/form-data">
    <input name="title">
    <input name="description">
    ${my:form(workflowId)}      <%-- 动态表单部分 --%>
    <input type="submit" value="提交">
</form>

enctype="multipart/form-data" 必须有,否则文件上传拿不到字节。


六、接收提交:Map 绑定 + 类型转换

ActionForm 侧:

public class DocumentActionForm extends ActionForm {
    private Map props = new HashMap();     // 接收 props(xxx)
    public Map getProps()  { return props; }
    public void setProps(Map props) { this.props = props; }
}

Action 侧——按表单定义的类型把原始值转成目标类型:

public ActionForward add(ActionMapping mapping, ActionForm form, ...) {
    DocumentActionForm daf = (DocumentActionForm) form;
    Document document = new Document();
    BeanUtils.copyProperties(document, daf);

    if (daf.getProps().isEmpty()) {
        document.setProps(null);
    } else {
        FlowForm flowForm = formManager.findForm(daf.getWorkflowId());
        if (flowForm == null) {
            document.setProps(null);
        } else {
            Map documentProps = new HashMap();
            Set fields = flowForm.getFields();

            for (Iterator iter = fields.iterator(); iter.hasNext();) {
                FormField field = (FormField) iter.next();
                String propertyName = field.getFieldName();
                FieldType propertyType = field.getFieldType();

                Object source = daf.getProps().get(propertyName);   // 界面传来的原始值
                Object target = null;

                if (source != null) {
                    // 情形一:普通字符串,按 FieldType 转成目标类型
                    if (source instanceof String
                            && !propertyType.getType().equals("java.io.File")) {
                        Class targetClass = Class.forName(propertyType.getType());
                        target = ConvertUtils.convert((String) source, targetClass);
                    }

                    // 情形二:文件上传,Struts 已封装成 FormFile
                    if (propertyType.getType().equals("java.io.File")) {
                        FormFile ff = (FormFile) source;
                        target = ff.getFileData();      // 取字节数组
                    }

                    if (target == null) {
                        throw new SystemException("无法处理输入的值!");
                    }

                    // 按类型放进 DocumentProperty 对应的字段
                    DocumentProperty dp = new DocumentProperty();
                    String type = propertyType.getType();
                    if (type.equals("java.io.File")) {
                        dp.setJava_io_File((byte[]) target);
                    } else if (type.equals("java.lang.Integer")) {
                        dp.setJava_lang_Integer((Integer) target);
                    } else {
                        dp.setJava_lang_String((String) target);
                    }
                    documentProps.put(propertyName, dp);
                }
            }
            document.setProps(documentProps);
        }
    }

    documentManager.addDocument(document, daf.getWorkflowId(), currentUser(request).getId());
    return mapping.findForward("pub_add_success");
}

三步走总结:

props(money) ──> ActionForm.props["money"] = "50000"      (Struts Map 绑定)
                        │
                        ├─ 查表单定义:money 的类型是 java.lang.Integer
                        ├─ ConvertUtils.convert("50000", Integer.class)
                        └─ DocumentProperty.java_lang_Integer = 50000
                                │
                                └─> document.props["money"]  → T_Document_Properties

七、表单值如何参与流程判断

存进去的值最终会被 CopyPropertiesActionHandler 拷进 jBPM 流程变量,供 #{money gt 10000} 这样的表达式使用(详见《公文流转与 jBPM 工作流》)。完整链路:

表单定义(FlowForm/FormField)
   ↓ 渲染
页面输入框 props(money)
   ↓ Struts 绑定 + ConvertUtils 转换
Document.props["money"] → DocumentProperty
   ↓ 持久化
T_Document_Properties 表
   ↓ CopyPropertiesActionHandler(进入节点时)
jBPM 流程变量 money
   ↓ 条件表达式求值
决定流程走向

八、扩展思路

需求 做法
增加日期类型 加 FieldType(type="java.util.Date") + date.ftl + UtilDateConverter 已支持
字段校验(必填、范围) 在 FormField 上加 required、minValue、maxValue、regex 字段,渲染时输出校验属性,提交时服务端校验
表单版本管理 FlowForm 增加 version 字段,公文记录所用的表单版本
按字段查询 值已在独立列,可直接 where java_lang_Integer > 10000;或建立物化视图
改成 JSON 存储 用 Map<String,String> + valueType 列,牺牲强类型换取灵活性

九、小结

动态表单的本质是把"结构"变成数据:

  • 结构存元数据:FlowForm → FormField → FieldInput/FieldType/FieldItem
  • 渲染靠模板:Freemarker 的 <#include "${field.fieldInput.template}"> 让不同输入形式复用同一布局
  • 输入靠约定:props(xxx) 命名 + Struts Map 绑定
  • 存储靠分列:DocumentProperty 按类型分三列,保证强类型
  • 流转靠注入:值被拷进流程变量后即可驱动条件分支

这套思路即便放到今天的低代码平台里,也依然成立。

要点小结

  • | 方案 | 做法 | 问题 | |---|---|---| | 每类公文一张表 | T_LeaveForm、T_ExpenseForm … | 新增流程就要建表、写…
  • 更通用的做法是加一个 value_type 列 + 一个 value 列,或用 JSON 字段。
  • 表单的值有三个可能类型,不能塞进同一列

由站内小编编辑整理

相关条目