Posts Tagged ‘html5

28
Feb
16

HTML 5 Responsive AJAX based CRUD application using Spring 4, JPA 2, JSF 2

This page shows how to create a transactional AJAX based HTML 5 responsive CRUD application to manage a company addressbook. In addition we will using annotations wherever possible. For ease of use we will use a HSQLDB in memory database that will automatically create a directory called data in your userid’s home directory.

Full downloadable source for this page is available here. Corrections and enhancements are welcome, fork, change and push back to GitHub.

Requirements

  • Java 8
  • Spring 4
  • JPA 2
  • JSF 2.1
  • HSQLDB
  • JAVA EE 6 level containers like JBoss EAP 6.4 or Tomcat 7

Create the pom.xml

First step is to create a pom.xml file. If you are using Tomcat 7 then enable the Glassfish dependency. Since Tomcat is only a servlet engine you will need implementation classes that don’t exist in Tomcat but are provided by other more beefy web application servers.

vi pom.xml

<?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>com.test</groupId>
	<artifactId>JSFJPASpringCRUDBasic</artifactId>
	<version>20160228</version>
	<packaging>war</packaging>
	<name>JSFJPASpringCRUDBasic</name>
	<pluginRepositories>
		<pluginRepository> <!-- Ignore this repository. Its only used for document publication. -->
			<id>numberformat-releases</id>
			<url>https://raw.githubusercontent.com/numberformat/wordpress/master/20130213/repo/</url>
		</pluginRepository>
	</pluginRepositories>
	<!-- It is possible to accidentally mix different versions of Spring JARs 
		when using Maven. For example, you may find that a third-party library, or 
		another Spring project, pulls in a transitive dependency to an older release. 
		If you forget to explicitly declare a direct dependency yourself, all sorts 
		of unexpected issues can arise. To overcome such problems Maven supports 
		the concept of a "bill of materials" (BOM) dependency. You can import the 
		spring-framework-bom in your dependencyManagement section to ensure that 
		all spring dependencies (both direct and transitive) are at the same version. 
		An added benefit of using the BOM is that you no longer need to specify the 
		<version> attribute when depending on Spring Framework artifacts -->
	<dependencyManagement>
	    <dependencies>
	        <dependency>
	            <groupId>org.springframework</groupId>
	            <artifactId>spring-framework-bom</artifactId>
	            <version>4.1.4.RELEASE</version>
	            <type>pom</type>
	            <scope>import</scope>
	        </dependency>
	    </dependencies>
	</dependencyManagement>

	<repositories>
		<repository>
			<id>prime-repo</id>
			<name>PrimeFaces Maven Repository</name>
			<url>http://repository.primefaces.org</url>
			<layout>default</layout>
		</repository>
	</repositories>
	
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>
<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.1</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.1</version>
		</dependency>
<!-- Data Management -->
		<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.1.6.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hsqldb</groupId>
			<artifactId>hsqldb</artifactId>
			<version>2.3.3</version>
		</dependency>		
<!-- Spring Framework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
		</dependency>
<!-- JSF -->
		<dependency>
			<groupId>net.bootsfaces</groupId>
			<artifactId>bootsfaces</artifactId>
			<version>0.8.0</version>
		</dependency>
		<dependency>
			<groupId>org.primefaces</groupId>
			<artifactId>primefaces</artifactId>
			<version>5.3</version>
		</dependency>
		<dependency>
			<groupId>org.primefaces.themes</groupId>
			<artifactId>bootstrap</artifactId>
			<version>1.0.9</version>
		</dependency>
		<!-- If running this in a Servlet only container like Tomcat 7 enable this dependency 
		<dependency> 
			<groupId>org.glassfish</groupId>
			<artifactId>javax.faces</artifactId>
			<version>2.1.6</version>
		</dependency>		
		-->
<!-- APIs for services provided by the containers -->		
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-web-api</artifactId>
			<version>6.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>net.sf.opencsv</groupId>
			<artifactId>opencsv</artifactId>
			<version>2.3</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin> <!-- Ignore this plugin. Its only used for document publication. -->
				<groupId>github.numberformat</groupId>
				<artifactId>blog-plugin</artifactId>
				<version>1.0-SNAPSHOT</version>
				<configuration>
					<gitUrl>https://github.com/numberformat/wordpress/tree/master/${project.version}/${project.artifactId}</gitUrl>
				</configuration>
				<executions>
					<execution>
						<id>1</id>
						<phase>site</phase>
						<goals>
							<goal>generate</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

Web Application Initialization

This app depends on the Servlet 3.0 specification. The spec requires web application containers to search the classpath looking for Initializers. Classes that implement the the spring “WebApplicationInitializer” are the ones that will be picked up.

vi src/main/java/com/test/WebAppInitializer.java

package com.test;  
  
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;  

/**
 * The Servlet 3 containers automatically search the classpath for classes that
 * implement the below interface and call the onStartup() method on initialization.
 */
public class WebAppInitializer implements WebApplicationInitializer {  
      
    @Override  
    public void onStartup(ServletContext servletContext) throws ServletException {  
    	// Initialize the spring framework.
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();  
        ctx.register(SpringConfig.class);  
        ctx.setServletContext(servletContext);    
        servletContext.addListener(new ContextLoaderListener(ctx));
        // required to get spring beans injected into JSF managed beans
        servletContext.addListener(new RequestContextListener());
        
        // initialize faces (not working...)
//        servletContext.setInitParameter("primefaces.THEME", "bootstrap");
//        servletContext.setInitParameter("javax.faces.DEFAULT_SUFFIX", ".xhtml");
//        ServletRegistration.Dynamic faces = servletContext.addServlet("Faces Servlet", "javax.faces.webapp.FacesServlet");
//        faces.setLoadOnStartup(1);
//        faces.addMapping("*.xhtml");
        
    }  
  
}  

Spring Configuration (No XML)

vi src/main/java/com/test/SpringConfig.java

package com.test;  
  
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.faces.context.FacesContext;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.beans.factory.config.Scope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;  

/**
 * This class replaces the spring xml configuration.
 * 
 */
@Configuration
@ComponentScan("com.test")
@EnableTransactionManagement 
public class SpringConfig {
	
	@Bean
	public DataSource getDataSource() {
		DriverManagerDataSource dm = new DriverManagerDataSource();
		dm.setDriverClassName("org.hsqldb.jdbcDriver");
		dm.setUrl("jdbc:hsqldb:file:"+System.getProperty("user.home") + "/data/JSFJPASpringCRUD"+";shutdown=true");
		dm.setUsername("sa");
		return dm;
	}
	
//	@Bean
//	public DataSource getDataSource() {
//		DriverManagerDataSource dm = new DriverManagerDataSource();
//		dm.setDriverClassName("com.mysql.jdbc.Driver");
//		// change the "/tmp" to be another location on your system.
//		dm.setUrl("jdbc:mysql://localhost:3306/xxxx");
//		dm.setUsername("xxxx");
//		dm.setPassword("xxxx");
//		return dm;
//	}
	
	@Bean
	public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
		LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
		em.setDataSource(getDataSource());
		em.setPackagesToScan(new String[] { "com.test.model" });
		JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
		em.setJpaVendorAdapter(vendorAdapter);
		em.setJpaProperties(additionalProperties());
		return em;
	}

	@Bean
	public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
		JpaTransactionManager transactionManager = new JpaTransactionManager();
		transactionManager.setEntityManagerFactory(emf);
		return transactionManager;
	}

	@Bean
	public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
		return new PersistenceExceptionTranslationPostProcessor();
	}

	Properties additionalProperties() {
		Properties properties = new Properties();
		properties.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
//		properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
		properties.setProperty("hibernate.flushMode", "FLUSH_AUTO");
		properties.setProperty("hibernate.hbm2ddl.auto", "update");
		properties.setProperty("hibernate.show_sql", "false");
		return properties;
	}  

	@Bean
	public CustomScopeConfigurer customScope () {
	    CustomScopeConfigurer configurer = new CustomScopeConfigurer ();
	    Map<String, Object> viewScope = new HashMap<String, Object>();
	    viewScope.put("view", new ViewScope());
	    configurer.setScopes(viewScope);

	    return configurer;
	}
	
	class ViewScope implements Scope {
		 
	    public Object get(String name, @SuppressWarnings("rawtypes") ObjectFactory objectFactory) {
	        Map<String,Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();
	 
	        if(viewMap.containsKey(name)) {
	            return viewMap.get(name);
	        } else {
	            Object object = objectFactory.getObject();
	            viewMap.put(name, object);
	 
	            return object;
	        }
	    }
	 
	    public Object remove(String name) {
	        return FacesContext.getCurrentInstance().getViewRoot().getViewMap().remove(name);
	    }
	 
	    public String getConversationId() {
	        return null;
	    }
	 
	    public void registerDestructionCallback(String name, Runnable callback) {
	        //Not supported
	    }
	 
	    public Object resolveContextualObject(String key) {
	        return null;
	    }
	}
	
}  

