jpa jsf
托管豆 這篇文章是本教程第1部分的繼續(xù)。
在“ com.mb”包中,您將需要?jiǎng)?chuàng)建以下類:
package com.mb;import org.primefaces.context.RequestContext;import com.util.JSFMessageUtil;public class AbstractMB {private static final String KEEP_DIALOG_OPENED = 'KEEP_DIALOG_OPENED';public AbstractMB() {super();}protected void displayErrorMessageToUser(String message) {JSFMessageUtil messageUtil = new JSFMessageUtil();messageUtil.sendErrorMessageToUser(message);}protected void displayInfoMessageToUser(String message) {JSFMessageUtil messageUtil = new JSFMessageUtil();messageUtil.sendInfoMessageToUser(message);}protected void closeDialog(){getRequestContext().addCallbackParam(KEEP_DIALOG_OPENED, false);}protected void keepDialogOpen(){getRequestContext().addCallbackParam(KEEP_DIALOG_OPENED, true);}protected RequestContext getRequestContext(){return RequestContext.getCurrentInstance();}
}package com.mb;import java.io.Serializable;
import java.util.List;import javax.faces.bean.*;import com.facade.DogFacade;
import com.model.Dog;@ViewScoped
@ManagedBean
public class DogMB extends AbstractMB implements Serializable {private static final long serialVersionUID = 1L;private Dog dog;private List<Dog> dogs;private DogFacade dogFacade;public DogFacade getDogFacade() {if (dogFacade == null) {dogFacade = new DogFacade();}return dogFacade;}public Dog getDog() {if (dog == null) {dog = new Dog();}return dog;}public void setDog(Dog dog) {this.dog = dog;}public void createDog() {try {getDogFacade().createDog(dog);closeDialog();displayInfoMessageToUser('Created With Sucess');loadDogs();resetDog();} catch (Exception e) {keepDialogOpen();displayErrorMessageToUser('Ops, we could not create. Try again later');e.printStackTrace();}}public void updateDog() {try {getDogFacade().updateDog(dog);closeDialog();displayInfoMessageToUser('Updated With Sucess');loadDogs();resetDog();} catch (Exception e) {keepDialogOpen();displayErrorMessageToUser('Ops, we could not create. Try again later');e.printStackTrace();}}public void deleteDog() {try {getDogFacade().deleteDog(dog);closeDialog();displayInfoMessageToUser('Deleted With Sucess');loadDogs();resetDog();} catch (Exception e) {keepDialogOpen();displayErrorMessageToUser('Ops, we could not create. Try again later');e.printStackTrace();}}public List<Dog> getAllDogs() {if (dogs == null) {loadDogs();}return dogs;}private void loadDogs() {dogs = getDogFacade().listAll();}public void resetDog() {dog = new Dog();}
}package com.mb;import java.io.Serializable;import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;import com.model.User;@SessionScoped
@ManagedBean(name='userMB')
public class UserMB implements Serializable {public static final String INJECTION_NAME = '#{userMB}';private static final long serialVersionUID = 1L;private User user;public boolean isAdmin() {return user.isAdmin();}public boolean isDefaultUser() {return user.isUser();}public String logOut() {getRequest().getSession().invalidate();return '/pages/public/login.xhtml';}private HttpServletRequest getRequest() {return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();}public User getUser() {return user;}public void setUser(User user) {this.user = user;}
}package com.mb;import java.io.Serializable;
import java.util.*;import javax.faces.bean.*;import com.facade.*;
import com.model.*;
import com.sun.faces.context.flash.ELFlash;@ViewScoped
@ManagedBean
public class PersonMB extends AbstractMB implements Serializable {private static final long serialVersionUID = 1L;private static final String SELECTED_PERSON = 'selectedPerson';private Dog dog;private Person person;private Person personWithDogs;private Person personWithDogsForDetail;private List<Dog> allDogs;private List<Person> persons;private DogFacade dogFacade;private PersonFacade personFacade;public void createPerson() {try {getPersonFacade().createPerson(person);closeDialog();displayInfoMessageToUser('Created With Sucess');loadPersons();resetPerson();} catch (Exception e) {keepDialogOpen();displayErrorMessageToUser('Ops, we could not create. Try again later');e.printStackTrace();}}public void updatePerson() {try {getPersonFacade().updatePerson(person);closeDialog();displayInfoMessageToUser('Updated With Sucess');loadPersons();resetPerson();} catch (Exception e) {keepDialogOpen();displayErrorMessageToUser('Ops, we could not create. Try again later');e.printStackTrace();}}public void deletePerson() {try {getPersonFacade().deletePerson(person);closeDialog();displayInfoMessageToUser('Deleted With Sucess');loadPersons();resetPerson();} catch (Exception e) {keepDialogOpen();displayErrorMessageToUser('Ops, we could not create. Try again later');e.printStackTrace();}}public void addDogToPerson() {try {getPersonFacade().addDogToPerson(dog.getId(), personWithDogs.getId());closeDialog();displayInfoMessageToUser('Added With Sucess');reloadPersonWithDogs();resetDog();} catch (Exception e) {keepDialogOpen();displayErrorMessageToUser('Ops, we could not create. Try again later');e.printStackTrace();}}public void removeDogFromPerson() {try {getPersonFacade().removeDogFromPerson(dog.getId(), personWithDogs.getId());closeDialog();displayInfoMessageToUser('Removed With Sucess');reloadPersonWithDogs();resetDog();} catch (Exception e) {keepDialogOpen();displayErrorMessageToUser('Ops, we could not create. Try again later');e.printStackTrace();}}public Person getPersonWithDogs() {if (personWithDogs == null) {if (person == null) {person = (Person) ELFlash.getFlash().get(SELECTED_PERSON);}personWithDogs = getPersonFacade().findPersonWithAllDogs(person.getId());}return personWithDogs;}public void setPersonWithDogsForDetail(Person person) {personWithDogsForDetail = getPersonFacade().findPersonWithAllDogs(person.getId());}public Person getPersonWithDogsForDetail() {if (personWithDogsForDetail == null) {personWithDogsForDetail = new Person();personWithDogsForDetail.setDogs(new ArrayList<Dog>());}return personWithDogsForDetail;}public void resetPersonWithDogsForDetail(){personWithDogsForDetail = new Person();}public String editPersonDogs() {ELFlash.getFlash().put(SELECTED_PERSON, person);return '/pages/protected/defaultUser/personDogs/personDogs.xhtml';}public List<Dog> complete(String name) {List<Dog> queryResult = new ArrayList<Dog>();if (allDogs == null) {dogFacade = new DogFacade();allDogs = dogFacade.listAll();}allDogs.removeAll(personWithDogs.getDogs());for (Dog dog : allDogs) {if (dog.getName().toLowerCase().contains(name.toLowerCase())) {queryResult.add(dog);}}return queryResult;}public PersonFacade getPersonFacade() {if (personFacade == null) {personFacade = new PersonFacade();}return personFacade;}public Person getPerson() {if (person == null) {person = new Person();}return person;}public void setPerson(Person person) {this.person = person;}public List<Person> getAllPersons() {if (persons == null) {loadPersons();}return persons;}private void loadPersons() {persons = getPersonFacade().listAll();}public void resetPerson() {person = new Person();}public Dog getDog() {if (dog == null) {dog = new Dog();}return dog;}public void setDog(Dog dog) {this.dog = dog;}public void resetDog() {dog = new Dog();}private void reloadPersonWithDogs() {personWithDogs = getPersonFacade().findPersonWithAllDogs(person.getId());}
}package com.mb;import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;import com.facade.UserFacade;
import com.model.User;@RequestScoped
@ManagedBean
public class LoginMB extends AbstractMB {@ManagedProperty(value = UserMB.INJECTION_NAME)private UserMB userMB;private String email;private String password;public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String login() {UserFacade userFacade = new UserFacade();User user = userFacade.isValidLogin(email, password);if(user != null){userMB.setUser(user);FacesContext context = FacesContext.getCurrentInstance();HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();request.getSession().setAttribute('user', user);return '/pages/protected/index.xhtml';}displayErrorMessageToUser('Check your email/password');return null;}public void setUserMB(UserMB userMB) {this.userMB = userMB;}
}
關(guān)于上面的代碼:
所有ManagedBeans僅負(fù)責(zé)VIEW操作; ManagedBeans應(yīng)該負(fù)責(zé)處理業(yè)務(wù)方法的唯一結(jié)果。 ManagedBeans中沒(méi)有業(yè)務(wù)規(guī)則。 在視圖層中執(zhí)行一些業(yè)務(wù)操作非常容易,但這不是一個(gè)好習(xí)慣。 LoginMB類使用另一個(gè)ManagedBean(UserMB),并在其中注入了它。 要將一個(gè)ManagedBean注入另一個(gè)ManagedBean中,您必須執(zhí)行以下操作: 在注入的ManagedBean的頂部使用@ManagedProperty PersonMB類可能會(huì)因?yàn)槠涮蠖邮苤貥?gòu)操作。 這樣的PersonMB可以使新手開發(fā)人員更輕松地理解代碼。 關(guān)于@ViewScoped的觀察 您將在帶有@ViewScoped批注的托管bean中看到一些重新加載和重置方法。 這兩種方法都需要重置對(duì)象狀態(tài)。 例如,狗對(duì)象將在方法執(zhí)行后保存視圖中的值(持久保存在數(shù)據(jù)庫(kù)中,在對(duì)話框中顯示值)。 如果用戶打開創(chuàng)建對(duì)話框并成功創(chuàng)建狗,則該狗對(duì)象將在用戶停留在同一頁(yè)面時(shí)保留所有值。 如果用戶再次打開創(chuàng)建對(duì)話框,則將在此處顯示最后記錄的狗的所有數(shù)據(jù)。 這就是為什么我們有重置方法的原因。
如果更新數(shù)據(jù)庫(kù)中的對(duì)象,則用戶視圖中的對(duì)象也必須接收此更新,ManagedBean對(duì)象也必須接收此新數(shù)據(jù)。 如果您在數(shù)據(jù)庫(kù)中更新了狗名,則狗列表也應(yīng)收到此更新的狗。 您可以在數(shù)據(jù)庫(kù)中查詢此新數(shù)據(jù),也可以僅更新托管Bean值。
開發(fā)人員必須注意:
重新加載查詢數(shù)據(jù)庫(kù)的托管Bean數(shù)據(jù)(重新加載方法) :如果重新加載ManagedBean對(duì)象的激發(fā)查詢附帶大量數(shù)據(jù),則其查詢可能會(huì)影響應(yīng)用程序性能。 開發(fā)人員可以使用具有延遲加載的數(shù)據(jù)表。 單擊此處查看有關(guān)Lazy Datatable的更多信息 。 在不查詢數(shù)據(jù)庫(kù)的情況下,直接在托管Bean中重新加載更新的對(duì)象 :假設(shè)user1更新了數(shù)據(jù)庫(kù)中的dog1名稱,同時(shí)user2更新了dog2年齡。 如果user1更新dog2,則user1將看到有關(guān)dog2的舊數(shù)據(jù),這可能會(huì)導(dǎo)致數(shù)據(jù)庫(kù)完整性問(wèn)題。 該方法的解決方案可以是數(shù)據(jù)庫(kù)表中的版本字段。 在更新發(fā)生之前,將檢查此字段。 如果版本字段不具有數(shù)據(jù)庫(kù)中找到的相同值,則可能引發(fā)異常。 使用此方法,如果user1更新dog2,則版本值將不同。 JSFMessageUtil 在“ com.util”包中,創(chuàng)建以下類:
package com.util;import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.context.FacesContext;public class JSFMessageUtil {public void sendInfoMessageToUser(String message) {FacesMessage facesMessage = createMessage(FacesMessage.SEVERITY_INFO, message);addMessageToJsfContext(facesMessage);}public void sendErrorMessageToUser(String message) {FacesMessage facesMessage = createMessage(FacesMessage.SEVERITY_WARN, message);addMessageToJsfContext(facesMessage);}private FacesMessage createMessage(Severity severity, String mensagemErro) {return new FacesMessage(severity, mensagemErro, mensagemErro);}private void addMessageToJsfContext(FacesMessage facesMessage) {FacesContext.getCurrentInstance().addMessage(null, facesMessage);}
}
此類將處理將顯示給用戶的所有JSF消息。 此類將幫助我們的ManagedBeans失去類之間的耦合。
創(chuàng)建一個(gè)類來(lái)處理對(duì)話框動(dòng)作也是一個(gè)好主意。
配置文件 在源“ src”文件夾中,創(chuàng)建以下文件:
“ log4.properties ”
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n# Root logger option
log4j.rootLogger=ERROR, stdout# Hibernate logging options (INFO only shows startup messages)
log4j.logger.org.hibernate=ERROR# Log JDBC bind parameter runtime arguments
#log4j.logger.org.hibernate.type=TRACE
“ messages.properties ”
#Actions
welcomeMessage=Hello! Show me the best soccer team logo ever
update=Update
create=Create
delete=Delete
cancel=Cancel
detail=Detail
logIn=Log In
add=Add
remove=Remove
ok=Ok
logOut= Log Out
javax.faces.component.UIInput.REQUIRED={0}: is empty. Please, provide some value
javax.faces.validator.LengthValidator.MINIMUM={1}: Length is less than allowable minimum of u2018u2019{0}u2019u2019
noRecords=No data to display
deleteRecord=Do you want do delete the record#Login / Roles Validations
loginHello=Login to access secure pages
loginUserName=Username
loginPassword=Password
logout=Log Out
loginWelcomeMessage=Welcome
accessDeniedHeader=Wow, our ninja cat found you!
accessDeniedText=Sorry but you can not access that page. If you try again, that ninja cat gonna kick you harder! >= )
accessDeniedButton=You got-me, take me out. =/#Person
person=Person
personPlural=Persons
personName=Name
personAge=Age
personDogs=These dogs belongs to
personAddDogTo=Add the selected Dog To
personRemoveDogFrom=Remove the selected Dog from
personEditDogs=Edit Dogs#Dog
dog=Dog
dogPlural=Dogs
dogName=Name
dogAge=Age
看一下“ lo4j.properties ”,注釋#log4j.logger.org.hibernate.type = TRACE 行。 如果要查看由Hibernate創(chuàng)建的查詢,則需要將文件的其他配置從ERROR編輯為DEBUG,并從上面的行中刪除#。
您將能夠看到Hibernate執(zhí)行的查詢及其參數(shù)。
xhtml頁(yè)面,面 在WebContent文件夾中,您將找到以下文件:
讓我們看看如何將Facelets應(yīng)用于項(xiàng)目。 在“ / WebContent / pages / protected / templates /”文件夾下創(chuàng)建以下文件:
“ left.xhtml ”
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html xmlns='http://www.w3.org/1999/xhtml'xmlns:ui='http://java.sun.com/jsf/facelets'xmlns:h='http://java.sun.com/jsf/html'xmlns:p='http://primefaces.org/ui'><h:body><ui:composition><h:form><p:commandButton styleClass='menuButton' icon='ui-icon-arrowstop-1-e' rendered='#{userMB.admin or userMB.defaultUser}' action='/pages/protected/defaultUser/defaultUserIndex.xhtml' value='#{bundle.personPlural}' ajax='false' immediate='true' /><br /><p:commandButton styleClass='menuButton' icon='ui-icon-arrowstop-1-e' rendered='#{userMB.admin}' action='/pages/protected/admin/adminIndex.xhtml' value='#{bundle.dogPlural}' ajax='false' immediate='true' /><br /></h:form></ui:composition>
</h:body>
</html>
“ master.xhtml ”
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html xmlns='http://www.w3.org/1999/xhtml'xmlns:ui='http://java.sun.com/jsf/facelets'xmlns:h='http://java.sun.com/jsf/html'xmlns:p='http://primefaces.org/ui'xmlns:f='http://java.sun.com/jsf/core'><h:head><title>CrudJSF</title><h:outputStylesheet library='css' name='main.css' /><meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
</h:head><h:body><f:view contentType='text/html; charset=UTF-8' encoding='UTF-8' ><div id='divTop' style='vertical-align: middle;'><ui:insert name='divTop'><ui:include src='top.xhtml' /></ui:insert></div><div id='divLeft'><ui:insert name='divLeft'><ui:include src='left.xhtml' /></ui:insert></div><div id='divMain'><p:growl id='messageGrowl' /><ui:insert name='divMain' /></div><h:outputScript library='javascript' name='jscodes.js' /></f:view>
</h:body>
</html>
“ top.xhtml”
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html xmlns='http://www.w3.org/1999/xhtml'xmlns:ui='http://java.sun.com/jsf/facelets'xmlns:h='http://java.sun.com/jsf/html'xmlns:p='http://primefaces.org/ui'><h:body> <ui:composition><div id='topMessage'><h1><h:form>#{bundle.loginWelcomeMessage}: #{userMB.user.name} | <p:commandButton value='#{bundle.logOut}' action='#{userMB.logOut()}' ajax='false' style='font-size: 20px;' /></h:form></h1></div></ui:composition> </h:body>
</html>
上面的代碼將成為該應(yīng)用程序所有xhtml頁(yè)面的基礎(chǔ)。 應(yīng)用Facelets模式以重用xhtml代碼非常重要。 在下面,您可以在xhtml頁(yè)面中看到如何應(yīng)用Facelets,請(qǐng)注意,開發(fā)人員只需要覆蓋所需的部分:
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' xmlns:ui='http://java.sun.com/jsf/facelets' xmlns:h='http://java.sun.com/jsf/html'xmlns:f='http://java.sun.com/jsf/core' xmlns:p='http://primefaces.org/ui' >
<h:body><ui:composition template='/pages/protected/templates/master.xhtml'><ui:define name='divMain'>#{bundle.welcomeMessage} :<br/><h:graphicImage library='images' name='logoReal.png' /></ui:define> </ui:composition>
</h:body>
</html>
請(qǐng)注意,只有“ divMain ”被覆蓋,其他部分保持不變。 這是Facelets的最大優(yōu)勢(shì),您無(wú)需在每個(gè)頁(yè)面中使用網(wǎng)站的所有區(qū)域。
繼續(xù)第三部分 。
參考: 在uaiHebert博客上,來(lái)自我們的JCG合作伙伴 Hebert Coelho的Tomcat JSF Primefaces JPA Hibernate完整Web應(yīng)用程序 。
翻譯自: https://www.javacodegeeks.com/2012/07/full-web-application-tomcat-jsf_04.html
jpa jsf
總結(jié)
以上是生活随笔 為你收集整理的jpa jsf_完整Web应用程序Tomcat JSF Primefaces JPA Hibernate –第2部分 的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔 網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔 推薦給好友。