Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Java WEB: Creating a Login Screen with JPA, JSF, PrimeFaces and MySQL

This article will show you how to create a login screen of a web application with JSF, JPA and PrimeFaces

Java Server Faces is a specification for the development of Web applications, following the Model View Controller (MVC) in Java. This specification has emerged as an alternative to Struts, which at the time was the main framework to implement applications that design pattern. Its first version was released in 2004 and in 2013 version 2.2 was launched.

Currently, there are several frameworks for building rich interfaces to JSF, as RichFaces the IceFaces, and especially PrimeFaces, which stands for providing a wide variety of components. Currently this framework is in version 5.1. and contains a large number of form components, list, menu, among others, that greatly facilitate the development of interfaces.

The JPA is a specification for Java Persistence data using the Object-Relational Mapping (ORM - Object Relational Mapping). One of the main JPA implementations is the Hibernate framework. JPA can be used with any database that has a driver for communicating with Java applications, including, PostgreSQL, Oracle, SQL Server and MySQL.

This article will show how to set up a web application with PrimeFaces and Hibernate, and also how to implement a login screen with these technologies. The database server used in the development of the application is MySQL.

Setting up the project

To facilitate the configuration of the project, Maven will be used. For the creation of this project dependencies of PrimeFaces libraries are needed, the JSF, the Hibenate and the MySQL driver. PrimeFaces library is also necessary to add the repository information that framework. Listing 1 shows the pom.xml file created project.

Listing 1. Setting up the project with PrimeFaces and JPA

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.mrbool</groupId>
        <artifactId>primefaces</artifactId>
        <version>0.0.1</version>
        <packaging>war</packaging>
   
        <dependencies>
              <dependency>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-validator</artifactId>
                    <version>4.2.0.Final</version>
              </dependency>
              <dependency>
                    <groupId>org.hibernate.common</groupId>
                    <artifactId>hibernate-commons-annotations</artifactId>
                    <version>4.0.1.Final</version>
                    <classifier>tests</classifier>
              </dependency>
              <dependency>
                    <groupId>org.hibernate.javax.persistence</groupId>
                    <artifactId>hibernate-jpa-2.0-api</artifactId>
                    <version>1.0.1.Final</version>
              </dependency>
              <dependency>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-entitymanager</artifactId>
                    <version>4.0.1.Final</version>
              </dependency>
              <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>5.1.6</version>
                    <scope>compile</scope>
              </dependency>
              <dependency>
                    <groupId>org.primefaces</groupId>
                    <artifactId>primefaces</artifactId>
                    <version>5.1</version>
                    <scope>compile</scope>
              </dependency>
              <dependency>
                    <groupId>org.glassfish</groupId>
                    <artifactId>javax.faces</artifactId>
                    <version>2.1.13</version>
                    <scope>compile</scope>
              </dependency>
          <dependency>
                    <groupId>commons-io</groupId>
                    <artifactId>commons-io</artifactId>
                    <version>2.4</version>
              </dependency>
        </dependencies>
        <repositories>
              <repository>
                    <id>prime-repo</id>
                    <name>PrimeFaces Maven Repository</name>
                    <url>http://repository.primefaces.org</url>
                    <layout>default</layout>
              </repository>
        </repositories>
  </project>

After setting up the project dependencies with Maven, you must configure the application to use the JSF framework. As the project is a web application, we need to create the web.xml file. The most important step is to configure the Faces Servlet, which uses javax.faces.webapp.FacesServlet class, and configure the mapping of URLs that will be handled by JSF in the case, all addresses ending with the pattern *.xhtml. If an error happends in the application, the request is redirected to the home page of the application. Listing 2 shows the code of web.xml.

Listing 2. project web.xml configuration

 <?xml version="1.0" encoding="UTF-8"?>
  <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
      <display-name>com.mrbool.primefaces</display-name>
      <servlet>
          <servlet-name>Faces Servlet</servlet-name>
          <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
          <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
          <servlet-name>Faces Servlet</servlet-name>
          <url-pattern>*.xhtml</url-pattern>
      </servlet-mapping>
      <welcome-file-list>
          <welcome-file>/index.xhtml</welcome-file>
      </welcome-file-list>
      <error-page>
          <exception-type>javax.faces.application.ViewExpiredException</exception-type>
          <location>/index.xhtml</location>
      </error-page>
  </web-app>