Logging configuration

vi src/main/resources/log4j.xml

<!DOCTYPE log4j:configuration PUBLIC
  "-//APACHE//DTD LOG4J 1.2//EN" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
   
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    
	<appender name="file" class="org.apache.log4j.FileAppender">
	   <param name="maxFileSize" value="1024KB" />
	   <param name="file" value="${user.home}/logs/JSFJPASpringCRUDBasic.log" />
	   <layout class="org.apache.log4j.PatternLayout">
		<param name="ConversionPattern" 
			value="%d %-5p %c:%L - %m%n" />
	   </layout>
	</appender>
	    
    <logger name="com.test">
        <level value="DEBUG"/>
    </logger>
    <logger name="com.springframework">
        <level value="INFO"/>
    </logger>
    <logger name="org.hibernate.SQL">
        <level value="DEBUG"/>
    </logger>
    <root>
        <level value="ERROR"/>
        <appender-ref ref="file"/>
    </root> 
</log4j:configuration>

Data Managers and Entities

Used by JPA to define and interact with the database.

vi src/main/java/com/test/model/Company.java

package com.test.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="company")
public class Company {
	@Id
	@GeneratedValue
	@Column(name="company_id")
	private Long id;
	@Column(name="name")
	private String name;
	@Column(name="shipto_address1")
	private String shipToAddress;
	@Column(name="shipto_address2")
	private String shipToAddress2;
	@Column(name="shipto_city")
	private String shipToCity;
	@Column(name="shipto_provence")
	private String shipToProvence;
	@Column(name="shipto_zip")
	private String shipToZip;
	@Column(name="cosign_address1")
	private String coSignAddress;
	@Column(name="cosign_address2")
	private String coSignAddress2;
	@Column(name="cosign_city")
	private String coSignCity;
	@Column(name="cosign_zip")
	private String coSignZip;
	@Column(name="cosign_country")
	private String coSignCountry;

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getShipToAddress() {
		return shipToAddress;
	}
	public void setShipToAddress(String shipToAddress) {
		this.shipToAddress = shipToAddress;
	}
	public String getShipToAddress2() {
		return shipToAddress2;
	}
	public void setShipToAddress2(String shipToAddress2) {
		this.shipToAddress2 = shipToAddress2;
	}
	public String getShipToCity() {
		return shipToCity;
	}
	public void setShipToCity(String shipToCity) {
		this.shipToCity = shipToCity;
	}
	public String getShipToProvence() {
		return shipToProvence;
	}
	public void setShipToProvence(String shipToProvence) {
		this.shipToProvence = shipToProvence;
	}
	public String getShipToZip() {
		return shipToZip;
	}
	public void setShipToZip(String shipToZip) {
		this.shipToZip = shipToZip;
	}
	public String getCoSignAddress() {
		return coSignAddress;
	}
	public void setCoSignAddress(String coSignAddress) {
		this.coSignAddress = coSignAddress;
	}
	public String getCoSignAddress2() {
		return coSignAddress2;
	}
	public void setCoSignAddress2(String coSignAddress2) {
		this.coSignAddress2 = coSignAddress2;
	}
	public String getCoSignCity() {
		return coSignCity;
	}
	public void setCoSignCity(String coSignCity) {
		this.coSignCity = coSignCity;
	}
	public String getCoSignZip() {
		return coSignZip;
	}
	public void setCoSignZip(String coSignZip) {
		this.coSignZip = coSignZip;
	}
	public String getCoSignCountry() {
		return coSignCountry;
	}
	public void setCoSignCountry(String coSignCountry) {
		this.coSignCountry = coSignCountry;
	}
	
}

Spring DataManager Interface.

vi src/main/java/com/test/model/CompanyDataManager.java

package com.test.model;

import java.util.List;

public interface CompanyDataManager {
	// C
	Company create(Company selectedCompany);
	// R
	List<Company> getAll();
	// U
	Company update(Company selectedCompany);
	// D
	void delete(Company selectedCompany);
}

Spring DataManager Implementation

vi src/main/java/com/test/model/CompanyDataManagerImpl.java

package com.test.model;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Component;

@Component("companyDataManager")
public class CompanyDataManagerImpl implements CompanyDataManager {
	@PersistenceContext 
	private EntityManager em;

