Showing posts with label Primefaces. Show all posts
Showing posts with label Primefaces. Show all posts

JSF-Primefaces database connectivity with Spring JdbcTemplate framework example


This example will explain how to connect database with JSF-Primefaces using Spring JdbcTemplate framework.




Step 1:
Create archetype web-app maven project in Eclipse IDE for Java EE and write all dependencies in pom.xml file.




pom.xml:


<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.blogspot.evaluatethecode</groupId> <artifactId>JsfPrimefacesSpringJdbc</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>JsfPrimefacesSpringJdbc Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <mysql.connector.version>5.1.9</mysql.connector.version> <spring.version>4.3.0.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- Spring framework --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.2.9</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.2.9</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>el-impl</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>com.sun.el</groupId> <artifactId>el-ri</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <dependency> <groupId>org.primefaces</groupId> <artifactId>primefaces</artifactId> <version>6.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connector.version}</version> </dependency> </dependencies> <build> <finalName>JsfPrimefacesSpringJdbc</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>


Step 2:
Create JSF managed bean classes


package blogspot.evaluatethecode.bean;


import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.event.ActionEvent;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

import blogspot.evaluatethecode.dao.IndexDao;
import blogspot.evaluatethecode.model.Users;

@Component
@ManagedBean(name = "indexBean")
@RequestScoped
@Scope("request")
public class IndexBean {
   
   private List<Users> userList;
   private String username;
   private String firstname;
   private String lastname;
   private String email;
   private String address;
   private String phone;
   
   
   public String getUsername() {
      return username;
   }
   public void setUsername(String username) {
      this.username = username;
   }
   public String getFirstname() {
      return firstname;
   }
   public void setFirstname(String firstname) {
      this.firstname = firstname;
   }
   public String getLastname() {
      return lastname;
   }
   public void setLastname(String lastname) {
      this.lastname = lastname;
   }
   public String getEmail() {
      return email;
   }
   public void setEmail(String email) {
      this.email = email;
   }
   public String getAddress() {
      return address;
   }
   public void setAddress(String address) {
      this.address = address;
   }
   public String getPhone() {
      return phone;
   }
   public void setPhone(String phone) {
      this.phone = phone;
   }
   public List<Users> getUserList() {
      return userList;
   }
   public void setUserList(List<Users> userList) {
      this.userList = userList;
   }
   
   @Autowired
   private IndexDao indexDao;
   
   public void setIndexDao(IndexDao indexDao) {
      this.indexDao = indexDao;
   }
   
   @PostConstruct
       public void init() {
       
      this.setUserList(indexDao.getUsersList());
      
    }
   
   public void addUser(ActionEvent actionEvent) {
      System.out.println("Inside add user");
      Users users = new Users();
      users.setUsername(this.getUsername());
      users.setFirstname(this.getFirstname());
      users.setLastname(this.getLastname());
      users.setAddress(this.getAddress());
      users.setEmail(this.getEmail());
      users.setPhone(this.getPhone());
      
      indexDao.insertUser(users);
      this.setUserList(indexDao.getUsersList());
      
      System.out.println("Successfully added");
      resetAll();
   }
   
   private void resetAll() {
      this.username = null;
      this.firstname = null;
      this.lastname = null;
      this.address = null;
      this.email = null;
      this.phone = null;
      
   }
   
}





Step 3:
Create DAO classes for JDBC retrieve and save operations.

DAO Interface:

package blogspot.evaluatethecode.dao;

import java.util.List;

import blogspot.evaluatethecode.model.Users;

public interface IndexDao {

   public List<Users> getUsersList();
   public int insertUser(Users users);
   
}

DAO Class:

package blogspot.evaluatethecode.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import blogspot.evaluatethecode.model.Users;  

@Repository("indexDao")
public class IndexDaoImpl implements IndexDao{
   
   @Autowired   private JdbcTemplate jdbcTemplate;  
     
   public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
       this.jdbcTemplate = jdbcTemplate;  
   }

   public List<Users> getUsersList() {
      String sql = "select userid, username," +
            " firstname, lastname, email, address, phone from users";
      List<Users> usersList = jdbcTemplate.query(
            sql, new BeanPropertyRowMapper<Users>(Users.class));
      return usersList;
   }

   public int insertUser(Users users) {
      String sql = "insert into users(username, firstname," +
            " lastname, email, address, phone) values " +
            "(?, ?, ?, ?, ?, ?)";
      
      int value = jdbcTemplate.update(sql,
                new Object[] { users.getUsername(), users.getFirstname(), 
                  users.getLastname(), users.getEmail(), users.getAddress(), 
                  users.getPhone() });
      return value;
   }

   
}


Step 4:
Create database table in MYSQL database

create database evaluatethecode
use database evaluatethecode

create table users (userid int primary key AUTO_INCREMENT,
 username varchar(20), firstname varchar(20),lastname varchar(20),
 email varchar(20),address varchar(50),phone varchar(20));


Step 5:
Create configuration files – web.xml, faces-config.xml and, application-Context.xml

web.xml:

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         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_2_5.xsd">
<display-name>JsfPrimefacesSpringJdbc Maven Webapp</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param> <welcome-file-list> <welcome-file>index.xhtml</welcome-file> </welcome-file-list> <servlet> <servlet-name>facesServlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>facesServlet</servlet-name> <url-pattern>/jsf/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>facesServlet</servlet-name> <url-pattern>*.xhtml</url-pattern> </servlet-mapping> </web-app>

faces-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
   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-facesconfig_2_1.xsd"
   version="2.1">
<application> <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver </el-resolver> </application> </faces-config>

