Showing posts with label JSF 2. Show all posts
Showing posts with label JSF 2. Show all posts

JSF 2 + Jetty Example

JSF 2 + Jetty Example
In this example we will see how to setup a simple JSF project with jetty container.

1. Create a maven project using web-app archetype and add below dependencies

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.1.7</version>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.1.7</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>
    </dependencies>

2. Update FacesServlet in to your web.xml

<listener>
        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
    </listener>
    <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>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.faces</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

3. Create a managed bean

package com.vinod.jsf;

import javax.faces.bean.ManagedBean;
@ManagedBean(name = "myFirstManagedBean", eager = false)
public class MyFirstManagedBean {
    public MyFirstManagedBean() {
          System.out.println("My bean");
       }
       public String getMessage() {
          return "Welcome to my jsf example";
       }
}

4. Create a xhtml file
Note: This is using JSF expression language to map the managed bean method

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <title>My JSF Examples</title>
</head>
<body>
   #{myFirstManagedBean.message}
</body>
</html>

5. Update jetty server and build details in to pom.xml

<build>
        <finalName>vinod-jsf</finalName>
        <defaultGoal>install</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>${jetty.version}</version>
                <configuration>
                    <webAppConfig>
                        <contextPath>/${project.artifactId}</contextPath>
                        <overrideDescriptor>${override-web-xml}</overrideDescriptor>
                    </webAppConfig>
                    <stopKey>stop</stopKey>
                    <stopPort>8081</stopPort>
                </configuration>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                        <encoding>UTF-8</encoding>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-eclipse-plugin</artifactId>
                    <version>2.9</version>
                    <configuration>
                        <wtpversion>2.0</wtpversion>
                        <downloadSources>true</downloadSources>
                        <additionalProjectFacets>
                            <jst.jsf>2.0</jst.jsf>
                        </additionalProjectFacets>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

6. Run it
mvn jetty:run
http://localhost:8080/vinod-jsf/myFirstJsf.xhtml







7. Done !! download example
https://github.com/kkvinodkumaran/myrepository/tree/master/vinod-jsf

Could not find backup for factory javax.faces.context.FacesContextFactory

JSF startup issues
an 16, 2016 8:41:34 AM javax.faces.FactoryFinder$FactoryManager getFactory
SEVERE: Application was not properly initialized at startup, could not find Factory: javax.faces.context.FacesContextFactory. Attempting to find backup.
[WARNING] unavailable
java.lang.IllegalStateException: Could not find backup for factory javax.faces.context.FacesContextFactory.

Resolution
Add listener details in to your web.xml
<listener>

        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>

</listener>

Skipping JSF Validation when required

Some cases we want to skip jsf validation for some components, here is one scenario

I have two text fields in a jsf page (Name and Address) and i have two submit buttons (Name Submit and Address Submit) . The requirement is when clicking on the Name Submit the Address empty Validation should be skipped ie Address validation will happens only when clicking the Address Submit. See below example to resolve this issue.

 

validationtest.xhtml


<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
     xmlns:h="http://java.sun.com/jsf/html">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <h2>JSF Validator Example</h2>
        <h:form id="validatorForm">
            <h:outputText id="name" value="Name :"/>
            <h:inputText id="nametext" value="#{newJSFManagedBean.name}" required="true">
            </h:inputText>
            <h:outputText id="address" value="Address :"/>
            <h:inputText id="addresstext" value="#{newJSFManagedBean.address}" required="#{!empty param['validatorForm:addresssubmit']}">
            </h:inputText>
            <h:commandButton value="Name Submission" id="namesubmit" action="#{newJSFManagedBean.nameSubmission}">
            </h:commandButton>
            <h:commandButton value="Address Submission" id="addresssubmit" action="#{newJSFManagedBean.addressSubmission}">
            </h:commandButton>
        </h:form>    </h:body>
</html>
In the above code Address field is validating only by click on address submit

Managed Bean

 

package com.vinod.jsf;

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

@ManagedBean
@RequestScoped
public class NewJSFManagedBean {
    private String name;
    private String address;

    public NewJSFManagedBean() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String nameSubmission() {
        return "validationtest.xhtml";
    }

    public String addressSubmission() {
        return "validationtest.xhtml";
    }
}

Deploy application and run it

1. Click on Name Submission (Validating only name)

 

sourceId=validatorForm:nametext[severity=(ERROR 2), summary=(validatorForm:nametext: Validation Error: Value is required.), detail=(validatorForm:nametext: Validation Error: Value is required.)]

2. Click on Address Submission (Validating name add address)


sourceId=validatorForm:nametext[severity=(ERROR 2), summary=(validatorForm:nametext: Validation Error: Value is required.), detail=(validatorForm:nametext: Validation Error: Value is required.)]

sourceId=validatorForm:addresstext[severity=(ERROR 2), summary=(validatorForm:addresstext: Validation Error: Value is required.), detail=(validatorForm:addresstext: Validation Error: Value is required.)]

Done..download application ..use mvn jetty:run to run the application

What is new in JSF 2?

JSF 2 new features

Facelets

  1. Helps in designing the UI pages without using JSP
  2. facilitates templates

Composite Components

  1. Easy to define custom components only with XHTML and TLD definition

AJAX Support

  1. built-in AJAX support and can be added to any UI components by just added <f:ajax> tag

New Navigation rules

  1. Implicit Navigation (Navigation without navigation rules in faces-config.xml)
  2. Conditional Navigation (define pre-conditions for navigation rules in faces-config.xml using EL)
  3. Preemptive Navigation (More control over navigation rules using ConfigurableNavigationHandler API)

Annotations

  1. Can define Managed bean name and scope
  2. Component annotations like @FacesComponent, @FacesRenderer, etc., to design custom component
  3. Hibernate has release annotations that work with JSF for Bean Validation

 

