可以使用<f:ajax>
JSF 2 附带的标记来完成此任务,本教程对此进行了很好的说明。第一个示例向您展示了如何完成手头的任务。另一个建议是对@ViewScoped
托管 bean 使用注释,如 BalusC 博客文章所述:JSF 2.0 中的通信 - 托管 bean 范围。
有了所有这些信息和您正在使用的托管 bean,演示可能是:
客户类
public class Customer {
private int customer_id;
private String name;
//constructor, getters and setters...
}
ReservationHandler 托管 bean
@ManagedBean
@ViewScoped
public class ReservationHandler {
private Customer customer;
//this EJB will retrieve the Customer data
//if you don't have it like this, then use your own
//custom CustomerService class/implementation to retrieve the data from dabatase
@EJB
private CustomerService customerService;
//constructor, getters and setters...
@PostConstruct
public void init() {
customer = new Customer();
}
public void showCustomerDataListener(AjaxBehaviorEvent event) {
Customer customerFromDB =
customerService.getCustomer(customer.getCustomer_id());
if (customerFromDB != null) {
customer = customerFromDB;
}
}
}
客户 Facelets 视图(只是相关代码)
<h:form>
<h:outputText value="Customer ID:" />
<h:inputText id="customer_id"
value="#{reservationHandler.customer.customer_id}">
<f:ajax event="blur"
listener="#{reservationHandler.showCustomerDataListener}"
render="customer_name" />
</h:inputText>
<h:outputText value="Customer name:" />
<h:inputText id="customer_name"
value="#{reservationHandler.customer.name}" />
</h:form>
如果您的Customer
班级拥有超过 1 个属性,您有两种选择:
render
在组件的属性中设置每个输入的ID <f:ajax>
,但这很幼稚。
将所有组件与一个组合UIContainer
并呈现此 UIContainer。假设Customer
该类具有附加private String address
属性的示例:
<h:form>
<h:outputText value="Customer ID:" />
<h:inputText id="customer_id"
value="#{reservationHandler.customer.customer_id}">
<f:ajax event="blur"
listener="#{reservationHandler.showCustomerDataListener}"
render="customerData" />
</h:inputText>
<h:panelGrid id="customerData" columns="2">
<h:outputText value="Customer name:" />
<h:inputText id="customer_name"
value="#{reservationHandler.customer.name}" />
<h:outputText value="Address:" />
<h:inputText id="customer_address"
value="#{reservationHandler.customer.address}" />
</h:panelGrid>
</h:form>
了解应用支持的事件<f:ajax event="what_to_write_here">
,请参考f:ajax JSF Core Tag Reference,事件标签属性说明:
将调用 Ajax 请求的事件,例如“click”、“change”、“blur”、“keypress”等。该事件必须由启用 Ajax 行为的组件支持。注意:事件名称与没有“on”前缀的 DOM 事件名称相同,因此对于“onclick”事件,正确的事件名称是“click”。h:commandButton、h:commandLink等命令组件支持“action”事件,h:inputText、h:selectOneMenu等输入组件支持“valueChange”事件。