application-Context.xml:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="blogspot.evaluatethecode" /> <context:annotation-config /> <bean id="driverManagerDataSource"
     class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
 
<property name="driverClassName" value="com.mysql.jdbc.Driver" />  
<property name="url" value="jdbc:mysql://localhost:3306/evaluatethecode" />  
<property name="username" value="root" />  
<property name="password" value="mysql" />  
</bean>  
  
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
<property name="dataSource" ref="driverManagerDataSource"></property>  
</bean>  

<bean id="indexDao" class="blogspot.evaluatethecode.dao.IndexDaoImpl">  
<property name="jdbcTemplate" ref="jdbcTemplate"></property>  
</bean>  

</beans>




Step 6:
Build maven project and deploy the war file inside target folder to Glassfish server.
Command to build maven project -> mvn clean install
Click here for deployment steps


Output: 



JSF - Primefaces example to dynamically generate columns with values


For running this example on our system, we need JDK 8, Maven, any Java IDE (Eclipse, Intellij IDEA, etc.), any Application/ Web server (Tomcat, Glassfish, etc.)

I have used Glassfish 5 application server to deploy this application and Intellij IDEA for development.

Steps to create JSF - Primefaces web application using Maven:

(1)    Create new Maven project of type : maven-archetype-webapp
(2)    Write down the required dependencies in pom.xml file.
(3)    Create ManagedBean class
(4)    Create xhtml file to display user interface.
(5)    Create 3 configuration files – web.xml,   faces-config.xml and applicationContext.xml and place them inside WEB-INF directory.
(6)    Build the project – mvn clean install
(7)    Deploy the war file generated inside target directory to Glassfish server and launch the application

  Structure of the project in Intellij IDEA:





  Step 1: Create new Maven project of type : maven-archetype-webapp



















Step 2: Write down the required dependencies in pom.xml file.

<?xml version="1.0" encoding="UTF-8"?>

<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>blogspot.evaluatethecode</groupId> <artifactId>jsfdynamiccolumn</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>JSF dynamic column</name> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.0.RELEASE</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.2.9</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.2.9</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>el-impl</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>com.sun.el</groupId> <artifactId>el-ri</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <dependency> <groupId>org.primefaces</groupId> <artifactId>primefaces</artifactId> <version>6.0</version> </dependency> </dependencies> <build> <finalName>dynamiccolumnjsf</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>

Step 3: Create ManagedBean class

package blogspot.evaluatethecode.bean;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import blogspot.evaluatethecode.model.ColumnModel;
import blogspot.evaluatethecode.model.ValueModel;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component@ManagedBean(name = "dynamicColumnBean")
@RequestScoped@Scope("request")
public class DynamicColumnBean {


    @PostConstruct    public void init() {
        List<ColumnModel> columnList = new ArrayList<>();
        columnList.add(new ColumnModel("Name","name"));
        columnList.add(new ColumnModel("Age","age"));
        columnList.add(new ColumnModel("Email","email"));
        this.setColumns(columnList);

        List<ValueModel> valueModelList = new ArrayList<>();
        valueModelList.add(new ValueModel
                ("Mr. Test","10","test@evaluatethecode.com"));
        valueModelList.add(new ValueModel
                ("Mr. Code","11","code@evaluatethecode.com"));
        this.setValues(valueModelList);
    }

    private List<ColumnModel> columns;
    private List<ValueModel> values;

    public List<ColumnModel> getColumns() {
        return columns;
    }

    public void setColumns(List<ColumnModel> columns) {
        this.columns = columns;
    }

    public List<ValueModel> getValues() {
        return values;
    }

    public void setValues(List<ValueModel> values) {
        this.values = values;
    }
}

Step 4: Create xhtml file to display user interface.

<f:view xmlns="http://www.w3.org/1999/xhtml"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:f="http://java.sun.com/jsf/core"
        xmlns:ui="http://java.sun.com/jsf/facelets"
        xmlns:p="http://primefaces.org/ui">

    <p:panelGrid columns = "1" border="1">
        <p:dataTable value="#{dynamicColumnBean.values}" var="myValue"
                     style="border: 1px solid black;">
            <f:facet name="header">Dynamically generated column in data table
            </f:facet>
            <p:columns value="#{dynamicColumnBean.columns}" var="myColumn"
                       style="border: 1px solid black;">
                <f:facet name="header">
                    #{myColumn.header}
                </f:facet>
                #{myValue[myColumn.property]}
            </p:columns>
        </p:dataTable>
    </p:panelGrid>

</f:view>

Step 5: Create 3 configuration files – web.xml,   faces-config.xml and applicationContext.xml and place them inside WEB-INF directory.

web.xml:

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         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_2_5.xsd">

  <display-name>jsf dynamic column</display-name>


  <listener>
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>
  <listener>
    <listener-class>
      org.springframework.web.context.request.RequestContextListener
    </listener-class>
  </listener>


  <context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
  </context-param>


  <welcome-file-list>
    <welcome-file>index.xhtml</welcome-file>
  </welcome-file-list>


  <servlet>
    <servlet-name>facesServlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>facesServlet</servlet-name>
    <url-pattern>/jsf/*</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>facesServlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>

</web-app>

faces-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
   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-facesconfig_2_1.xsd"
   version="2.1">

   <application>
      <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver
      </el-resolver>
   </application>

</faces-config>

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">

   <context:component-scan base-package="blogspot.evaluatethecode" />
   <context:annotation-config />

</beans>

Step 6: Go to the location where pom.xml file is present and build the maven project using command – mvn clean install

Step 7: Deploy the war file generated inside target directory to Glassfish server and launch the application. Click here for Steps to deploy war file on Glassfish 5 Server


Output :