时间:2011-08-09 IBM Richard Hightower
这个 CRUD 应用程序由以下元素组成:
ContactController:JSF 控制器
Contact:代表联系人信息的模型对象
ContactRepository:用来创建、读取、更新和删除 Contact 对象的模型对象
contacts.jsp:这个 JavaServer Pages(JSP)显示用来管理联系人的 JSF 组件
faces-config.xml:JSF 的配置,在这里将 ContactController 和 ContactRepository 声明为托管 bean,并将 ContactRepository 注入 ContactController
ContactController
ContactController 后端支持 contacts.jsp 页面。清单 1 给出了 ContactController 的代码:
清单 1. ContactController
package com.arcmind.contact.controller;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.component.UICommand;
import javax.faces.component.UIForm;
import javax.faces.context.FacesContext;
import com.arcmind.contact.model.Contact;
import com.arcmind.contact.model.ContactRepository;
public class ContactController {
/** Contact Controller collaborates with contactRepository. */
private ContactRepository contactRepository;
/** The current contact that is being edited. */
private Contact contact = new Contact();
/** Contact to remove. */
private Contact selectedContact;
/** The current form. */
private UIForm form;
/** Add new link. */
private UICommand addNewCommand;
/** Persist command. */
private UICommand persistCommand;
/** For injection of collaborator. */
public void setContactRepository(ContactRepository contactRepository) {
this.contactRepository = contactRepository;
}
public void addNew() {
form.setRendered(true);
addNewCommand.setRendered(false);
persistCommand.setValue("Add");
}
public void persist() {
form.setRendered(false);
addNewCommand.setRendered(true);
if (contactRepository.persist(contact) == null) {
addStatusMessage("Added " + contact);
} else {
addStatusMessage("Updated " + contact);
}
}
public void remove() {
contactRepository.remove(selectedContact);
addStatusMessage("Removed " + selectedContact);
}
public void read() {
contact = selectedContact;
form.setRendered(true);
addNewCommand.setRendered(false);
addStatusMessage("Read " + contact);
persistCommand.setValue("Update");
}
private void addStatusMessage(String message) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_INFO, message, null));
}
//most getter/setter omitted
}
清单 1 用不到 74 行代码创建了一个 CRUD GUI — 不算太麻烦。ContactController 在 request 范 围内管理,所以在实例化一个新的 ContactController 时,会创建一个新的 Contact。有三个组件绑定 到 ContactController:form(UIForm 类型)、addNewCommand(UICommand 类型)和 persistCommand (UICommand 类型)。
addNew |