Phase Event listener in JSF and create table if not exist in database
Phase Event
Phase events are processed in between each phase of the JSF request processing life cycle. Therefore, these can be used to check or report the sequence of processing of different phases of JSF life cycle.HERE IS THE EXAMPLE
regPhaseListener.java
---------------------------------------------------------------------------------------package EventHandlers;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class regPhaseListener implements PhaseListener{
// Resource injection using instead of context and initialContext
//@Resource(name = "jdbc/regJNDI")
DataSource ds;
public regPhaseListener(){
try {
Context ctx= new InitialContext();
ds=(DataSource)ctx.lookup("jdbc/regJNDI");
} catch (NamingException ex) {
ex.printStackTrace();
}
}
@Override
public void afterPhase(PhaseEvent pe) {
//throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void beforePhase(PhaseEvent pe) {
// This method is called before the beginning of a phase in the JSF life cycle. And method will //create table USERS if not found in database.
try {
Connection conn =ds.getConnection();
System.out.println();
DatabaseMetaData dbMeta =conn.getMetaData();
ResultSet check_tbl=dbMeta.getTables(null, null, "users", null);
if (!check_tbl.next()) {
Statement stmt = null;
stmt=conn.createStatement();
String create_table="CREATE TABLE USERS" +
"(FIRSTNAME VARCHAR(50),"+
"LASTNAME VARCHAR(50),"+
"EMAIL VARCHAR(100),"+
"PASSWORD VARCHAR(50),"+
"PHONE VARCHAR(50),"+
"USERNAME VARCHAR(50))";
stmt.executeUpdate(create_table);
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
@Override
public PhaseId getPhaseId() {
return PhaseId.RENDER_RESPONSE;
//throw new UnsupportedOperationException("Not supported yet.");
}
}
registration.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://xmlns.jcp.org/jsf/html"
xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"
xmlns:c="http://java.sun.com/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title>Registration</title>
<link href="asset/css/bootstrap.css" rel="stylesheet" type="text/css"/>
<style>
.regform{width:60%;
}
@font-face{
font-family:precious;
src: url('asset/Precious font/Precious.ttf') format("truetype")
}
.reg{font-family: 'Precious',Copperplate Gothic Light;
color:#0818f3;}
</style>
</h:head>
<h:body>
<c:view>
<ui:include src="template/common/top-header.xhtml"/>
<div class="container">
<h:form>
<table class="regform table-responsive table">
<tr>
<td colspan="3"><br/>
<h1 class="reg">
<h:outputText value="Please Register Yourself"></h:outputText>
</h1>
</td>
</tr>
<tr>
<td>
<c:ajax event="keyup" render="errorName" execute="@this">
<h:inputText pt:placeholder="First Name" id="fname" value="#{signUp.firstName}"
validator="#{signUp.nameValidation}"
class="form-control col-xs-6 col-md-6" >
<c:validateRegex pattern="[A-Za-z]+"/>
</h:inputText>
<h:message for="fname" id="errorName" class="alert alert-warning"></h:message>
</c:ajax>
</td>
</tr>
<tr>
<td>
<h:inputText pt:placeholder="Last Name" value="#{signUp.lastName}"
class="form-control col-xs-6 col-md-6"
validatorMessage="Last name Field can't be empty" >
</h:inputText>
</td>
</tr>
<tr>
<td>
<h:inputText pt:placeholder="User Name" value="#{signUp.userName}" class="form-control col-xs-6 col-md-6" validatorMessage="UserName Field can't be empty" >
</h:inputText>
</td>
</tr>
<tr>
<td>
<c:ajax event="valueChange" render="errorEmail" execute="@this" >
<h:inputText pt:placeholder="arpit@example.com" id="e-mail" value="#{signUp.email}"
validator="#{signUp.email_email_Validation}"
class="form-control col-xs-4 col-md-4" >
<c:validator validatorId="forumValidator"/>
</h:inputText>
<h:message for="e-mail" id="errorEmail" class="alert alert-warning"></h:message>
</c:ajax>
</td>
</tr>
<tr>
<td>
<h:inputSecret pt:placeholder="Password" value="#{signUp.password}" class="form-control" validatorMessage="password can't be empty">
</h:inputSecret>
</td>
</tr>
<tr>
<td>
<h:inputText pt:placeholder="Phone" value="#{signUp.phone}" class="form-control" validatorMessage=" Phone field can't be empty">
</h:inputText>
</td>
</tr>
<tr>
<td colspan="2">
<h:commandButton value="Submit" action="#{signUp.Insert}"
class="btn btn-default" >
<c:phaseListener type="EventHandlers.regPhaseListener" />
</h:commandButton>
<h:outputText value="Already a mamber, ">
</h:outputText>
<h:link value="Go to Login" outcome="/login.xhtml"></h:link>
</td>
</tr>
</table>
</h:form>
</div>
</c:view>
</h:body>
<ui:include src="template/common/footer.xhtml"/>
</html>
------------------------------------------------------------------------------------------------
Register PhaseListener in faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
<!-- Registering phase listener-->
<lifecycle>
<phase-listener>EventHandlers.regPhaseListener</phase-listener>
</lifecycle>
</faces-config>
Comments
Post a Comment