我们可以在JSF中创建自己的自定义转换器。
以下列表是我们可以在JSF中创建自定义转换器的步骤。
javax.faces.convert.Converter
接口创建一个转换器类。getAsObject()
和getAsString()
方法。@FacesConvertor
为自定义转换器分配唯一的ID。打开 NetBeans IDE 创建一个Web工程:CustomConverter,其目录结构如下所示 -
创建以下文件代码,文件:index.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" xmlns:f="http://java.sun.com/jsf/core"> <h:body> <h:form> <h:panelGrid columns="3"> Enter your bookmark URL : <h:inputText id="bookmarkURL" value="#{user.bookmarkURL}" size="40" required="true" label="Bookmark URL"> <f:converter converterId="com.zyiz.URLConverter" /> </h:inputText> <h:message for="bookmarkURL" style="color:red" /> </h:panelGrid> <h:commandButton value="Submit" action="result" /> </h:form> </h:body> </html>
文件:result.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" xmlns:f="http://java.sun.com/jsf/core" xmlns:c="http://java.sun.com/jsp/jstl/core" > <h:body> <h:panelGrid columns="2"> Bookmark URL : <h:outputText value="#{user.bookmarkURL}" /> </h:panelGrid> </h:body> </html>
文件:User.java 的代码内容如下所示 -
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.zyiz; /** * * @author Administrator */ import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import javax.faces.convert.FacesConverter; @FacesConverter("com.zyiz.URLConverter") public class URLConverter implements Converter { @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { String HTTP = "http://"; StringBuilder url = new StringBuilder(); if (!value.startsWith(HTTP, 0)) { url.append(HTTP); } url.append(value); if (url.toString().length() > 30) { FacesMessage msg = new FacesMessage("URL Conversion error.", "Invalid URL format."); msg.setSeverity(FacesMessage.SEVERITY_ERROR); throw new ConverterException(msg); } return url.toString(); } @Override public String getAsString(FacesContext context, UIComponent component, Object value) { return value.toString(); } }
右键运行工程:CustomConverter,如果没有任何错误,打开浏览器访问:
http://localhost:8084/CustomConverter/
应该会看到以下结果 -
简单写入一些信息,然后提交 -