使用列表和复选框的Spring MVC数据绑定 [英] Spring MVC databinding using lists and checkboxes

查看:94
本文介绍了使用列表和复选框的Spring MVC数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有关此问题的问题已经提出,但是我发现的答案都没有解决我的问题.

I know questions on this matter have been asked already, but none of the answers I found solved my problem.

我的数据库上有多对多的关系.我正在使用JPA和Hibernate创建和更改表.这是我的模型类:

I have a many-to-many relantionship on my database. I'm using JPA and Hibernate to create and alter my tables. Here are my model classes:

Book.java

Book.java

@Entity
@Table(name="tb_books")
public class Book implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false, insertable = false)
    private Integer id;

    @Column(name = "title", nullable = false, length = 255)
    private String title;

    @Column(name = "author", nullable = false, length = 255)
    private String author;

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
    @JoinTable(name = "book_tag",
               joinColumns = { @JoinColumn(name = "fk_book") },
               inverseJoinColumns = { @JoinColumn(name = "fk_tag") })
    private List<Tag> tags;

    //getters, setters, equals and hash methods...

}

Tag.java

@Entity
@Table(name="tb_tags")
public class Tag implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Integer id;

    @Column(name = "description", nullable = false, length = 255)
    private String description;

    //getters, setters, equals and hash methods...
}

我正在尝试使用Spring MVC使用来自JSP的数据在book_tag表中进行插入和更新.这是我的控制器和插入页面:

I'm trying to make insertions and updates on my book_tag table with the data comming from a JSP using Spring MVC. Here is my controller and insertion page:

BookController.java

BookController.java

@Controller
@RequestMapping(value = "/book")
public class BookController {

    @Autowired
    private BookService bookService;

    /*
        Controller method that gets us to the adding book page. 
    */    
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView addBookPage() {

        List<Tag> tags = tagService.getTags(); //all tags from the database

        ModelAndView modelAndView = new ModelAndView("form-book");
        modelAndView.addObject("book", new Book());
        modelAndView.addObject("tags", tags);

        return modelAndView;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ModelAndView addBookProcess(@ModelAttribute Book book) {

        bookService.addBook(book);
        return new ModelAndView("redirect:/book/add");
    }

    //...

}

form-b​​ook.jsp

form-book.jsp

<form:form method="POST" modelAttribute="book" action="${pageContext.request.contextPath}/book/add.html">
<table>
    <tbody>
        <tr>
            <td>Title:</td>
            <td><form:input path="title" autocomplete="off" /></td>
        </tr>
        <tr>
            <td>Author:</td>
            <td><form:input path="author" autocomplete="off" /></td>
        </tr>
        <tr>
            <td colspan="2">

                <form:checkboxes path="tags" 
                items="${tags}" 
                itemLabel="description"
                itemValue="id"/>

            </td>
        </tr>
        <tr>
            <td><input type="submit" value="Add" /></td>
            <td><input type="button" onclick="location.href = '${pageContext.request.contextPath}/index'" value="Cancel"/></td>
        </tr>
    </tbody>
</table>

</form:form>

一切正常,除非我尝试选择一个或多个复选框更新或插入书籍.当我尝试这样做时,我会得到一个错误请求"页面,我想是因为我在处理数据绑定时做错了什么.

Everything is working fine, except when I try to update or insert books with one or more checkboxes selected. When I try to do so, I just get a "Bad Request" page, I imagine because of something wrong I'm doing concerning databinding.

这是我应该处理这种情况的方式吗?有没有更好的办法?我在做什么错了?

Is this the way I'm supposed to handle this situation? Is there a better way? What am I doing wrong?

推荐答案

很明显,从复选框发出的列表实际上是一个字符串数组,无法将其转换为定义模型类的标签列表.

Apparently, the List comming from the checkbox was actually an array of Strings, which could not be converted to a List of Tags, as defined the model classes.

我通过创建一个自定义的PropertyEditor解决了我的问题,这使我可以将复选框与标签列表绑定.

I solved my problem by creating a custom PropertyEditor, which would allow me to bind the checkboxes with the list of tags.

public class TagPropertyEditor extends PropertyEditorSupport {

    private TagService tagService;

    public TagPropertyEditor(TagService tagService){
        this.tagService = tagService;
    }

    @Override
    public String getAsText() {
        return ((Tag) getValue()).getId().toString();
    }

    @Override
    public void setAsText(String incomingId) throws IllegalArgumentException {
        Tag tag = tagService.getTag(Integer.valueOf(incomingId));
        setValue(tag);
    }
}

然后在我的BookController上注册:

And then registering on my BookController:

//...
@InitBinder
public void initBinder(WebDataBinder binder){
    binder.registerCustomEditor(Tag.class, new TagPropertyEditor(tagService));
}

这是我的JSP上的checboxes标记:

And this is the checboxes tag on my JSP:

 <form:checkboxes path="tags" 
                  items="${tags}"
                  itemLabel="description"
                  itemValue="id"/>

这篇关于使用列表和复选框的Spring MVC数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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