从inputText到URL有任何标准的JSF转换器吗? [英] Is there any standard JSF converter from inputText to URL?

查看:116
本文介绍了从inputText到URL有任何标准的JSF转换器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to convert inputText to java.net.URL in JSF page:

...
<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;
}

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

Should I implement the converter from scratch or there is some other way?

推荐答案

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

Yes, you need to implement a Converter. It's not that hard for this particular case:

@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 它会自动注册。

Put it somewhere in your project. Thanks to the @FacesConverter it'll register itself automagically.

这篇关于从inputText到URL有任何标准的JSF转换器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