我們可以在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.yiibai.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.yiibai;
/**
*
* @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.yiibai.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/
應該會看到以下結果 -
簡單寫入一些資訊,然後提交 -