带有参数的JSF 2中的自定义转换器

时间:2012-07-23 13:05:18

标签: jsf jsf-2 converter

我正在尝试实现一个自定义截断转换器,它会截断给定索引处的字符串并添加一个连续符号。只有当我对参数进行硬编码时,转换器才能正常工作,因为它们没有传递给后端。我做错了什么?

参数是转换器类的属性:

@FacesConverter(value = TruncateConverter.CONVERTER_ID)
public class TruncateConverter implements Converter, StateHolder
{
    public static final String CONVERTER_ID = "bla.blablabla.Truncate";

    private int truncateIndex;
    private String contSymbol;

以下是我如何使用转换器(或尝试):

<h:outputText id="news-text-left" value="#{newsListBean.newsList_teaser.text}">
    <f:converter converterId="bla.blablabla.Truncate" truncateIndex="150" contSymbol="..." />
</h:outputText>

我用Google搜索了很多内容并且无法找到带参数的JSF2转换器的单个示例...谢谢大家的帮助,非常感谢!

4 个答案:

答案 0 :(得分:23)

您可以查看JSF2.0源代码。例如,DateTimeConverter ... JSF源代码可以在svn reposotory中找到:https://svn.java.net/svn/mojarra~svn/trunk

IMO创建这样的转换器并不容易。它还需要创建转换器标签以注册转换器。

将一些数据传递给转换器的其他方法是attibutes。所以你可以写

<h:outputText ...>
  <f:converter converterId="bla.blablabla.Truncate" />
  <f:attribute name="truncateIndex" value="150"/>
</h:outputText>

打电话给component.getAttributes().get("truncateIndex"); 在转换器代码中。

答案 1 :(得分:4)

http://jerryorr.blogspot.nl/2011/10/creating-jsf-12-custom-converter-with.html是使用参数设置第一个自定义转换器的好指南

答案 2 :(得分:4)

基于@Maks解决方案:可以将转换器和属性合并到一个标记中:

<facelet-taglib version="2.2"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facelettaglibrary_2_2.xsd">
    <namespace>http://mycompany.com/some-identifier</namespace>
    <tag>
        <tag-name>truncate</tag-name>
        <converter>
            <converter-id>bla.blablabla.Truncate</converter-id>
        </converter>
        <attribute>
            <name>truncateIndex</name>
        </attribute>
    </tag>
</facelet-taglib>

然后您可以像这样使用转换器:

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:my="http://mycompany.com/some-identifier">

  <my:truncate truncateIndex="150" />

</ui:composition>

您也不需要从组件属性中获取参数。将自动填充具有相同名称的bean属性:

@FacesConverter("bla.blablabla.Truncate")
public class Truncate implements Converter {

    private String truncateIndex;

    // getters + setters

    ...

}

答案 3 :(得分:0)

这是我做的(在一个单独的jar文件中,并使用maven的默认目录):

1)创建转换器的类(在src / main / java中)

2)创建.taglib.xml类(在src / main / resources / META-INF内)

3)创建faces-config.xml(在src / main / resources / META-INF内)

示例:

步骤1)

package com.ocabit.jsf.converter;



import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;

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;

import org.springframework.stereotype.Service;

import com.ocabit.utils.currency.CurrencyUtils;


/**
 * Converter para valores BigDecimal.
 * 
 * @author Carlos Eduardo Pauluk
 * 
 */