Ref: http://en.wikipedia.org/wiki/JavaServer_Faces

JSF 2 PhaseListener example

JSF PhaseListener

As we know JSF life cycle and if we want to trace each phase we can use the PhaseEvent api , here is one simple JSF 2 example which is using phase listener (via method binding) in the managed bean and printing messages on each phase.

Create a Managed Bean 

In this managed bean we need to add a method with the argument as PhaseEvent, use this this event object we can get the phase details

package com.vinod.jsf;

import javax.faces.bean.ManagedBean;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;

@ManagedBean
public class PhaseListenerBean {
    public String getMessage() {
        return "Hello World!";
    }

    public void phaseTest(PhaseEvent evt) throws Exception {
        try {
            if (PhaseId.APPLY_REQUEST_VALUES.equals(evt.getPhaseId())) {
                System.out.println("Phase is " + PhaseId.APPLY_REQUEST_VALUES);
            }
            if (PhaseId.INVOKE_APPLICATION.equals(evt.getPhaseId())) {
                System.out.println("Phase is " + PhaseId.INVOKE_APPLICATION);
            }
            if (PhaseId.RENDER_RESPONSE.equals(evt.getPhaseId())) {
                System.out.println("Phase is " + PhaseId.RENDER_RESPONSE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public String actionSubmit() {
        System.out.println("Action submit triggered");
        return "phase.xhtml";

    }
}
 

Create a JSF page

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html">
<h:head>
    <title>Facelet Title</title>
    <f:view beforePhase="#{phaseListenerBean.phaseTest}" />
</h:head>
<h:body>
    <h:form>
            Hello from Facelets
            #{phaseListenerBean.message}
            <h:commandButton value="Submit" id="submit"
            action="#{phaseListenerBean.actionSubmit}" />
    </h:form>
</h:body>
</html>
 

Run Application and click on the submit button (phase.xhtml) and we can see the console it is printing the phases

 

Phase is RENDER_RESPONSE 6

 

Phase is APPLY_REQUEST_VALUES 2

 

Phase is INVOKE_APPLICATION 5

 

Action submit triggered

 

Phase is RENDER_RESPONSE 6


 


Done..download application ..use mvn jetty:run to run the application

JSF Data table Simple example

JSF 2 DataTable

In JSF we can create data table to iterate collection or array or values and display or edit in to JSF pages. Here is one simple example to display data table using h:dataTable tag.
Steps
  • Create a Managed bean which contains the collection of records which needs to be displayed in JSF page
  • Create a JSF page and create h:dataTable component


1. Create a Customer class

package com.vinod.jsf;

public class Customer {
    private String name;
    private String address;
    private String phonenumber;
    public String getPhonenumber() {
        return phonenumber;
    }
    public void setPhonenumber(String phonenumber) {
        this.phonenumber = phonenumber;
    }
    public Customer(String name, String address, String phoneNumber) {
        super();
        this.name = name;
        this.address = address;
        this.phonenumber = phoneNumber;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}
2. Create a Managed Bean
package com.vinod.jsf;

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

import javax.faces.bean.ManagedBean;

@ManagedBean
public class DataTableBean {

    public DataTableBean() {
    }
    public List getCustomers() {
        List customers = new ArrayList();
        customers.add(new Customer("vinod", "Bangalore", "7777777777"));
        customers.add(new Customer("hari", "chennai", "7777447777"));
        customers.add(new Customer("Jithesh", "Pala", "7777557777"));
        return customers;

    }
}
3. Create a jsf Page
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
<head>
<title>My JSF Examples</title>
</head>
<h:body>
    <h:form id="vinod">
        <h:dataTable value="#{dataTableBean.customers}" var="customer">
            <h:column>
                <f:facet name="header">Name</f:facet>
                    #{customer.name}
                      </h:column>
            <h:column>
                <f:facet name="header">Address</f:facet>
                    #{customer.address}
                </h:column>
            <h:column>
                <f:facet name="header">Phone Number</f:facet>
                    #{customer.phonenumber}
                </h:column>
        </h:dataTable>
    </h:form>
</h:body>
</html>
4. Run Application

https://github.com/kkvinodkumaran/myrepository/tree/master/vinod-jsf
Done..download application ..use mvn jetty:run to run the application

JSF 2 Custom Converter Example

JSF 2 Converter

 

In JSF we can create custom converter class which can give our own definition for data conversion.
Following steps required to create Converters
  1. Create a Java Converter class which implements javax.faces.convert.FacesConverter interface
  2. Override converter methods
  3. Apply converter annotations to Converter class
  4. Add converter tag for JSF input component

Create a converter class

package com.vinod.jsf;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
@FacesConverter("com.vinod.InputConverter")
public class InputConverter implements Converter{

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        System.out.println(" object value " + value);
        return value;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        System.out.println(" string value " + value);
        return "Mr." + value.toString();
    }

}


Create a Managed bean



package com.vinod.jsf;

import javax.faces.bean.ManagedBean;

@ManagedBean
public class ConverterBean {
    public ConverterBean() {
    }
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String submit() {
        System.out.println("submit clicked");
        return "ConverterExample.xhtml";
    }
}

Create a JSF xhtml page

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
<head>
<title>My JSF Examples</title>
</head>
            <h:body>
            <h:form id="vinod">
                <h:outputText value="Converter Example"/>
                <h:inputText id="nametext" value="#{converterBean.name}">
                    <f:converter converterId="com.vinod.InputConverter" />
                </h:inputText>
            <h:commandButton value="Click" id="cmd" action="#{converterBean.submit}" >
            </h:commandButton>
        </h:form>
    </h:body>
</html>
  

Run it..

 

Done…Download source code..
https://github.com/kkvinodkumaran/myrepository

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts