Integration of JSF2+EJB3+JPA2+JavaDB(Derby) PART-2

Now the Web module code starts here. following is the managed bean which acts as a controller for the jsf pages.

CustomerMBean.java

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.customerapp.web;

import com.spark.ejb.model.Customer;
import com.spark.ejb.model.DiscountCode;
import com.spark.ejb.sessionbeans.CustomerSession;
import java.security.Principal;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
*
* @author Sony
*/
@ManagedBean(name = “customer”)
@SessionScoped
public class CustomerMBean
{
@EJB
private CustomerSession customerSessionBean;
private Customer customer;
private Object[] selectedCustomer;

public Object[] getSelectedCustomer()
{
return selectedCustomer;
}

public void setSelectedCustomer(Object[] selectedCustomers)
{
this.selectedCustomer = selectedCustomers;
System.out.println(“setSelectedCustomer() called: ” + selectedCustomers[0]);
}

public CustomerMBean()
{
}

/**
* Returns list of customer objects to be displayed in the data table
* @return
*/
public List<Customer> getCustomers()
{
return customerSessionBean.retrieve();
}

/**
* Returns the selected Customer object
* @return
*/
public Customer getDetails()
{
//Can either do this for simplicity or fetch the details again from the
//database using the Customer ID
return customer;
}

/**
* Returns an array of SelectItem to be displayed in the DiscountCode
* Dropdown list in the CustomerDetails page
* @return
*/
public javax.faces.model.SelectItem[] getDiscountCodes()
{
SelectItem[] options = null;
List<DiscountCode> discountCodes = customerSessionBean.getDiscountCodes();
if (discountCodes != null && discountCodes.size() > 0)
{
int i = 0;
options = new SelectItem[discountCodes.size()];
for (DiscountCode dc : discountCodes)
{
options[i++] = new SelectItem(dc.getDiscountCode(),
dc.getDiscountCode() + ” (” + dc.getRate() + “%)”);
}
}
return options;
}

/**
* Action handler – user selects a customer record from the list
* (data table) to view/edit
* @param customer
* @return outcome string
*/
public String showDetails(Customer customer)
{
this.customer = customer;
return “DETAILS”;
}

/**
* Action handler – update the changes in the Customer object to the
* database
* @return
*/
public String update()
{
System.out.println(“###UPDATE###”);
customer = customerSessionBean.update(customer);
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
“Sucessful”, “Record successfully saved!”));
return “SAVED”;
}

/**
* Action handler – goes to the Customer listing page
* @return
*/
public String list()
{
System.out.println(“###LIST###”);
return “LIST”;
}

/**
*
* @return Principal of the logged-in user
*/
private Principal getLoggedInUser()
{
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance().
getExternalContext().getRequest();
return request.getUserPrincipal();
}

/**
* Property
* @return true if user is logged in, false otherwise
*/
public boolean isUserNotLogin()
{
Principal loginUser = getLoggedInUser();
if (loginUser == null)
{
return true;
}
return false;
}

/**
* Property
* @return Username of the logged-in user
*/
public String getLoginUserName()
{
Principal loginUser = getLoggedInUser();
if (loginUser != null)
{
return loginUser.getName();
}
return “None”;
}

/**
* Action handler – logout
* @return outcome string for pageflow definition
*/
public String logout()
{
HttpServletRequest request =
(HttpServletRequest) FacesContext.getCurrentInstance().
getExternalContext().getRequest();

Principal loginUser = getLoggedInUser();
if (loginUser != null)
{
HttpSession session = request.getSession(false);
if (session != null)
{
session.invalidate();
}
}
return “LOGOUT”;
}

public String createNewCustomer()
{
return “NEW”;
}
}

Now here is the code for the jsf page which will retrieve all the records for the Derby database(javadb).i used “RichFaces” an implementation of JSF Specification.Download the PrimeFaces library (go for the latest stable api ) from http://www.primefaces.org/downloads.html.

