Penggunaan JSF Validator pada aplikasi cukup menambahkan tag ke dalam input form. Pada aplikasi GuestBook tadi tambahkan atribut required=”true” jika field input harus
diisi, tag <f:validateLength minimum=”” maximum=””> untuk membatasi jumlah minimum dan maksimum karakter yang harus dituliskan. Selengkapnya kode berikut:
<body>
<h1>GuestBook Form</h1>
<f:view>
<h:form id=”guestBookForm”>
<h:panelGrid columns=”3″ bgcolor=”#e6edfd”>
<h:outputLabel for=”name”>
<h:outputText value=”Name:”/>
</h:outputLabel>
<h:inputText id=”name” value=”#{guestBook.name}” required=”true”>
<f:validateLength minimum=”4″/>
</h:inputText>
<h:message for=”name”/>
<h:outputLabel for=”sex”>
<h:outputText value=”Sex:”/>
</h:outputLabel>
<h:selectOneListbox id=”sex” value=”” size=”3″ title=”select one
option”>
<f:selectItem id=”s1″ itemLabel=”Male” itemValue=”male” />
<f:selectItem id=”s2″ itemLabel=”Female”
itemValue=”female” />
</h:selectOneListbox>
<h:message for=”sex”/>
<h:outputLabel for=”email”>
<h:outputText value=”Email:”/>
</h:outputLabel>
<h:inputText id=”email” value=”#{guestBook.email}”
required=”true”/> <h:message for=”email” />
<h:outputLabel for=”birthdate”>
<h:outputText value=”Birthdate:”/>
</h:outputLabel>
<h:inputText id=”birthdate” value=”#{guestBook.birthdate}”/>
<h:message for=”birthdate”/>
<h:outputLabel for=”message”>
<h:outputText value=”Message:”/>
</h:outputLabel>
<h:inputTextarea id=”message” value=”#{guestBook.message}”/>
<h:message for=”message”/>
<h:commandButton type=”reset” value=”Reset”/>
<h:commandButton type=”submit” action=”#{guestBook.addGuest}”
value=”Add”/>
<h:outputText value=””/>
</h:panelGrid>
</h:form>
</f:view>
</body>
diisi, tag <f:validateLength minimum=”” maximum=””> untuk membatasi jumlah minimum dan maksimum karakter yang harus dituliskan. Selengkapnya kode berikut:
<body>
<h1>GuestBook Form</h1>
<f:view>
<h:form id=”guestBookForm”>
<h:panelGrid columns=”3″ bgcolor=”#e6edfd”>
<h:outputLabel for=”name”>
<h:outputText value=”Name:”/>
</h:outputLabel>
<h:inputText id=”name” value=”#{guestBook.name}” required=”true”>
<f:validateLength minimum=”4″/>
</h:inputText>
<h:message for=”name”/>
<h:outputLabel for=”sex”>
<h:outputText value=”Sex:”/>
</h:outputLabel>
<h:selectOneListbox id=”sex” value=”” size=”3″ title=”select one
option”>
<f:selectItem id=”s1″ itemLabel=”Male” itemValue=”male” />
<f:selectItem id=”s2″ itemLabel=”Female”
itemValue=”female” />
</h:selectOneListbox>
<h:message for=”sex”/>
<h:outputLabel for=”email”>
<h:outputText value=”Email:”/>
</h:outputLabel>
<h:inputText id=”email” value=”#{guestBook.email}”
required=”true”/> <h:message for=”email” />
<h:outputLabel for=”birthdate”>
<h:outputText value=”Birthdate:”/>
</h:outputLabel>
<h:inputText id=”birthdate” value=”#{guestBook.birthdate}”/>
<h:message for=”birthdate”/>
<h:outputLabel for=”message”>
<h:outputText value=”Message:”/>
</h:outputLabel>
<h:inputTextarea id=”message” value=”#{guestBook.message}”/>
<h:message for=”message”/>
<h:commandButton type=”reset” value=”Reset”/>
<h:commandButton type=”submit” action=”#{guestBook.addGuest}”
value=”Add”/>
<h:outputText value=””/>
</h:panelGrid>
</h:form>
</f:view>
</body>
Buat kelas baru EmailValidator dalam paket jeni3.jsf.validator. Kelas ini mengimplementasikan method validate dari interface Validator. Gambar berikut satu cara mengimplementasikan method validate secara otomatis oleh Netbeans.
package jeni3.jsf.validator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
/**
* @author mee_andto@yahoo.com
* @version 0.5
*/
public class EmailValidator implements Validator{
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
//get the component’s contents and cast it to a String
String enteredEmail = (String)value;
//set the email pattern
Pattern p = Pattern.compile(“.+@.+\\.[a-z]+”);
//match the given string with the pattern
Matcher m = p.matcher(enteredEmail);
boolean matchFound = m.matches();
if (!matchFound){
FacesMessage message = new FacesMessage();
message.setDetail(“Email not valid – The email must be in
the format yourname@yourdomain.com”);
message.setSummary(“Email not valid – The email must be in
the format yourname@yourdomain.com”);
message.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message);
}
}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
/**
* @author mee_andto@yahoo.com
* @version 0.5
*/
public class EmailValidator implements Validator{
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
//get the component’s contents and cast it to a String
String enteredEmail = (String)value;
//set the email pattern
Pattern p = Pattern.compile(“.+@.+\\.[a-z]+”);
//match the given string with the pattern
Matcher m = p.matcher(enteredEmail);
boolean matchFound = m.matches();
if (!matchFound){
FacesMessage message = new FacesMessage();
message.setDetail(“Email not valid – The email must be in
the format yourname@yourdomain.com”);
message.setSummary(“Email not valid – The email must be in
the format yourname@yourdomain.com”);
message.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message);
}
}
3. Definisikan class validator anda di file faces-config.xml, seperti kode berikut:
<validator>
<description>A validator for checking the email</description>
<validator-id>EmailValidator</validator-id>
<validator-class>jeni3.jsf.validator.EmailValidator</validatorclass>
</validator>
<validator>
<description>A validator for checking the email</description>
<validator-id>EmailValidator</validator-id>
<validator-class>jeni3.jsf.validator.EmailValidator</validatorclass>
</validator>
4. Buat class Backen Bean dengan nama LoginFormBean. (LoginFormBean.java), letakkan dalam paket jeni3.jsf.login.
package jeni3.jsf.login;
import java.util.Map;
import javax.faces.context.FacesContext;
/**
* @author mee_andto@yahoo.com
* @version 0.5
*/
public class LoginForm {
/** Creates a new instance of LoginForm */
public LoginForm() {
}
private String username = “”;
private String email = “”;
public String authenticate(){
if (username.equals(“jeni”) &&
email.equals(“arek@malang.info”)){
FacesContext context = FacesContext.getCurrentInstance();
Map sessionMap =
context.getExternalContext().getSessionMap();
sessionMap.put(“email”,email);
return “success”;
}else{
return “failure”;
}
}
//add more here getter and setter for each private variable
Jangan lupa menambahkan getter dan setter. Refactor – Encapsulate Fields.
package jeni3.jsf.login;
import java.util.Map;
import javax.faces.context.FacesContext;
/**
* @author mee_andto@yahoo.com
* @version 0.5
*/
public class LoginForm {
/** Creates a new instance of LoginForm */
public LoginForm() {
}
private String username = “”;
private String email = “”;
public String authenticate(){
if (username.equals(“jeni”) &&
email.equals(“arek@malang.info”)){
FacesContext context = FacesContext.getCurrentInstance();
Map sessionMap =
context.getExternalContext().getSessionMap();
sessionMap.put(“email”,email);
return “success”;
}else{
return “failure”;
}
}
//add more here getter and setter for each private variable
Jangan lupa menambahkan getter dan setter. Refactor – Encapsulate Fields.
5. Definisikan bean dan navigation rule dalam file faces-config.xml.
<managed-bean>
<description>
</description>
<managed-bean-name>loginForm</managed-bean-name>
<managed-bean-class>jeni3.jsf.login.LoginForm</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/login/loginForm.jsp</from-view-id>
<navigation-case>
<from-action>#{loginForm.authenticate}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/login/loginSuccess.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{loginForm.authenticate}</from-action>
<from-outcome>failure</from-outcome>
<to-view-id>/login/loginError.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<managed-bean>
<description>
</description>
<managed-bean-name>loginForm</managed-bean-name>
<managed-bean-class>jeni3.jsf.login.LoginForm</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/login/loginForm.jsp</from-view-id>
<navigation-case>
<from-action>#{loginForm.authenticate}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/login/loginSuccess.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{loginForm.authenticate}</from-action>
<from-outcome>failure</from-outcome>
<to-view-id>/login/loginError.jsp</to-view-id>
</navigation-case>
</navigation-rule>
6. Buat form login berupa file JSP. Nama file loginForm.jsp, letakkan dalam direktorilogin. Berikut kodenya:
<%@ page contentType=”text/html”%>
<%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f”%>
<%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h”%>
<style>
//css style
.error{
size:15px;
}
</style>
<f:view>
<html>
<head><title>Login Page</title></head>
<body>
<h1>Login Form</h1>
<h:form>
<h:panelGrid columns=”3″ bgcolor=”#e6edfd”>
<h:outputText value=”Enter your name: ” />
<h:inputText id=”username” value=”#{loginForm.username}”
required=”true”/>
<h:message for=”username” styleClass=”error” />
<h:outputText value=”Enter your email: ” />
<h:inputText id=”email” value=”#{loginForm.email}”
required=”true”>
<f:validator validatorId=”EmailValidator” />
</h:inputText>
<h:message for=”email” styleClass=”error” />
<h:outputText value=”” />
<h:commandButton type=”submit” value=”Login”
action=”#{loginForm.authenticate}” />
<h:outputText value=”” />
</h:panelGrid>
</h:form>
</body>
</html>
</f:view>
<%@ page contentType=”text/html”%>
<%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f”%>
<%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h”%>
<style>
//css style
.error{
size:15px;
}
</style>
<f:view>
<html>
<head><title>Login Page</title></head>
<body>
<h1>Login Form</h1>
<h:form>
<h:panelGrid columns=”3″ bgcolor=”#e6edfd”>
<h:outputText value=”Enter your name: ” />
<h:inputText id=”username” value=”#{loginForm.username}”
required=”true”/>
<h:message for=”username” styleClass=”error” />
<h:outputText value=”Enter your email: ” />
<h:inputText id=”email” value=”#{loginForm.email}”
required=”true”>
<f:validator validatorId=”EmailValidator” />
</h:inputText>
<h:message for=”email” styleClass=”error” />
<h:outputText value=”” />
<h:commandButton type=”submit” value=”Login”
action=”#{loginForm.authenticate}” />
<h:outputText value=”” />
</h:panelGrid>
</h:form>
</body>
</html>
</f:view>
7. Buat file JSP jika login berhasil. File loginSuccess.jsp dalam folder login.
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-
8″>
<title>Login Successfull</title>
</head>
<body>
<f:view>
<h:panelGrid columns=”2″ bgcolor=”#e6edfd”>
<f:facet>
<h:outputText style=”font-size:14px” value=”Login
successfull” />
<f:facet>
<h:outputText style=”font-size:14px” value=”Name =”/>
<h:outputText value=”#{loginForm.username}”/><br/>
<h:outputText style=”font-size:14px” value=”Email =”/>
<h:outputText value=”#{loginForm.email}”/>
</h:panelGrid>
</f:view>
</body>
</html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-
8″>
<title>Login Successfull</title>
</head>
<body>
<f:view>
<h:panelGrid columns=”2″ bgcolor=”#e6edfd”>
<f:facet>
<h:outputText style=”font-size:14px” value=”Login
successfull” />
<f:facet>
<h:outputText style=”font-size:14px” value=”Name =”/>
<h:outputText value=”#{loginForm.username}”/><br/>
<h:outputText style=”font-size:14px” value=”Email =”/>
<h:outputText value=”#{loginForm.email}”/>
</h:panelGrid>
</f:view>
</body>
</html>
8. Buat file JSP jika login berhasil. File loginError.jsp dalam folder login.
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-
8″>
<title>Login Error</title>
</head>
<body>
<h1>Login Error</h1>
</body>
</html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-
8″>
<title>Login Error</title>
</head>
<body>
<h1>Login Error</h1>
</body>
</html>
Tidak ada komentar:
Posting Komentar