	@Override
	public List<Company> getAll() {
		return em.createQuery("SELECT c FROM Company c", Company.class).getResultList();
	}

	@Override
	public Company update(Company selectedCompany) {
		Company mergedCompany = em.merge(selectedCompany);
		return mergedCompany;
	}

	@Override
	public void delete(Company selectedCompany) {
		em.remove(em.contains(selectedCompany) ? selectedCompany : em.merge(selectedCompany));
	}
	
	public Company create(Company selectedCompany) {
		em.persist(selectedCompany);
		return selectedCompany;
	}
	
}

JSF Page and the JSF Managed Bean

The managed bean hold user entered data. This particular bean is in the View Scope. This ia scope between request and session. It stays active as long as the uesr is on the page. We could not use the Request Scope for this because the page makes AJAX call in the background.

vi src/main/java/com/test/CompanyMB.java

package com.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Random;

import javax.faces.bean.ManagedBean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.test.model.Company;
import com.test.model.CompanyDataManager;

import au.com.bytecode.opencsv.CSVReader;


/**
 * The following is a JSF Managed Bean that is actually managed by Spring.
 */

@Controller
@Scope(value="view") // you can not use JSF Scoped values here since its a spring managed bean
@ManagedBean	// use this to indicate that its a JSF Bean (managed by spring)
public class CompanyMB {

	private static final Logger logger = LoggerFactory.getLogger(CompanyMB.class);

	@Autowired
	private CompanyDataManager companyDataManager;
	
	private Company selectedCompany;
	private List<Company> all;
	private Boolean addState = false;
	
	public List<Company> getAll() { // getters should NEVER implement DB fetch logic.
		if(all==null) loadAll();
		return all;
	}

	/**
	 * This method will be called by the page during preRenderView. Example:
	 * <f:event type="preRenderView" listener="#{companyMB.loadAll}"/>
	 */
	@Transactional(isolation=Isolation.SERIALIZABLE)
	public void loadAll() {
    	logger.info("getting All");
		if(companyDataManager==null) throw new NullPointerException("dataManager is null");
		all = companyDataManager.getAll();
	}

	public CompanyDataManager getCompanyDataManager() {
		return companyDataManager;
	}


	public Company getSelectedCompany() {
		return selectedCompany;
	}


	public void setSelectedCompany(Company selectedCompany) {
		this.selectedCompany = selectedCompany;
	}
	
	private int countLines(InputStream file) {
		if(file==null) throw new NullPointerException("file stream should not be null.");
		int lines = 0;
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(file))) {
			while (reader.readLine() != null) lines++;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return lines;
	}
	@Transactional
	public void newCompany() {
		Company c = getRandomCompany();
		selectedCompany = companyDataManager.create(c);
		addState = true;
	}

	private Company getRandomCompany() {
		final String DUMMY_COMPANY_LIST_CSV = "/dummyCompanyList.csv";

		Company c = new Company();
		InputStream is = getClass().getResourceAsStream(DUMMY_COMPANY_LIST_CSV);
		if(is==null) return c;
		int lines = countLines(is);
		int randomLine = new Random().nextInt(lines - 2) + 1;
		int index = 0;
		is = getClass().getResourceAsStream(DUMMY_COMPANY_LIST_CSV);
		try (CSVReader reader = new CSVReader(new InputStreamReader(is))) {
			String[] nextLine = null;
			while((nextLine=reader.readNext()) != null) {
				if(index >= randomLine) {
					c.setName(nextLine[0]);
					c.setShipToAddress(nextLine[3]);
					c.setShipToCity(nextLine[4]);
					c.setShipToProvence(nextLine[5]);
					c.setShipToZip(nextLine[6]);
					break;
				}
				index++;
			}
		} catch (Exception ex) {
			throw new RuntimeException("unable to read random address CSV file.", ex);
		}
		return c;
	}
	
	@Transactional
	public void updateSelectedCompany() {
		logger.debug("update Selected Company called.");
		companyDataManager.update(selectedCompany);
	}
	@Transactional
	public void deleteSelectedCompany() {
		logger.debug("delete Selected Company called.");
		companyDataManager.delete(selectedCompany);
	}
	
	@Transactional
	public void cancel() {
		if(addState) {
			deleteSelectedCompany();
			addState=false;
		}
	}
}

This is the only UI page the users will see. Single page HTML5 applications use javascript to show dialogs and submit requests in the background.

