【问题标题】:How to give <form:input path="{java.util.set}"> to set the modelAttribute value?如何给 <form:input path="{java.util.set}"> 设置 modelAttribute 值?
【发布时间】:2020-12-04 12:53:15
【问题描述】:

我有一个具有以下结构的模型:

class Person {
    private int id;
    private Set<Person> friends = new Set<Person>();
}

当我在&lt;form:form&gt; 中使用此类的modelAttribute 时,如何设置friends 属性的值?

请帮忙!

【问题讨论】:

    标签: spring jsp model-view-controller


    【解决方案1】:

    最初在您的 Model.java 文件中添加字段的 setter 和 getter,即 id 和 Friends。

    Model.java

    public class Person {
        private int id;
        Set<String> friends= new HashSet<String>();
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public Set<String> getFriends() {
            return friends;
        }
        public void setFriends(Set<String> friends) {
            this.friends = friends;
        }
    }
    

    那么在您的 PersonController 类代码中应该如下所示:

    PersonController

    @RequestMapping(value = "/savePerson", method = RequestMethod.POST)
    public String savePerson(@ModelAttribute("person") Person person){
        
        Person tempPerson = new Person();
        Set<String> frnd = new HashSet<String>();
        tempPerson.setId(person.getId());
        /* This code line depends on how you are planning to get the friends list from form and then add it to 'frnd' set by frnd.add() method and pass the set to following setter*/
        tempPerson.setFriends(frnd);
        personService.savePerson(tempPerson);
        return "redirect:/persons";
    }
    

    【讨论】:

    • 您好,感谢您回复我的帖子。我的问题是如何在 JSP 端映射这个模型属性?当我在
      中获取模型属性时,如何将 Set 设置为
    猜你喜欢
    • 2013-12-31
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-09
    • 2011-04-02
    • 2014-04-27
    • 2015-11-03
    相关资源
    最近更新 更多