下拉框 – 从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 ,似乎我应该使用 ,我试过这样:

someView.ftl:

  

所以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] ---------- 

我也尝试过:

  

这些方面还有更多的东西,但没有成功:

 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 options = Arrays.asList(getOptionsFromDatabaseAndConvertToStringList()); mav.addObject("options",options ); mav.setViewName("someview"); return mav; } 

第三

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

 <@spring.bind "options" /> 
<@spring.formSingleSelect "targetBean.choice", options, " " />

根据formSingleSelect的文档:

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

我认为最好的办法是提供一个地图,其中值为键,标签为地图值。 否则,freemarker可能会试图为你做包装,你的控制力会减少。

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