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

时间:2010-08-05 14:04:26

标签: java jsf

我正在尝试在JSF页面中将inputText转换为java.net.URL

...
<h:form>
  <h:inputText value="${myBean.url}" />
  <h:commandButton type="submit" value="go" />
</h:form>
...

我支持的bean是:

import java.net.URL;
@ManagedBean public class MyBean {
  public URL url;
}

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

2 个答案:

答案 0 :(得分: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();
    }

}

把它放在你项目的某个地方。感谢@FacesConverter,它会自动注册。

答案 1 :(得分:-2)

您可以实现自定义转换器

http://www.roseindia.net/jsf/customconverter.shtml

希望这有帮助

相关问题