2010-06-30 21 views

回答

1

这显然是可能的,如果我理解正确的,你......

型号

public class Foo() { 
    private String result; 
    public String getResult() { return result; } 
    public void setResult(String result) { this.result = result; } 
} 

控制器

这是使用注解。如果你不明白这是什么,你应该查看Spring文档。 @ModelAttribute("fooResults")将可供您的视图用于您的下拉元素。 @ModelAttribute("command") Foo foo将自动“吸取”您在下拉列表中选择的任何内容。

@Controller 
public class FooController() { 

    @ModelAttribute("fooResults") 
    public List<String> fooResults() { 
     // return a list of string 
    } 

    @RequestMapping(method = RequestMethod.GET) 
    public String get(@ModelAttribute("command") Foo foo) { 
     return "fooView"; 
    } 

    @RequestMapping(method = RequestMethod.POST) 
    public String post(@ModelAttribute("command") Foo foo) { 
     // do something with foo 
    } 

查看

使用表单标签库的魔力,可以绑定一个下拉(在form:select)对模型结果的财产,并填充与fooResults的项目。

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> 

<form:form commandName="command"> 
    <form:select path="result"> 
     <form:options items="${fooResults}" itemLabel="result" itemValue="result"/> 
    </form:select> 
    <input type="submit" value="submit"/> 
</form> 

这一切都假定你有种知道你在做什么:)如果你不这样做,检查出http://static.springsource.org/docs/Spring-MVC-step-by-step/

+0

这是行不通的,至少在2.5版本。我们需要制作自定义属性编辑器,如下所示ans – 2012-04-25 08:24:57

1

这篇文章解释了你想要做什么:http://blogs.credera.com/2009/01/22/spring-mvc-custom-property-editors/。我花了很长时间寻找完全相同的问题,并且在Credera上的AJ Angus有我在网上看到的最好的解释。总之,你必须告诉Spring如何将select标签上的字符串形式选项值转换回对象。这是通过将项目值作为对象的ID来完成的: 所以Spring现在拥有员工的ID,但是当用户单击提交时,Spring如何将ID更改回员工?这是PropertyEditor的手段,这Spring文档没有很好地解释:

public class EmployeeNamePropertyEditor extends PropertyEditorSupport { 
EmployeeDAO employeeDAO; 

public EmployeeNamePropertyEditor(EmployeeDAO employeeDAO) { 
    this.employeeDAO = employeeDAO; 
} 

public void setAsText(String text) { 
    Employee employee = new Employee(); 
    employee = employeeDAO.getEmployee(Long.parseLong(text)); 
    setValue(employee); 
} 
} 

然后使用initBinder,让控制器知道属性编辑器存在:

@InitBinder 
public void initBinder(WebDataBinder binder) { 
    binder.registerCustomEditor(Employee.class, new   
    EmployeeNamePropertyEditor(employeeDAO)); 
} 

那么你就完全组!查看更好更详细的解释链接。

+0

它的功能就像一个魅力 – 2012-04-25 08:23:38

相关问题