You must also configure the persistence.xml file, which is the file that sets the access to the database with JPA. Listing 3 shows this file. Some important settings that are file, the tag <persistence-unit> must be set the name of the persistence unit, the tag <provider> should be set to implementation used JPA, if Hibernate, the <class> defines the classes of objects that will be persisted in this example, only the User class is used. Other properties define the MySQL access options. The property hibernate.hbm2ddl.auto states that the database will be automatically created if it does not exist, which decreases a little setup work.

Listing 3. persistence.xml file that configures access to the database with JPA

 <persistence xmlns="http://java.sun.com/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
       http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
        version="2.0">
   
        <persistence-unit name="users">
   
              <!-- provedor/implementacao do JPA -->
              <provider>org.hibernate.ejb.HibernatePersistence</provider>
   
              <class>com.mrbool.model.User</class>

   
              <properties>
              
                    <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />

                    <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/user" />
                    <property name="javax.persistence.jdbc.user" value="root" />
                    <property name="javax.persistence.jdbc.password" value="root" />
   
                    <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />

                    <property name="hibernate.show_sql" value="true" />
                    <property name="hibernate.format_sql" value="true" />
   
                    <property name="hibernate.hbm2ddl.auto" value="update" />

   
              </properties>
        </persistence-unit>
  </persistence>

For projects configured with maven, the persistence.xml file must be in the /src/main/resources/METAINF project.

To run the examples created in this article you must use a Web container. The PrimeFaces and JPA can run on any one that is compatible with the Java Web, including the Jetty and Tomcat.

Developing the Login screen

The first step in the development of the Login screen, is to develop a class that implements the objects that will be persisted to the database. How we use the JPA, you must use the notes of this specification, to be made the object-relational mapping of the class attributes.

Listing 4 shows the User class code, which is the object to be persisted in the database. The class has four attributes, which are the Id, the user name, user password, and date of last access to the system. The main notes are @Id, which defines the attribute is the only class identifier, the @Column annotation that defines several options for the column, as the column name in the database, if it is a column with unique values and if it can receive nulls and @Temporal annotation to be used for attributes to the date type.

All user data is mandatory, unless the lastAccess, the required data must have the nullable attribute to false, and not mandatory true.

Listing 4. User class that represents the object to be persisted

 package com.mrbool.model;
   
  import java.util.Date;
   
  import javax.persistence.Column;
  import javax.persistence.Entity;
  import javax.persistence.Id;
  import javax.persistence.Temporal;
  import javax.persistence.TemporalType;
   
  @Entity
  public class User {
        
        @Id
        @Column(name="id", nullable=false, unique=true)
        private int id;
        
        @Column(name="userName", nullable=false, unique=true)
        private String nameUser;
        
        @Column(name="password", nullable=false, unique=false)
        private String password;
   
        @Column(name="lastAccess", unique=true)
        @Temporal(TemporalType.DATE)
        private Date lastAccess;
        
        public String getNameUser() {
              return nameUser;
        }
        
        public void setNameUser(String nameUser) {
              this.nameUser = nameUser;
        }
        
        public String getPassword() {
              return password;
        }
        
        public void setPassword(String password) {
              this.password = password;
        }
        
        public Date getLastAccess() {
              return lastAccess;
        }
        
        public void setLastAccess(Date lastAccess) {
              this.lastAccess = lastAccess;
        }
   }

After creating the class of the object to be persisted, we can define the class that does operations in the database, such as add, delete, and retrieve data. To implement login, we need only the method that retrieves user data, if it exists. Listing 5 shows the code of UserDAO class that has the method getUser getting the userName and password parameters. This method is made a search in the database, and if that user exists, it is returned, otherwise null is returned. When a query does not return results, except for NoResultException type is thrown, so we used a try/catch, and if this exception is thrown, the method returns null, indicating that there is no user with the username and passed password as a parameter.

Listing 5. Class UserDAO that makes access to data

 package com.mrbool.db;
   
  import javax.persistence.EntityManager;
  import javax.persistence.EntityManagerFactory;
  import javax.persistence.NoResultException;
  import javax.persistence.Persistence;
   
  import com.mrbool.model.User;
   
  public class UserDAO {
   
        private EntityManagerFactory factory = Persistence
                    .createEntityManagerFactory("users");
        private EntityManager em = factory.createEntityManager();
   
        public User getUser(String nameUser, String password) {
   
              try {
                    User user = (User) em
                               .createQuery(
                                           "SELECT u from User u where u.nameUser = :name and u.password = :password")
                               .setParameter("name", nameUser)
                               .setParameter("password", password).getSingleResult();
   
                    return user;
              } catch (NoResultException e) {
                    return null;
              }
        }
   
      public boolean inserirUser(User user) {
              try {
                    em.persist(user);
                    return true;
              } catch (Exception e) {
                    e.printStackTrace();
                    return false;
              }
        }
        
        public boolean deletarUser(User user) {
              try {
                    em.remove(user);
                    return true;
              } catch (Exception e) {
                    e.printStackTrace();
                    return false;
              }
        }
   
  }

