需要帮助绑定使用Spring MVC窗体 [英] Need help with binding Set with Spring MVC form

查看:139
本文介绍了需要帮助绑定使用Spring MVC窗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试最近3天仍然无法解决我的问题。



我有个人课程


$ b $
$ b @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY,mappedBy =person)
@ JoinColumn(name =person_id)
public Set< Book> books = new HashSet< Book>();

class Book

book_id
person_id

在我的JSP表单中,我有

 < c:forEach items =$ {BookList}var =var1 varStatus =counter> 
< input type =checkboxname =books [$ {counter.index}]。book_idvalue =$ {var1.book_id}> $ {var1.book_name}< / input>
< / c:forEach>

根据复选框,我将书籍插入表中
图书列表已填充来自refrenceData模型。



COntroller

  @RequestMapping(value = / persons / add,method = RequestMethod.GET)
public String getAdd(Model model){
logger.debug(Received request to show add page);

//创建新的人并添加到模型
//这是formBackingOBject
model.addAttribute(personAttribute,new Person());

//这将解析为/WEB-INF/jsp/addpage.jsp
返回hibernate / addpage;
}



@RequestMapping(value =/ persons / add,method = RequestMethod.POST)
public String add(@Valid @ ModelAttribute(personAttribute)Person person,BindingResult result){
logger.debug(Received request to add new person);

if(result.hasErrors())
返回hibernate / addpage;
else
personService.add(person);

//这将解析为/WEB-INF/jsp/addedpage.jsp
返回hibernate / addedpage;
}

现在如果我有单个Book对象,那么这样做可以,数据输入数据库,但如果我已经设置,那么它说无效的财产簿[1]



搜索了很多在SO和Google我le le我有两个选项

  PropertyEditor 
AutoPopulatingList


$ b $我不知道如何在我的情况下使用它们。任何人都可以帮助我,我必须使用它们以及如何使用它

解决方案

看这个问题在集合集合中绑定对象



您需要使用其他类型的集合。我建议使用列表而不是地图。当您从表单发送一个名称如下参数:

  name =books [0] .book_id

SpringMVC将查找名为books的属性(这是一个Set),然后它将尝试获取第一个元素通过做books.get(0)。 Set没有得到,因为Set没有订单。



为了实现列表,您可以使用AutoPopulatingList。这是一个惰性列表的实现,它将创建一个不存在的对象。例如,如果您调用书籍[0] .id,并且您没有在列表的位置0添加一本书,它将抛出NullPointerException,但是如果您使用AutoPopulatingList,它将创建一个新的Book并将其添加到该位置,如果该位置为空。

  public List< Book> books = new AutoPopulatingList< Book>(new ElementFactory< Book>(){
@Override
public Book createElement(final int index)throws ElementInstantiationException {
//根据需要调用构造函数
return new Book();
}
});

如果您要使用默认构造函数Book(即Book())进行实例化,你可以使用这样的语法:

  public List< Book> books = new AutoPopulatingList< Book>(Book.class); 


I have been trying for last 3 days still i am not able to solve my problem

I have Person Class

@SuppressWarnings("rawtypes")
 @OneToMany(cascade = CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="person")
 @JoinColumn(name="person_id")
 public Set<Book> books = new HashSet<Book>();

class Book

book_id
person_id

In my JSP form i have

<c:forEach items="${BookList}" var="var1" varStatus="counter">
     <input type="checkbox" name="books[${counter.index}].book_id" value="${var1.book_id}" >${var1.book_name}</input>
    </c:forEach>

I am inserting the books in table depending upon the check boxes The book list is populated from refrenceData model.

COntroller

@RequestMapping(value = "/persons/add", method = RequestMethod.GET)
    public String getAdd(Model model) {
        logger.debug("Received request to show add page");

        // Create new Person and add to model
        // This is the formBackingOBject
        model.addAttribute("personAttribute", new Person());

        // This will resolve to /WEB-INF/jsp/addpage.jsp
        return "hibernate/addpage";
    }



@RequestMapping(value = "/persons/add", method = RequestMethod.POST)
public String add(@Valid @ModelAttribute("personAttribute") Person person, BindingResult result) {
        logger.debug("Received request to add new person");

        if (result.hasErrors()) 
    return "hibernate/addpage";
        else
        personService.add(person);

    // This will resolve to /WEB-INF/jsp/addedpage.jsp
        return "hibernate/addedpage";
    }

Now if i have single Book object then this works ok and data is entered in DB but if i have set then it says invalid property book[1]

After searching a lot on SO and Google i leart that i have two option

PropertyEditor
AutoPopulatingList

I don't know how to use them in my case. Can anyone help me , where do i have to use them and how to use it

解决方案

Look at this question Bind objects in a Set collection

You need to use another type of Collection. I'd recommend to use a List instead of a Map. When you send from the form a parameter with a name like:

name="books[0].book_id"

SpringMVC will look in the property called books (which is a Set for you) and then it will try to get the first element by doing books.get(0). Set don't have a get because Set has not an order.

For the implementation of the list you can use AutoPopulatingList. It is an implementation of a lazy List which will create an object if it doesn't exist. For example if you invoke books[0].id and you haven't added a book in the position 0 of the list it will throw a NullPointerException, but if you use AutoPopulatingList it will create a new Book and addd it in that position if that position is empty.

public List<Book> books = new AutoPopulatingList<Book>(new ElementFactory<Book>() {
    @Override
    public Book createElement(final int index) throws ElementInstantiationException {
         //call the constructor as you need
         return new Book();
    }       
});

if you you are going to instanciate it with the default constructor of Book (that is Book()), you can use a syntax like this one:

public List<Book> books = new AutoPopulatingList<Book>(Book.class);

这篇关于需要帮助绑定使用Spring MVC窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