在Spring MVC中,我可以使用后备对象进行有状态下拉列表吗?

时间:2010-06-30 09:20:03

标签: java spring-mvc

在Spring MVC中,我希望有一个带有html下拉列表的表单,该表单由域对象列表支持,但只显示对象中的一个字段。提交表单时,我希望能够检索整个对象。我可以这样做吗?

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分:1)

这篇文章准确解释了您想要做的事情:https://www.credera.com/blog/technology-insights/java/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让控制器知道propertyEditor存在:

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

然后你就定了!查看链接以获得更好,更详细的解释。