Passing a Character (vs passing String) to backing bean method in EL

前端 未结 2 906
隐瞒了意图╮
隐瞒了意图╮ 2021-01-23 02:51

I would like to call a setter directly from a command button and pass a value. My problem is that the setter is expecting a Character and jsf if passing it back as a String. Is

相关标签:
2条回答
  • 2021-01-23 03:18

    I have tried to use simple quotes directly without using charAt(0) tips ...

    and this work correctly when parameter type is char or Character.

    Example passing a character:

    #{manageItemHandler.dataEntryOp.setBomComplete('Y')}
    

    Example passing a String literal and a character constant:

    <p:panel style="border:none;#{vC.traceUpdate('p:panel','X')}">
    

    The code of traceUpdate() java method is following:

    @ManagedBean(name = "vC")
    @ViewScoped
    public class ActionViewController
    extends AbstractViewController
        {
        public String traceUpdate(String s, Character c)
            {
            System.out.println("s:" + s + " " + c);
            return "";
            }
    

    OR

    @ManagedBean(name = "vC")
    @ViewScoped
    public class ActionViewController
    extends AbstractViewController
        {
        public String traceUpdate(String s, char c)
            {
            System.out.println("s:" + s + " " + c);
            return "";
            }
    

    where Character as been replace by char

    This example run on Glassfish 4.1 using Primefaces 6.2.4.

    0 讨论(0)
  • 2021-01-23 03:27

    This is unfortunately by design. Everything in quotes is in EL treated as String. A workaround would be to pass String#charAt() instead.

    #{manageItemHandler.dataEntryOp.setBomComplete('Y'.charAt(0))}
    

    This is only ugly. An alternative is to pass its int codepoint instead, which is 89 for Y.

    #{manageItemHandler.dataEntryOp.setBomComplete(89)}
    

    But this is not exactly self-documenting. Much better is to just make use of enums.

    public enum Choice {
        Y, N;
    }
    

    with

    protected Choice bomComplete;
    

    which you can just invoke the desired way

    #{manageItemHandler.dataEntryOp.setBomComplete('Y')}
    

    The string 'Y' will be automatically converted to that enum. As a bonus, enums have many more additional advantages, such as compile time type safety.

    0 讨论(0)
提交回复
热议问题