Full Web Application with Tomcat JSF Primefaces JPA Hibernate

Primefaces AutoComplete, JSF Converter

The JSF has the Converter tool that helps us get some data from the user view and transform into an object loaded from the database or a cache.

In the “com.converter” package create the following class:

package com.converter;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.*;

import com.facade.DogFacade;
import com.model.Dog;

@FacesConverter(forClass = com.model.Dog.class)
public class DogConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
		DogFacade dogFacade = new DogFacade();
		int dogId;

		try {
			dogId = Integer.parseInt(arg2);
		} catch (NumberFormatException exception) {
			throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Type the name of a Dog and select it (or use the dropdow)", "Type the name of a Dog and select it (or use the dropdow)"));
		}

		return dogFacade.findDog(dogId);
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {

		if (arg2 == null) {
			return "";
		}
		Dog dog = (Dog) arg2;
		return String.valueOf(dog.getId());
	}
}

About the above code:

  • In the @Converter annotation there is an attribute named “forClass”. This attribute indicates to the de JSF that all classes of the specified in the “forClass” will invoke the Converter. The DogConverter is annotated with “forClass = com.model.Dog.class”, every time the JSF needs a Converter for a Dog class the JSF will invoke the DogConverter. It was not necessary to write any code in the “web.xml” file.

The Converter code is required in the Primefaces AutoComplete. Bellow you see how easy is to use the AutoComplete:

personUpdateDialog.xhtml

PersonMB.java

About the above code:

  • The AutoComplete function has several options like minimum query length, delay to start a query, dropdown to display all values and more. It is worth to see all the options: http://primefaces.org/showcase/ui/autoCompleteBasic.jsf and http://primefaces.org/showcase/ui/autocompleteHome.jsf
  • The “complete” method has a cache of the values found in the database. The method goes to each object of the List<Dog> and keeps the matches.
  • Notice that the Converter will always be called because the “itemValue=”#{dog}”” that you will find in the AutoComplete component.

You can see bellow the AutoComplete working:

