Full Web Application with Tomcat JSF Primefaces JPA Hibernate

98

Posted on June 21, 2012 by

Share it now!

ManagedBeans

In the “com.mb” package you will need to create the classes bellow:

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;
	}	
}

About the above code:

  • All ManagedBeans are responsible only for the VIEW actions; the ManagedBeans should be responsible to handle the only outcome of the business methods. There are no business rules in the ManagedBeans. It is very easy to do some business actions in the view layer but is not a good practice.
  • The LoginMB class uses another ManagedBean (UserMB) there were injected inside of it. To inject a ManagedBean inside another ManagedBean you must do as bellow:
    • Uses the @ManagedProperty on the top of the injected ManagedBean
    • Create a set method to the property like “loginMB.setUserMB(…)
  • The PersonMB class could receive refactoring actions because it is too big. The PersonMB is like that to make easer for rookie developers to understand the code faster.

Observations about @ViewScoped

You will see in the managed beans with the @ViewScoped annotation some reload and reset methods. Both methods are required to reset the objects state; e.g. a dog object would hold values from the view after a method execution (persist in the database, display values in a dialog).  If the user open de create dialog and successfully create a dog this dog object will hold all values while the user stays in the same page. If the user opens the create dialog again all the data of the last recorded dog will be displayed there. That is why we have the reset methods.

If you update an object in the database the object in the user view must receive this update too, the ManagedBean objects must receive this new data. If you updated a dog name in the database the list of dog should receive this updated dog too. You can query this new data in the database or just update the managed bean values.

A developer must be aware of:

  • Reload the managed bean data querying the database (the reload methods): if the fired query to reload the ManagedBean object comes with a huge amount of data his query may affect the application performance. A developer could use a datatable with lazy load. Click here to see more about Lazy Datatable.
  • Reload the updated object directly in the managed bean without querying the database: imagine that the user1 updates the dog1 name in the database and at the same time user2 updates the dog2 age. The user1 will see the old data about the dog2 that could cause a database integrity issue if the user1 updates the dog2. A solution to this approach could be a version field in the database table. Before the update takes place this field would be checked. If the version field does not hold the same value found in the database an exception could be raised. With this approach if the user1 updates the dog2 the version value would not be the same.

Response to Full Web Application with Tomcat JSF Primefaces JPA Hibernate

1 4 5 6
  1. Kg

    Dear day Sir, nice tutorial but i am getting this error

    javax.faces.el.EvaluationException: java.lang.ExceptionInInitializerError
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
    at co.za.jmr.healthproj.filter.AbstractFilter.doLogin(AbstractFilter.java:21)
    at co.za.jmr.healthproj.filter.LoginFilter.doFilter(LoginFilter.java:45)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:534)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:722)
    Caused by: java.lang.ExceptionInInitializerError
    at co.za.jmr.healthproj.facade.UserFacade.(UserFacade.java:8)
    at co.za.jmr.healthproj.mb.LoginManagedBean.login(LoginManagedBean.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    … 38 more
    Caused by: javax.persistence.PersistenceException: No Persistence provider for EntityManager named JSFCrudPU
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
    at co.za.jmr.healthproj.dao.GenericDAO.(GenericDAO.java:18)
    … 48 more

    • uaihebert Post author

      Hello, how are you?

      Check if the persistence.xml is in the correct path, or if the persistence-unit has the correct name.

      Thanks for passing by.

1 4 5 6

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current day month ye@r *