MyEclipse開(kāi)發(fā)JSF之創(chuàng)建Managed Beans淺析
MyEclipse開(kāi)發(fā)JSF三.創(chuàng)建Message Bundle
Message Bundle文件是一個(gè)簡(jiǎn)單的屬性文件,存儲(chǔ)與keys相關(guān)的消息,提供國(guó)際化支持,也可以用在JSP頁(yè)面中。Struts也提供了類(lèi)似的文件ApplicationResources.properties。
在JSF中,可以在頁(yè)面中加載message bundle使用如下代碼:﹤f:loadBundle basename="com.jsfdemo.MessageBundle" var= "bundle"/﹥
在創(chuàng)建message bundle文件之前,在src文件中通過(guò)右鍵選擇“New ﹥ Package”來(lái)創(chuàng)建com.jsfdemo包。使用新鍵文件向?qū)?lái)創(chuàng)建message bundle文件,如圖3.1:
MyEclipse開(kāi)發(fā)JSF圖1
Figure 3.1: Creating the Message Bundle file
創(chuàng)建完MessageBundle.properties文件以后,要添加在JSP頁(yè)面顯示的每個(gè)標(biāo)簽的key/value對(duì)或者是文本字符串??梢詮?fù)制下面中的內(nèi)容到message bundle文件中。
MessageBundle.properties
user_name_label=User Name:
user_password_label=Password:
login_button_label=Login
MessageBundle.properties文件的內(nèi)容
MessageBundle文件創(chuàng)建完以后,下一步,我們要?jiǎng)?chuàng)建ManagedBean以處理用戶登錄。
MyEclipse開(kāi)發(fā)JSF四.創(chuàng)建 Managed Beans
這部分我們將創(chuàng)建Managed Beans來(lái)執(zhí)行l(wèi)ogin操作,在這個(gè)Demo中,登錄操作就是簡(jiǎn)單的核對(duì)用戶名和密碼是否都是myeclipse,并將頁(yè)面轉(zhuǎn)向到userLoginSuccess.jsp。
首先用MyEclipse JSF Editor打開(kāi)faces-config.xml文件
MyEclipse開(kāi)發(fā)JSF圖2
Figure 4.1: Opening faces-config.xml file for editing
點(diǎn)擊右上角的Add ManagedBean來(lái)添加新的bean,如圖所示:
MyEclipse開(kāi)發(fā)JSF圖3
Figure 4.2: Launch the ManagedBean wizard from the Outline View
點(diǎn)擊以后出現(xiàn)新的Managed Bean向?qū)?,如圖所示添加值
MyEclipse開(kāi)發(fā)JSF圖4
Figure 4.3: Setup the new ManagedBean's class and properties
MyEclipse開(kāi)發(fā)JSF圖5
Figure 4.4: Managed Bean Wizard Final Page
點(diǎn)擊完成以后,發(fā)現(xiàn)在Outline View中新增加了一個(gè)UserBean.
MyEclipse開(kāi)發(fā)JSF圖6
Figure 4.5: UserBean now shown in the Outline View
UserBean.java的源代碼也出現(xiàn)在 java編輯器中。
MyEclipse開(kāi)發(fā)JSF圖7
Figure 4.6: UserBean Java source opened up in an editor
Username 和password的setters和getters方法已經(jīng)為我們產(chǎn)生了,接下來(lái)就是要在這個(gè)類(lèi)中增加一個(gè)方法loginUser來(lái)處理用戶登錄的操作。
代碼如下所示:
UserBean.java
- public String loginUser() ...{
- if("myeclipse".equals(getUserName()) && "myeclipse".equals(getPassword()))
- return "success";
- FacesContext facesContext = FacesContext.getCurrentInstance();
- FacesMessage facesMessage = new FacesMessage(
- "You have entered an invalid user name and/or password");
- facesContext.addMessage("loginForm", facesMessage);
- return "failure";
- }
我們注意到,UserBean類(lèi)沒(méi)有繼承任何JSF的類(lèi)或接口,它只是一個(gè)簡(jiǎn)單的JavaBean包括額外邏輯來(lái)執(zhí)行操作。他包括了類(lèi)似Struts中的Struts Form 和 Struts Action的功能,將二者集成到一個(gè)類(lèi)中.
另外,這些方法并沒(méi)有返回到指定的類(lèi),像Struts中的ActionForward那樣。
MyEclipse開(kāi)發(fā)JSF之創(chuàng)建Managed Beans就向你介紹到這里,那么之后我們將繼續(xù)向你介紹MyEclipse開(kāi)發(fā)JSF的其他步驟。
【編輯推薦】