In the article, the methods insert and delete will not be used. but if you need them , just use them as getUser method is called.

With access to data already deployed, you can develop ManagedBean JSF, which is the class that receives the data that the user submits the application screen, to receive the data, is used the user attribute. With these data, the method sends calls getUser method UserDAO class if this method returns null, an error screen for the user is sent, and it remains on the same page, otherwise the user is redirected to the main.xhtml screen. Listing 6 shows the code for this class.

Listing 6. Class ManagedBean LoginManagedBean

 package com.mrbool.managedbeans;
   
  import javax.faces.application.FacesMessage;
  import javax.faces.bean.ManagedBean;
  import javax.faces.bean.ViewScoped;
  import javax.faces.context.FacesContext;
   
  import com.mrbool.db.UserDAO;
  import com.mrbool.model.User;
   
  @ManagedBean(name = "LoginMB")
  @ViewScoped
  public class LoginManagedBean {
   
        private UserDAO userDAO = new UserDAO();
        private User user = new User();
        
        public String send() {
              
              user = userDAO.getUser(user.getNameUser(), user.getPassword());
              if (user == null) {
                    user = new User();
                    FacesContext.getCurrentInstance().addMessage(
                               null,
                               new FacesMessage(FacesMessage.SEVERITY_ERROR, "User not found!",
                                           " Login Error!"));
                    return null;
              } else {
                    return "/main";
              }
              
              
        }
   
        public User getUser() {
              return user;
        }
   
        public void setUser(User user) {
              this.user = user;
        }
  }

You can now implement the login screen, the screen has two input components, a <p:inputText>, the user to enter the user name and <p:password>, which functions as a inputText but shows * data with the user to enter their password. Listing 7 shows the HTML code developed. The component <p:messages> is displayed if an error occurs at login, for example, if the user does not exist.

Listing 7. XHTML the Login screen

 <html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:p="http://primefaces.org/ui">
   
  <h:head>
   
  </h:head>
   
  <h:body>
        <h:form>
              <p:messages id="messages" />
              <p:panelGrid columns="2">
                    <p:outputLabel for="nameUser" value="Name User:" />
                    <p:inputText id="nameUser" value="#{LoginMB.user.nameUser}" />
                    
                    <p:outputLabel for="password" value="Password:" />
                    <p:password id="password" value="#{LoginMB.user.password}" />
                    
                    <p:commandButton value="Enviar" icon="ui-icon-star" action="#{LoginMB.send}" ajax="false">
                    </p:commandButton>
   
              </p:panelGrid>
        </h:form>
  </h:body>
  </html>

Figure 1 shows the implemented login screen, as you can see, there are two fields for the user to enter their username and password. He can then click the Send button, if the login fails, an error message is displayed, otherwise, it is redirected to the main screen of the system.

Figure 1. implemented login screen.

Figure 2 shows the login screen if a user has entered the user name or password incorrectly, if it occurs, an error message will be displayed.

Figure 2. login screen with error message.

Listing 8 shows the XHTML code of the system login page as the goal of this article was just the login screen. This screen displays only a message saying "Login successfully! Welcome to the system ", but it would be possible to implement anything on that page, and the user could only access it via the login screen.

Listing 8. XHTML main screen of the system for success case at login

 <html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:p="http://primefaces.org/ui">
   
  <h:head>
   
  </h:head>
   
  <h:body>
        <h:form>
   
              <p:outputLabel value="Login success! Welcome to the system!"></p:outputLabel>
        </h:form>
  </h:body>
  </html>

This article showed how to set up and implement a login screen combining PrimeFaces frameworks, JSF and Hibernate. The configuration made in this article is for the creation of any Web application with these technologies.

Links

PrimeFaces ShowCase

http://www.primefaces.org/showcase/

Official Page of Hibernate

http://hibernate.org/

Oracle page about JSF

http://www.oracle.com/technetwork/java/javaee/javaserverfaces-139869.html



Web developer and passioned for web design, SEO and front end technologies.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login