"getasstring() jsf customed converter fails to convert object" Code Answer


just don't throw an exception when null or an empty value is received. this makes no sense. they may represent legitimately valid values which just represent "no value". just return null then. if you'd like to force requireness, then you should be using required="true" instead or any custom validator, but just don't do that in a converter.

you should throw the converterexception only when the value is really unconvertable. i've improved your converter to do exactly that. you are namely not checking if the submitted value is a valid number nor if the obtained model value is an instance of product. it would otherwise have caused numberformatexception or classcastexception further down in the code which you should have prevented beforehand by throwing the appropriate converterexception.

public class productconverter implements converter {

    private productejb productejb;

    public object getasobject(facescontext context, uicomponent component, string value) {
        if (value == null || value.isempty()) {
            return null;

        if (!value.matches("\d+")) {
            throw new converterexception("the value is not a valid id number: " + value);

        int id = integer.parseint(value);
        return productejb.findproductbyid(id);
        // you may want to perform an additional check if it didn't return null
        // and otherwise throw converterexception with "unknown product id".

    public string getasstring(facescontext context, uicomponent component, object value) {        
        if (value == null) {
            return null; // or an empty string, can also.

        if (!(value instanceof product)) {
            throw new converterexception("the value is not a valid product: " + value);

        integer id = ((product)value).getproduct_id();
        return (id != null) ? string.valueof(id) : null;

By joshowen on April 21 2022

Answers related to “getasstring() jsf customed converter fails to convert object”

Only authorized users can answer the Search term. Please sign in first, or register a free account.