JSF转换器更改选项值

时间:2012-05-16 19:57:01

标签: jsf converter

我有一个转换器,它正在更改我所有选项的值:

我首先创建selectOneMenu我有html

<select name="j_idt14:j_idt20" size="1">
        <option value="2" selected="selected">Infantil</option> //value="2"
    <option value="6">Lançamento Inverno</option>
    <option value="5">Lançamento Verão 2</option>
    <option value="4">Lançamento Preview 1</option>
    <option value="3">Feminina</option>
    <option value="7">Masculina</option>//value="7"
</select>

当我提交表单时,它会调用转换器并将其转换为object,它会使我的值(ID)变得混乱,它在第一个和最后一个上重复相同的id结果

<select name="j_idt14:j_idt20" size="1">
    <option value="2" selected="selected">Infantil</option>//value="2"
    <option value="6">Lançamento Inverno</option>
    <option value="5">Lançamento Verão 2</option>
    <option value="4">Lançamento Preview 1</option>
    <option value="3">Feminina</option>
    <option value="2">Masculina</option>//value="2" ?
</select>

这是我的converter

@FacesConverter(value = "SubGroup")
public class SubGroup implements Converter
{
    private static ProductSubgroupVO productSubgroupVO   = new ProductSubgroupVO();

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value)
    {
        productSubgroupVO.setId(Integer.valueOf(value));
        productSubgroupVO = (ProductSubgroupVO) new ProductSubgroupBO().getProductSubgroup(productSubgroupVO).toArray()[0];
        return (ProductSubgroupVO) productSubgroupVO;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value)
    {
        productSubgroupVO = (ProductSubgroupVO) value;
        String teste = String.valueOf(productSubgroupVO.getId());
        return teste;
    }
}

我注意到了一些事情,但我不知道converter是否是正确的行为,每次调用getAsObject时,最后再次调用getAsString

1 个答案:

答案 0 :(得分:1)

您的productSubgroupVO被声明为static,因此在所有转换器实例和线程之间共享。这不是线程安全的。将其删除并仅在方法局部范围内声明它。

@Override
public Object getAsObject(FacesContext context, UIComponent component, String value)
{
    ProductSubgroupVO productSubgroupVO = new ProductSubgroupVO();
    productSubgroupVO.setId(Integer.valueOf(value));
    return (ProductSubgroupVO) new ProductSubgroupBO().getProductSubgroup(productSubgroupVO).toArray()[0]
}

@Override
public String getAsString(FacesContext context, UIComponent component, Object value)
{
    ProductSubgroupVO productSubgroupVO = (ProductSubgroupVO) value;
    return String.valueOf(productSubgroupVO.getId());
}