tags:

views:

21

answers:

2

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

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?

A: 

you can implement a Custom Converter

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

Hope this helps

ErVeY
That site is however the [worst Java/JSF source](http://balusc.blogspot.com/2008/06/what-is-it-with-roseindia.html) one can ever recommend to a beginner. Rather suggest another sources.
BalusC
Sorry about that O.o i didn't know thisI'm a begginer too and i trying to implement jsf and icefaces and don't find goods code examples, i'll try hard for the next time ;D
ErVeY
No worries. You are yourself a beginner as well. That site is maintained by amateurs targeting on advertisement incomes only. Almost every code snippet shows/introduces bad practices in one or other way. That customconverter article for example should better have used a `SimpleDateFormat` to convert between Date and String. Also, the fact that JSF has builtin date/time converters is not mentioned at all.
BalusC
@BalusC you are so right. I tought JSF to me myself and unfortunately that site pops up quite often if you google for solutions. 90% of the time, i cursed that site for showing me real bullsh**, I can only advise everybody to avoid it.
f1sh
+1  A: 

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

package mypackage;

import java.net.MalformedURLException;
import java.net.URL;

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(forClass=URL.class)
public class URLConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        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) {
        return value.toString();
    }

}

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

BalusC
Many thanks! :)
Vincenzo
You're welcome. Please note the edit; I was forgotten the `FacesMessage`. It is the one which is to be displayed in a `h:message(s)`.
BalusC