LoginSignup
1
0

More than 5 years have passed since last update.

jCaptchaリロードをajaxで実装

Last updated at Posted at 2018-02-07

環境

  • windows7
  • java7
  • javaServerFaces2.2
  • glassfish4.1

やりたいこと

jcaptchaをリロードボタンクリックでajaxを利用して再描画
画面ごとリロードすればjcaptchaもリロードされるけど・・・

方法

成功例

xhtml
<!-- jcaptcha表示部 -->
<div class="jcaptchaItemBlook">
  <h:graphicImage id="jcaptchaImage" value="/jcaptcha" />
</div>

<!-- ajax実装部 -->
<h:commandButton class="jcaptchaReloadBtn" value="画像更新" immediate="true">
  `<f:ajax listener="#{controller.reload}" render="jcaptchaImage" event="click" />
</h:commandButton>
java
public String reload() throws CaptchaServiceException {
     return "#{request.contextPath}/jcapcha" + Math.floor(Math.random() * 100);
}

失敗例

xhtml
<!-- jcaptcha表示部 -->
<div class="jcaptchaItemBlook">
  <img id="jcaptchaImage"  src="#{request.contextPath}/jcaptcha" />
</div>

説明など

  • 失敗例の記載以外の部分は、成功例と同様です。
  • imgタグだとajaxの戻り値としてvalueを設定できなかったので、graphicImageを採用
  • xhtml側のgraphicImageタグに"#{request.contextPath}/jcapcha"を設定すると、contextPathが2重に表示されたので削除
  • java側は逆に戻り値として"#{request.contextPath}/jcapcha"をつけてあげる必要がある

事件発生!

  • chromeでは問題なく動作するのに、FireFoxとIEではrefreshされないという問題がテスト時に発覚!

対応方法

xhtml
<!-- jcaptcha表示部 -->
<div class="jcaptchaItemBlook">
  <p:graphicImage id="jcaptchaImage" value="/jcaptcha" cache="false" />
</div>
  • primeFacesのタグに変更する必要があった。
  • cache="false"を追記する。

最終例

xhtml
<!-- jcaptcha表示部 -->
<h:panelGroup class="jcaptchaItemBlook">
  <p:graphicImage id="jcaptchaImage" value="/jcaptcha" cache="false" />
</h:panelGroup>

<!-- ajax実装部 -->
<h:commandButton class="jcaptchaReloadBtn" value="画像更新" immediate="true">
  <f:ajax listener="#{controller.reload}" render="jcaptchaImage" event="click" />
</h:commandButton>
java
@Getter
@Setter
private String captchaImage;
public void reload() throws CaptchaServiceException {
  this.setCaptchaImage("/jcaptcha");
} 
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0