jsf.ajax.request: Method must be called within a formとなった時の対応方法


  • 環境
    • CentOS Linux release 7.8.2003 (Core)
    • Eclipse IDE for Enterprise Java Developers.Version: 2020-03 (4.15.0)
    • openjdk version "11.0.7" 2020-04-14 LTS
    • JSF 2.3.9

事象 : f:ajaxを使った処理を実行したら怒られた

なんか動かないと思ったら、Chromeの開発ツールのConsoleにエラーが出ていた

Chromeの開発ツールのConsoleに出たエラー
jsf.js.jsf?ln=javax.faces:1 Uncaught Error: jsf.ajax.request: Method must be called within a form
    at Object.request (jsf.js.jsf?ln=javax.faces:1)
    at Object.ab (jsf.js.jsf?ln=javax.faces:1)
    at HTMLInputElement.onclick (upload.jsf:12)

原因 : formタグがないから

うっかりformタグを忘れていた。

xhtml
<body>
<!--省略-->
    <h:commandButton value="閉じる" action="#{uploadBean.close}">
      <f:ajax onevent="windowClose" />
    </h:commandButton>
  </div>
</body>
出力されたhtml
<input id="j_idt11:j_idt14" type="submit" name="j_idt11:j_idt14" value="閉じる" onclick="mojarra.ab(this,event,'action',0,0,{'onevent':windowClose});return false">

対応 : formタグの中にf:ajaxを配置する

xhtml
<body>
  <h:form>
<!--省略-->
      <h:commandButton value="閉じる" action="#{uploadBean.close}">
        <f:ajax onevent="windowClose" />
      </h:commandButton>
    </div>
  </h:form>
</body>