<?xml version=”1.0″ encoding=”UTF-8″?>
<!–
To change this template, choose Tools | Templates
and open the template in the editor.
–>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml&#8221;
xmlns:f=”http://java.sun.com/jsf/core&#8221;
xmlns:h=”http://java.sun.com/jsf/html&#8221;
xmlns:p=”http://primefaces.org/ui”&gt;
<h:head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″/>
<title>Customer Listing</title>
<p:resources />
</h:head>
<h:body>
<h:form>
<h2><h:outputText value=”Customer Listing”/></h2>
<p:dataTable var=”item” value=”#{customer.customers}” id=”customerList”
paginator=”true” rows=”10″>
<p:column>
<f:facet name=”header”>
<h:outputText value=”Customer ID” />
</f:facet>
<h:commandLink action=”#{customer.showDetails(item)}” value=”#{item.customerId}”/>
</p:column>
<p:column>
<f:facet name=”header”>
<h:outputText value=”Name”/>
</f:facet>
<h:outputText value=”#{item.name}”/>
</p:column>
<p:column>
<f:facet name=”header”>
<h:outputText value=”CreditLimit”/>
</f:facet>
<h:outputText value=”#{item.creditLimit}”/>
</p:column>
<p:column>
<f:facet name=”header”>
<h:outputText value=”Discount %”/>
</f:facet>
<h:outputText value=”#{item.discountCode.rate}”/>
</p:column>
<p:column>
<f:facet name=”header”>
<h:outputText value=”State”/>
</f:facet>
<h:outputText value=”#{item.state}”/>
</p:column>
<p:column>
<f:facet name=”header”>
<h:outputText value=”City”/>
</f:facet>
<h:outputText value=”#{item.city}”/>
</p:column>
<p:column>
<f:facet name=”header”>
<h:outputText value=”Zip”/>
</f:facet>
<h:outputText value=”#{item.zip}”/>
</p:column>
<p:column>
<f:facet name=”header”>
<h:outputText value=”Phone”/>
</f:facet>
<h:outputText value=”#{item.phone}”/>
</p:column>
<p:column>
<f:facet name=”header”>
<h:outputText value=”Email”/>
</f:facet>
<h:outputText value=”#{item.email}”/>
</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>

Finally Configure your faces-config.xml and web.xml as follows:

web.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app version=”3.0″ xmlns=”http://java.sun.com/xml/ns/javaee&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd”&gt;
<context-param>
<param-name>com.sun.faces.verifyObjects</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.validateXml</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml</param-value>
</context-param>
<context-param>
<param-name>facelets.DEVELOPMENT</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>facelets.SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
<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>/faces/*</url-pattern>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Resource Servlet</servlet-name>
<servlet-class>
org.primefaces.resource.ResourceServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Resource Servlet</servlet-name>
<url-pattern>/primefaces_resource/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>com.sun.faces.allowTextChildren</param-name>
<param-value>true</param-value>
</context-param>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/CustomerList.jsp</welcome-file>
</welcome-file-list>
<error-page>
<error-code>403</error-code>
<location>/faces/AccessDenied.jsp</location>
</error-page>
<security-constraint>
<display-name>Update Customer Details</display-name>
<web-resource-collection>
<web-resource-name>CustomerDetails</web-resource-name>
<description>Update Customer Details</description>
<url-pattern>/faces/CustomerDetails.jsp</url-pattern>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<description>Allows Admin roles to view and update CustomerDetails</description>
<role-name>Admin</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<display-name>View Customer Details</display-name>
<web-resource-collection>
<web-resource-name>CustomerDetails</web-resource-name>
<description>View the Customer Details</description>
<url-pattern>/faces/CustomerDetails.jsp</url-pattern>
<http-method>GET</http-method>
</web-resource-collection>
<web-resource-collection>
<web-resource-name>CustomerList</web-resource-name>
<description>Navigate to Customer Details</description>
<url-pattern>/faces/CustomerList.jsp</url-pattern>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<description>Allows the roles to only view CustomerDetails</description>
<role-name>CustomerRep</role-name>
<role-name>Admin</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>ldap-realm</realm-name>
<form-login-config>
<form-login-page>/faces/Login.jsp</form-login-page>
<form-error-page>/faces/LoginError.jsp</form-error-page>
</form-login-config>
</login-config>
<security-role>
<description>This is the Administrator role who can perform all available tasks in the application</description>
<role-name>Admin</role-name>
</security-role>
<security-role>
<description>This is the Customer Representative role who can only view the Customers’ details but not update it</description>
<role-name>CustomerRep</role-name>
</security-role>
</web-app>

faces-config.xml

<?xml version=’1.0′ encoding=’UTF-8′?>

<!– =========== FULL CONFIGURATION FILE ================================== –>

<faces-config version=”2.0″
xmlns=”http://java.sun.com/xml/ns/javaee&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd”&gt;
<application/>
<managed-bean>
<managed-bean-name>customer</managed-bean-name>
<managed-bean-class>com.customerapp.web.CustomerMBean</managed-bean-class>

<managed-bean-scope>session</managed-bean-scope></managed-bean>
<navigation-rule>
<from-view-id>/CustomerList.jsp</from-view-id>
<navigation-case>
<from-outcome>DETAILS</from-outcome>
<to-view-id>/CustomerDetails.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>LOGOUT</from-outcome>
<to-view-id>/Logout.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/CustomerDetails.jsp</from-view-id>
<navigation-case>
<from-outcome>LOGOUT</from-outcome>
<to-view-id>/Logout.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>NEW</from-outcome>
<to-view-id>/CustomerNew.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/CustomerList.xhtml</from-view-id>
<navigation-case>
<from-outcome>DETAILS</from-outcome>
<to-view-id>/CustomerDetails.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/CustomerDetails.xhtml</from-view-id>
<navigation-case>
<from-outcome>LIST</from-outcome>
<to-view-id>/CustomerList.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s