【问题标题】:Binding JSF inputText to a HashMap doesn't work将 JSF inputText 绑定到 HashMap 不起作用
【发布时间】:2014-11-02 01:52:20
【问题描述】:

我正在尝试将多个 inputText 字段绑定到 HashMap<Integer, String>。但它没有为HashMap 赋予任何价值。

这里是 JSF 页面。

<ui:repeat  value="#{questionBean.question.answerCollection}" var="answer">                
    <h:inputText  value="#{questionBean.newComments[answer.answerId]}"></h:inputText>
    <br/>
    <h:commandButton value="Add Comment">
                    <f:ajax event="click" listener="#{questionBean.makeComment(answer)}"></f:ajax>
    </h:commandButton>
</ui:repeat>

这里是backing bean的相关部分。

private Map<Integer, String> newComments = new HashMap<Integer, String>();
...

public void makeComment(Answers answer) throws Exception {
    String username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();

    Users user = userFacade.getUserByUsername(username);

    Comments comment = new Comments();

    for(Integer key: newComments.keySet()){
        throw new Exception("Answer ID IS :"+key);
        // It doesn't throw any exception in here.
        // The map is empty.
    }        

    String commentContent = newComments.get(answer.getAnswerId());
    if(commentContent == null){
        throw new Exception("Content Is NULL");
        // It throws exception here.
    }

    comment.setCommentContent(newComments.get(answer.getAnswerId()));
    comment.setDateCreated(new java.sql.Date(Calendar.getInstance().getTimeInMillis()));
    comment.setAnswerId(answer);
    comment.setUserId(user);
    commentFacade.create(comment);
}

这段代码可能有什么问题?

【问题讨论】:

    标签: jsf jsf-2 map el


    【解决方案1】:

    主要的错误是&lt;f:ajax&gt; 也没有被告知要处理输入字段。它的execute 事件默认为@this,意思是“当前组件”。因此,使用此构造,将只处理 &lt;h:commandButton&gt;(即其操作将被解码、排队和调用)。

    因此,通过明确告诉它处理整个表单来相应地修复它:

    <f:ajax execute="@form" ... />
    

    下一个(潜在的)错误是依赖于 EL 实现的,但目前它们都不支持泛型。 Map&lt;K, V&gt; 将被简单地视为Map,没有任何键和值的隐式/自动转换。在 EL 中,数值被隐式解释为Long。在您的特定情况下,Map 将填充 Long 键而不是 Integer 键,可能会在迭代它时导致 ClassCastException。如果您相应地修复模型以使用Long 而不是Integer,那么这个问题也应该得到解决。

    私有映射 newComments = new HashMap();


    与具体问题无关,在前端使用java.sql.* 模型是一个非常糟糕的主意。而是在数据库端使用它。

    【讨论】:

    • 您能否给出一个简短的解释或参考,为什么使用 Java.sql.Date 是个坏主意?谢谢
    • @stg: stackoverflow.com/questions/3323618/… 在模型中使用持久层特定的类是紧耦合的。只需始终使用java.util.Date,并且仅在您绝对需要进行转换的时候进行转换(即在您需要进行preparedStatement.setDate() 的时候)。此外,JSF 日历/日期选择器组件也不支持java.sql.* 日期/时间类。他们会尝试在模型中设置java.util.Date 的实例,结果是属性未找到异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    • 2022-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多