下拉框-从Spring MVC模型/上下文到使用freemarker的表单


问题内容

这应该是非常基本的,但是我在网上找不到任何有关它的信息,只是我似乎无法将它们拼凑在一起的点点滴滴。

我们正在使用带有freemarker的Spring
MVC。现在,我想在页面上添加一个表单,该表单允许我从预定义列表中选择一个值(需要在后端进行数据库访问)。

我的控制器:

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ModelAndView get(@PathVariable Integer id) {

    // stuff..
    ModelAndView mav = new ModelAndView();

    mav.addObject("targetObject", new TargetObject());
    mav.addObject("options", Arrays.asList("a", "b", "c"));
    mav.setViewName("someview");

    return mav;
}

我发现了freemarkers的spring支持spring.ftl,似乎我应该使用<@spring.formSingleSelect>尝试过的方法:

someView.ftl:

<#import "../spring.ftl" as spring />

<form action="somePath" method="POST">
    <@spring.formSingleSelect "targetObject.type", "options", " " />
    <input type="submit" value="submit"/>
</form>

因此targetObject.type似乎由宏自动绑定。

但是,如何使我的选项进入自由标记的可见性,以便宏可以创建选项?

现在我得到:

Expected collection or sequence. options evaluated instead to freemarker.template.SimpleScalar on line 227, column 20 in spring.ftl.
The problematic instruction:
----------
==> list options as value [on line 227, column 13 in spring.ftl]
 in user-directive spring.formSingleSelect [on line 53, column 9 in productBase/show.ftl]
----------

我也尝试过:

<@spring.bind "${options}" />

还有更多类似的事情,但没有成功:

freemarker.core.NonStringException: Error on line 48, column 18 in someView.ftl
Expecting a string, date or number here, Expression options is instead a freemarker.template.SimpleSequence

谢谢你的帮助!


问题答案:

经过多次改写和重新思考,我终于找到了解决方案:

第一

我显然需要选择一个豆子

第二

这些选项需要初始化为字符串列表,并由Spring MVC提供给页面:

public ModelAndView get() {

    // ...
    ModelAndView mav = new ModelAndView();
    List<String> options = Arrays.asList(getOptionsFromDatabaseAndConvertToStringList());
    mav.addObject("options",options );
    mav.setViewName("someview");

    return mav;
}

第三

options现在需要绑定在freemarker模板中,然后可以像其他任何freemarker变量一样访问(即, 不带 引号):

<@spring.bind "options" />

<form action="whatever" method="POST">
    <@spring.formSingleSelect "targetBean.choice", options, " " />
    <input type="submit" value="submit"/>
</form>