vi src/main/webapp/company.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:b="http://bootsfaces.net/ui"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:p="http://primefaces.org/ui">
<h:head>
	<title>Acme Distribution</title>
</h:head>
<h:body>
	<b:container>
		<b:navBar brand="Acme Wholesale Distributor" brandHref="#"
			inverse="true">
			<b:navbarLinks>
				<b:dropMenu value="Home" href="index.xhtml">
					<b:navLink value="Companies" href="company.xhtml"></b:navLink>
				</b:dropMenu>
			</b:navbarLinks>
		</b:navBar>

		<b:panel title="Company Address List" look="primary">

			<h:form id="form">
				<p:dataTable id="companyDt" var="company" value="#{companyMB.all}">
					<f:event type="preRenderView" listener="#{companyMB.loadAll}" />
					<p:column headerText="Name">
						<h:outputText value="#{company.name}" />
					</p:column>

					<p:column headerText="Address" priority="2">
						<h:outputText value="#{company.shipToAddress}" />
					</p:column>
					<p:column headerText="City" priority="3" width="160">
						<h:outputText value="#{company.shipToCity}" />
					</p:column>
					<p:column headerText="State" priority="4" width="160">
						<h:outputText value="#{company.shipToProvence}" />
					</p:column>
					<p:column headerText="Zip" priority="5" width="80">
						<h:outputText value="#{company.shipToZip}" />
					</p:column>
					<p:column width="55">
						<f:facet name="header">
						<p:commandButton action="#{companyMB.newCompany}" update=":form:companyDetail"
							oncomplete="PF('companyDialog').show()" icon="ui-icon-plusthick"
							title="Add"/>
						</f:facet>					
						<p:commandButton update=":form:companyDetail"
							oncomplete="PF('companyDialog').show()" icon="ui-icon-search"
							title="View">
							<f:setPropertyActionListener value="#{company}"
								target="#{companyMB.selectedCompany}" />
						</p:commandButton>
					</p:column>

				</p:dataTable>
				<!-- AJAX like Pop-up Dialog -->
				<p:dialog header="Company Info" widgetVar="companyDialog"
					modal="true" showEffect="fade" hideEffect="fade" resizable="false" closable="false" >
					
					<p:outputPanel id="companyDetail" style="text-align:center;">
						<p:panelGrid columns="2"
							rendered="#{not empty companyMB.selectedCompany}"
							columnClasses="label,value">
							<h:outputText value="Id:" />
							<h:outputText value="#{companyMB.selectedCompany.id}" />
							<h:outputText value="Name" />
							<h:inputText value="#{companyMB.selectedCompany.name}" />
							<h:outputText value="Address 1:" />
							<h:inputText value="#{companyMB.selectedCompany.shipToAddress}" />
							<h:outputText value="City:" />
							<h:inputText value="#{companyMB.selectedCompany.shipToCity}" />
							<h:outputText value="State:" />
							<h:inputText value="#{companyMB.selectedCompany.shipToProvence}" />
							<h:outputText value="Zip:" />
							<h:inputText value="#{companyMB.selectedCompany.shipToZip}" />
						</p:panelGrid>
						<!-- Save Button -->
						<p:commandButton update="companyDt" 
							action="#{companyMB.updateSelectedCompany}" value="Save"
							oncomplete="PF('companyDialog').hide()" icon="ui-icon-disk" />
						<!-- Delete Button -->
						<p:commandButton update="companyDt"
							action="#{companyMB.deleteSelectedCompany}" value="Delete"
							oncomplete="PF('companyDialog').hide()" icon="ui-icon-trash" />
						<p:commandButton action="#{companyMB.cancel}" update="companyDt" value="Cancel"
							oncomplete="PF('companyDialog').hide()"
							icon="ui-icon-arrowreturn-1-w" />
					</p:outputPanel>
				</p:dialog>
			</h:form>
		</b:panel>
		<b:panel>
		 <span class="subitem">Responsive</span>
                        <span class="defaultText dispTable">
        DataTable has two responsive modes. In priority mode, visibility of columns are toggled based on the screen size and their priority (1-6). On the other hand
        in reflow mode, columns are displayed as stacked on smaller screens.
    
                        </span>
		</b:panel>
	</b:container>
</h:body>
</html>

Sample Data (optional)

You can find the file under src/main/resources in the github repository for this page.




Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 75 other followers

April 2017
S M T W T F S
« Mar    
 1
2345678
9101112131415
16171819202122
23242526272829
30  

Blog Stats

  • 807,309 hits