@FacesConverter("bigDecimalConverter")
@Service("bigDecimalConverter")
public class BigDecimalConverter implements Converter, Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public static final String CONVERTER_ID = "com.ocabit.jsf.converter.BigDecimalConverter";

    /**
     * Em caso de null, força a saída para 0.0;
     */
    private boolean nullToZero = false;

    /**
     * Em caso de zero, força a saída para null;.
     */
    private boolean zeroToNull = false;

    /**
     * Só retorna números positivos.
     */
    private boolean onlyAbs = false;

    /**
     * Só retorna números negativos.
     */
    private boolean onlyNeg = false;

    /**
     * Quantidade de casas decimais.
     */
    private int decimals = 2;

    @Override
    public Object getAsObject(final FacesContext context, final UIComponent component, final String value) {
        try {
            BigDecimal bd = new BigDecimal(value);
            bd = bd.setScale(getDecimals(), RoundingMode.HALF_DOWN);

            if (bd.equals(BigDecimal.ZERO) && isZeroToNull()) {
                return null;
            }

            if (isOnlyAbs()) {
                bd = bd.abs();
            }
            if (isOnlyNeg()) {
                bd = bd.abs();
                bd = bd.negate();
            }

            return bd;
        } catch (final Exception e) {
            BigDecimal bd = null;
            if (isNullToZero()) {
                bd = CurrencyUtils.getBigDecimalCurrency("0.0");
                bd = bd.setScale(getDecimals(), RoundingMode.HALF_DOWN);
            }
            return bd;
        }
    }

    @Override
    public String getAsString(final FacesContext context, final UIComponent component, final Object value) {
        if (!(value instanceof BigDecimal)) {
            throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro ao converter o valor decimal.", ""));
        }

        final NumberFormat nf = NumberFormat.getInstance();
        // sempre terá 2 casas decimais
        nf.setMinimumFractionDigits(2);
        nf.setMaximumFractionDigits(2);
        return nf.format(((BigDecimal) value).doubleValue());
    }

    public boolean isNullToZero() {
        return nullToZero;
    }

    public void setNullToZero(boolean nullToZero) {
        this.nullToZero = nullToZero;
    }

    public boolean isZeroToNull() {
        return zeroToNull;
    }

    public void setZeroToNull(boolean zeroToNull) {
        this.zeroToNull = zeroToNull;
    }

    public boolean isOnlyAbs() {
        return onlyAbs;
    }

    public void setOnlyAbs(boolean onlyAbs) {
        this.onlyAbs = onlyAbs;
    }

    public boolean isOnlyNeg() {
        return onlyNeg;
    }

    public void setOnlyNeg(boolean onlyNeg) {
        this.onlyNeg = onlyNeg;
    }

    public int getDecimals() {
        return decimals;
    }

    public void setDecimals(int decimals) {
        this.decimals = decimals;
    }

}

步骤2)

<!DOCTYPE facelet-taglib PUBLIC
    "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
    "facelet-taglib_1_0.dtd">
<facelet-taglib version="2.2"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facelettaglibrary_2_2.xsd">
    <namespace>http://ocabit.com.br/facelets</namespace>


    <tag>
        <tag-name>convertBigDecimal</tag-name>      
        <converter>
            <converter-id>com.ocabit.jsf.converter.BigDecimalConverter</converter-id>           
        </converter>    
    </tag>


</facelet-taglib>

步骤3)

<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
        http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
    version="2.2">

    <converter>
        <description></description>
        <converter-id>com.ocabit.jsf.converter.BigDecimalConverter</converter-id>
        <converter-class>com.ocabit.jsf.converter.BigDecimalConverter</converter-class>
        <property>
            <property-name>nullToZero</property-name>
            <property-class>boolean</property-class>
            <description>Ao invés de retornar 'null', retorna '0.0'</description>
        </property>
        <property>
            <property-name>zeroToNull</property-name>
            <property-class>boolean</property-class>
            <description>Ao invés de retornar '0.0', retorna 'null'</description>
        </property>
        <property>
            <property-name>onlyAbs</property-name>
            <property-class>boolean</property-class>
            <description>Somente retorna números positivos</description>
        </property>
        <property>
            <property-name>onlyNeg</property-name>
            <property-class>boolean</property-class>
            <description>Somente retorna números negativos</description>
        </property>
        <property>
            <property-name>decimals</property-name>
            <property-class>int</property-class>
            <description>Quantidade de casas decimais</description>
        </property>
    </converter>


</faces-config>

瞧。