从inputText到URL有任何标准的JSF转换器吗?

yeg*_*256 5 java jsf

我正在尝试转换inputTextjava.net.URLJSF页面:

...
<h:form>
  <h:inputText value="${myBean.url}" />
  <h:commandButton type="submit" value="go" />
</h:form>
...
Run Code Online (Sandbox Code Playgroud)

我支持的bean是:

import java.net.URL;
@ManagedBean public class MyBean {
  public URL url;
}
Run Code Online (Sandbox Code Playgroud)

我应该从头开始实现转换器还是有其他方法?

Bal*_*usC 7

是的,你需要实现一个Converter.这个特殊情况并不难:

@FacesConverter(forClass=URL.class)
public class URLConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null) {
            return null;
        }

        try {
            return new URL(value);
        }
        catch (MalformedURLException e) {
            throw new ConverterException(new FacesMessage(String.format("Cannot convert %s to URL", value)), e);
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value == null) {
            return "";
        }

        return value.toString();
    }

}
Run Code Online (Sandbox Code Playgroud)

把它放在项目的某个地方.由于@FacesConverter它将自动注册自己.