草庐IT

java - 未在空值上调用 JSF 自定义转换器

coder 2024-03-19 原文

我为输出 java.math.BigDecimal 时创建了自定义转换器。当 BigDecimal 为 0.00 或 null 时,我想输出一个破折号。

这是我的 XHTML

<p:dataTable value="#{bean.data}" var="item">
    <p:column>
        <h:outputText value="#{item.currentValue}">
            <f:converter converterId="my.bigDecimalConverter" />
        </h:outputText>
    </p:column>
</p:dataTable>

我遇到的问题是,当#{item.currentValue} 为 null 时,转换器中的 getAsString 方法未被调用。

@FacesConverter("my.bigDecimalConverter")
public class BigDecimalConverter implements Converter {

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (context == null || component == null) {
            throw new NullPointerException();
        }                

        if (value == null) {
            System.out.println("null=");
            return "--";
        }

        System.out.print("Class=" + value.getClass());

        if (value instanceof String) {
            System.out.println("Str=" + value);
            return (String) value;
        }

        if (value instanceof BigDecimal) {
            BigDecimal bd = (BigDecimal)value;
            if (bd.equals(new BigDecimal("0.00"))) {
                return "--";
            } else {
                return bd.toPlainString();
            }
        }

        return "";
    }
}

我说它没有被调用,因为当 BigDecimal 为 null 时,我没有得到任何错误并且没有 println 语句输出。当 BigDecimal 不是 null 时,它会按预期工作,打印出“Class=class java.math.BigDecimal”,当 BigDecimal 为 0.00 时,我会得到 -- 在页面上输出。

我正在使用 JSF 2.1、Mojarra 2.1.27

我还使用以下工具来测试我的转换器。

<h:outputText value="#{null}">
    <f:converter converterId="my.bigDecimalConverter" />
</h:outputText>

阅读这个问题似乎转换器应该使用 null 值。 https://stackoverflow.com/a/19093197/50262

最佳答案

您发布的链接说转换器应该使用空值,但并没有说在每种情况下都会使用空值调用转换器。

具体来说,它并没有说转换器在 h:outputText 中并且值为 null 时将被调用。

如果您深入了解 Mojarra 资源,您会看到:

//Line 355 -- com.sun.faces.renderkit.html_basic.HtmlBasicRenderer
//method getCurrentValue

    Object currentObj = getValue(component);
    if (currentObj != null) {
        currentValue = getFormattedValue(context, component, currentObj);
    }

很明显,空值永远不会被转换!而且我找不到解决方法。

然后,如果您确实需要您的值为 null(您可以返回 0 或其他内容),我认为您唯一的机会是制作自定义渲染器。这很容易:

您编写了一个覆盖重要方法的渲染器:

package my;

import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;

import com.sun.faces.renderkit.html_basic.TextRenderer;

public class HtmlCustomRenderer extends TextRenderer {

    @Override
    public String getCurrentValue(FacesContext context, UIComponent component) {

        if (component instanceof UIInput) {
            Object submittedValue = ((UIInput) component).getSubmittedValue();
            if (submittedValue != null) {
                // value may not be a String...
                return submittedValue.toString();
            }
        }

        String currentValue = null;
        Object currentObj = getValue(component);
        //Remove the 'if' to call getFormattedValue even if null
        currentValue = getFormattedValue(context, component, currentObj);
        return currentValue;

    }

}

然后我们在 faces-config.xml 中声明渲染器:

<render-kit>
    <renderer>
        <component-family>javax.faces.Output</component-family>
        <renderer-type>javax.faces.Text</renderer-type>
        <renderer-class>my.HtmlCustomRenderer</renderer-class>
    </renderer>
</render-kit>

现在您的转换器将使用空值调用!

希望对您有所帮助!

关于java - 未在空值上调用 JSF 自定义转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27048438/

有关java - 未在空值上调用 JSF 自定义转换器的更多相关文章

  1. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  2. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  3. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  4. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  5. ruby-on-rails - 未在 Ruby 中初始化的对象 - 2

    我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调

  6. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  7. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  8. ruby - 定义方法参数的条件 - 2

    我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano

  9. ruby - 如何在 Grape 中定义哈希数组? - 2

    我使用Ember作为我的前端和GrapeAPI来为我的API提供服务。前端发送类似:{"service"=>{"name"=>"Name","duration"=>"30","user"=>nil,"organization"=>"org","category"=>nil,"description"=>"description","disabled"=>true,"color"=>nil,"availabilities"=>[{"day"=>"Saturday","enabled"=>false,"timeSlots"=>[{"startAt"=>"09:00AM","endAt"=>

  10. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

随机推荐