52 Thoughts on “Full Web Application with Tomcat JSF Primefaces JPA Hibernate

  1. Femi Adigun on April 28, 2013 at 3:51 pm said:

    A great resource, the best have seen in recent times. Thank you for giving a brother a helping hand. may the good Lord bless you real good

  2. Hi uaihebert,

    I came accross this post while reading various examples of integrating JSF & Hibernate. This is a great example of how to integrate the technologies. The sample application was simple enough so as not to detract from showing the key integration points. I happen to also be using Primefaces so that was a nice added bonus.

    Thanks for taking the time to put this together. I am sure many people will find this as usefull as I have.

  3. Justin on March 22, 2013 at 5:46 pm said:

    Thank you so much for this. I’m using it as a template for my project. One question: In LoginMB.login() you save the User object to the session. I realize this is because you want to access it in the Filters. However, because userMB is already SessionScoped, can’t you simply get access to the user object through that? Seems like there would be two user objects in the session with this code. Let me know your thoughts, thank you.

    • uaihebert on April 4, 2013 at 8:05 pm said:

      Hello Justion,

      I used the UserMB to store inside it because it is a session scoped. The UserMB has other functions other than just the user methods.

      In memory you will have a Managedbean and a user object, but it will consume a very small memory of your server giving you a very usefull objects with methods easily to access.

      Thanks for passing by.

  4. Rehan Ahzer on February 9, 2013 at 4:38 pm said:

    Slight miss ordering of sequecne perhaps …. JSFMessageUtil is on Page 7 and is being used by code on page6.

    • uaihebert on February 11, 2013 at 7:52 pm said:

      Rehan, how are you?

      I used the JSFMessageUtil before presenting it just like I see in the books.

      Most of the times the books show the code and than explains it.

      Thanks for passing by! [=

  5. Great tutorial. I am new to all this. How would you go about creating a change password for a user. Just a bit advice on maybe the flow would be very helpful.

    Thanks :)

    • uaihebert on January 25, 2013 at 9:27 pm said:

      Hello Brian,

      After the user log in you can put a link to a page where he can do it. [=

      Thanks for passing by.

      • Hi again,

        I have got a link there for a change password. What I want to do is when I click it for it to display the users email which is easy enough as I use the login session. Then I want to check the old password and set a new one.

        I was wondering more which classes I would need to change.

        I have something like this:

        public void updatePassword(User user, String oldPassword, String newPassword) {
        userDAO.beginTransaction();
        User persistedUser = userDAO.find(user.getId());
        if (user != null && user.getPassword().equals(oldPassword)) {
        persistedUser.setPassword(newPassword);
        userDAO.update(persistedUser);
        userDAO.commitAndCloseTransaction();
        }
        }

        Which is in the facade do you think is this something that looks along the right lines? I appreciate you will more than likely be busy but just a hint of whether I am on the right track would be great. I tried to put oldPassword etc in bean but it complains about it not being a field.

        Thanks again Bri :)

        • uaihebert on January 28, 2013 at 3:32 pm said:

          Hello Brian.

          You could invoke the method just like the other invoked methods samples in the application.

          First, you have to understand better what the error means. Where should the oldPassword come from?

          I think you should read the book Core JavaServer Faces. It is a really great book about JSF.

          Thanks for passing by.

  6. Hello,

    many thanks for this great application, but I have a dummy question: how to build the application (war file)? There is no ant script or Maven pom file.

    • uaihebert on January 22, 2013 at 4:50 pm said:

      Hello Sofa, how are you?

      The Eclipse can generate it for you.

      There is an option named Export, check it out. [=

      Thanks for passing by.

      • Hello uaihebert,

        Thanks, I am fine, hope you too. Thanks for your response, the export works. but I have a “small” problem:

        I tried to run this applicatiom with Jboss 7, I configured the mysql driver and the data source in JBoss. That works fine,
        the MySQL tables had been created automatically by hibernate. I inputed in the table users an user with the role ADMIN.

        The login screen works. When I submit the login form with no password I get correct response (“Password is empty…”) but when I
        submit the login form with the correct (or false) login data, a java.lang.NullPointerException occurs.

        Hope, you can help, I spent much time with this problem.

        The problem occurs in the class GenericDAO.java probably on this place:
        em = emf.createEntityManager();
        Seemingly the entity manager cannot be created.

        JBoss standalone.xml:
        ——————–

        jdbc:mysql://localhost:3306/jsfcruddb
        mysqlDriver

        root

        org.h2.jdbcx.JdbcDataSource

        com.mysql.jdbc.Driver

        persistence.xml:
        —————-

        org.hibernate.ejb.HibernatePersistence
        java:/MySQLDS

        JBoss log:
        ———-
        01:29:41,412 INFO [org.jboss.as.server] (DeploymentScanner-threads – 2) JBAS018559: Deployed “JSFCrudApp.war”
        01:30:04,343 INFO [org.hibernate.dialect.Dialect] (http–127.0.0.1-8080-2) HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
        01:30:04,361 INFO [org.hibernate.engine.transaction.internal.TransactionFactoryInitiator] (http–127.0.0.1-8080-2) HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory
        01:30:04,376 INFO [org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory] (http–127.0.0.1-8080-2) HHH000397: Using ASTQueryTranslatorFactory
        01:30:04,397 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (http–127.0.0.1-8080-2) HHH000228: Running hbm2ddl schema update
        01:30:04,409 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (http–127.0.0.1-8080-2) HHH000102: Fetching database metadata
        01:30:04,416 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (http–127.0.0.1-8080-2) HHH000396: Updating schema
        01:30:04,419 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (http–127.0.0.1-8080-2) HHH000232: Schema update complete
        01:30:04,508 WARNUNG [javax.enterprise.resource.webcontainer.jsf.lifecycle] (http–127.0.0.1-8080-2) #{loginMB.login}: java.lang.NullPointerException: javax.faces.FacesException: #{loginMB.login}: java.lang.NullPointerException
        at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118) [jsf-impl-2.1.7-jbossorg-2.jar:]
        at javax.faces.component.UICommand.broadcast(UICommand.java:315) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
        at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
        at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
        at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) [jsf-impl-2.1.7-jbossorg-2.jar:]
        at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.1.7-jbossorg-2.jar:]
        at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [jsf-impl-2.1.7-jbossorg-2.jar:]
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
        at com.filter.LoginCheckFilter.doFilter(LoginCheckFilter.java:68) [classes:]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
        at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.1.1.Final.jar:7.1.1.Final]
        at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
        at java.lang.Thread.run(Unknown Source) [rt.jar:1.6.0_27]
        Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
        at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
        at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) [jsf-impl-2.1.7-jbossorg-2.jar:]
        … 24 more
        Caused by: java.lang.NullPointerException
        at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.getStatus(JtaStatusHelper.java:73) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
        at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.isActive(JtaStatusHelper.java:115) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
        at org.hibernate.engine.transaction.internal.jta.CMTTransaction.join(CMTTransaction.java:149) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
        at org.hibernate.ejb.AbstractEntityManagerImpl.joinTransaction(AbstractEntityManagerImpl.java:1207) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
        at org.hibernate.ejb.AbstractEntityManagerImpl.postInit(AbstractEntityManagerImpl.java:176) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
        at org.hibernate.ejb.EntityManagerImpl.(EntityManagerImpl.java:89) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
        at org.hibernate.ejb.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:125) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
        at org.hibernate.ejb.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:120) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
        at com.dao.GenericDAO.beginTransaction(GenericDAO.java:24) [classes:]
        at com.dao.UserDAO.beginTransaction(UserDAO.java:1) [classes:]
        at com.facade.UserFacade.isValidLogin(UserFacade.java:10) [classes:]
        at com.mb.LoginMB.login(LoginMB.java:40) [classes:]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_27]
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_27]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_27]
        at java.lang.reflect.Method.invoke(Unknown Source) [rt.jar:1.6.0_27]
        at org.apache.el.parser.AstValue.invoke(AstValue.java:262) [jbossweb-7.0.13.Final.jar:]
        at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278) [jbossweb-7.0.13.Final.jar:]
        at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) [jsf-impl-2.1.7-jbossorg-2.jar:]
        at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
        … 25 more

Comment navigation

 

Leave a Reply

Post Navigation