当按下回车键时,Jsf从输入文本调用bean方法



JSF 2.0、Mojarra 2.0.1、PrimeFaces 3.4.1

这里有一个p:inputText组件,当按下回车键时,它将调用一个backingbean方法。

<p:inputText id="commentInput" rendered="#{status.haveComment}" 
    value="#{statusBean.newComment}"
    onkeypress="if (event.keyCode == 13) { onchange(); return false; }">
    <f:ajax event="change" listener="#{statusBean.test}" />
</p:inputText>

而backingbean的方法是:

public void test(AjaxBehaviorEvent event) {
   System.out.println("Pressed enter!");
}

当回车键被按下时,它调用方法,但它不止于此意外行为案例:

--Click input text
----Type some letters
------Click somewhere else in the page
--------CONSOLE: Pressed enter!

我认为ajax event=change以某种方式检测到更改并调用该方法。如何将这个p:inputText组件转换为像Facebook或其他人一样的适当的评论接受组件?

这是onchange事件在HTML中的工作方式。当输入元素中的文本发生更改时,就会发生这种情况,但当组件失去焦点时(在您的情况下,就是您单击页面中其他位置时),就会触发这种情况。

你可以为test方法定义p:remoteCommand,只需写:

<p:remoteCommand name="test" actionListener="#{statusBean.test}"/>
<p:inputText id="commentInput" rendered="#{status.haveComment}" 
  value="#{statusBean.newComment}"
  onkeypress="if (event.keyCode == 13) { test(); return false; }"/>

以及在后台bean中:

public void test() {
 System.out.println("Pressed enter!");
}

对于较新的PrimeFaces版本(至少5+),您可以使用p:defaultCommand而不是脚本。尽管您不能使用p:remoteCommand,因为p:defaultCommand需要一些可点击的东西。

<p:inputText id="input" />
<p:defaultCommand target="submit" />
<!--you can show the button to allow the user to click too, or hide it with display: none-->
<p:commandButton id="submit" style="display: none;" process="input" />

默认情况下,p:defaultCommand应用于整个表单。您可以使用scope属性来限制它。

最新更新