开发者

Is there any standard JSF converter from inputText to 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" /&g开发者_如何学Pythont;
</h:form>
...

My backed bean is:

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

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


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();
    }

}

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


you can implement a Custom Converter

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

Hope this helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