这是我的表:
<h:dataTable var="book" value="#{ordersBean.userOrders}"
binding="#{ordersBean.htmlDataTable}">
<h:column>
<f:facet name="header">order ID</f:facet>
<h:outputText value="#{book[0]}"/>
</h:column>
<h:column>
<f:facet name="header">Book Title</f:facet>
<h:outputText value="#{book[1]}"/>
</h:column>
<h:column>
<f:facet name="header">Cost</f:facet>
<h:outputText value="#{book[2]}"/>
</h:column>
<h:column>
<f:facet name="header">Remove Order</f:facet>
<h:commandButton action="#{ordersBean.deleteOrder}" image="resources/images/del.gif"/>
</h:column>
</h:dataTable>
我需要获取用户点击其Order ID
图标的行Remove Order
,然后从DAO
删除该订单。
以下是deleteOrder()
:
@ManagedBean
@SessionScoped
public class OrdersBean {
private List<Book> userOrders = new ArrayList<Book>();
private HtmlDataTable htmlDataTable;
@Transactional
public void deleteOrder() {
Book selectedBook = (Book) htmlDataTable.getRowData(); // class cast exception (168)
}
//For populating table
@Transactional
public List<Book> userAllOrders() {
userOrders = bookDao.getTitleCostQty(String.valueOf(currentUser.getId())).list();
return userOrders;
}
public HtmlDataTable getHtmlDataTable() {
return htmlDataTable;
}
public void setHtmlDataTable(HtmlDataTable htmlDataTable) {
this.htmlDataTable = htmlDataTable;
}
//getter/setters
但是我收到了这个错误:
javax.servlet.ServletException: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.obs.model.Book
javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
javax.faces.el.EvaluationException: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.obs.model.Book
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.obs.model.Book
com.obs.bean.OrdersBean.deleteOrder(OrdersBean.java:168)
答案 0 :(得分:2)
你使用JSF 2.2吗?也许它从2.0开始有效......
所以你可以在commandButton中传递实际的书:
<h:commandButton actionListener="#{ordersBean.deleteOrder(book)}" ... />
并在bean中接收所选书籍作为参数:
public void deleteOrder(Book selectedBook) {
// ...
}
答案 1 :(得分:1)
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver()
{
IgnoreSerializableAttribute = true
}
};
, value="#{ordersBean.userOrders}"
应该是DataModel类型,包括模型类型的WrappedData以避免强制转换异常。请执行以下操作:
h:dataTable
现在,它不会通过任何强制转换异常:
private DataModel userOrders = new ListDataModel();
public DataModel getUserOrders() {
userOrders = new ListDataModel();
/* populate your list of Book in another list and setWrappedData for userOrders. */
List<Book> bookList = userAllOrders();
if (bookList != null && bookList.size() > 0){
userOrders.setWrappedData(bookList);
}
return bookList;
}
public void setUserOrders(DataModel userOrders) {
this.userOrders = userOrders;
}