I would like to create a new entity instance in my jsf, bind the input values to the properties and pass the entire object to a method. Unfortunately, I am not able to create a new instance of an entity or bind the values to the properties in jsf. I created a small example to explain my issue:
The managed bean BookCatalogBean
is a kind of controller and work as interface between view and model. The method getNewBook
create a new instace of Book
. The input values in the jsf should be bind to this object.
@ManagedBean
@SessionScoped
public class BookCatalogBeanimplements Serializable {
private List<Book> availableBooks = new ArrayList<Book>();
public BookCatelogBean() {
this.availableBooks.add(new Book(0, "Title", "Author"));
}
public Book getNewBook() {
return new Book(this.getNewId());
}
public void add(Book book) {
}
public void update(Book book) {
}
public void delete(Book book) {
}
private long getNewId() {
return this.availableBooks.stream().max(Comparator.comparing(x -> x.getId())).get().getId() + 1;
}
}
In my view I would like to reuse the new instance of Book
and bind the input values to the properties of the object. I tried to create a new instance with <c:set />
but this did not work. My managed bean or method bookCatelogBean.add
always receives an object with an empty (null) title
and author
.
<h:form class="form">
<ul>
<li>
<span>
<!-- Create and use a new instance ob `Book` -->
<h:inputText value="#{newBook.title}" a:placeholder="Title"/>
<h:inputText value="#{newBook.author}" a:placeholder="Autor"/>
</span>
</li>
<li>
<span>
<h:commandButton value="Submit" action="#{bookCatelogBean.add(newBook)}"/>
</span>
</li>
</ul>
</h:form>
How could I create a new instance of Book
in my jsf and bind the input values to it? What I am doing wrong?
I am aware, that I can turn the entity Book
into a managed bean with requested scope to create a single object per request, but I need multiple objects per request at different places. If I use Book
with requested scope every var="book"
has the same value.