繁体   English   中英

下拉框 - 从Spring MVC模型/上下文到使用freemarker形成

[英]Dropdown box - from Spring MVC model / context to form using 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由宏看起来自动绑定。

但是如何让我的选项进入freemarker seequence以便宏可以创建选项?

现在我得到:

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

谢谢你的帮助!

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

第一

我需要有一个豆子明显地保持我的选择

第二

这些选项需要初始化为String列表,并由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>

根据formSingleSelect的文档:

@param options a map (value=label) of all the available options

我认为最好的办法是提供一个地图,其中值为键,标签为地图值。 否则,freemarker可能会尝试为您进行包装,而您的控制力较弱。

我刚刚验证过:如果你提供自己的地图,一切都很好。

<spring.formSingleSelect "target.property" referenceToYourMapProvidedInController ""/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM