LoginSignup
5
6

More than 5 years have passed since last update.

JSFのFormでGETもどきを実装する

Last updated at Posted at 2016-07-07

JSFのFormを出力するタグ h:form には method 属性がない。強制的に POST でリクエストされる。
登録や更新ならそれでもいいけれど、検索フォームの時に POST は違和感が残る。リロードすると「フォームの内容を再送信しますか?」のようなメッセージがでてしまうからだ。

要するに GET

http://hoge.com/search?id=2&name=taro

のようにしたいのでやってみる。

View

<f:metadata>
  <!-- クエリパラメータをセットして初期化処理を呼ぶ -->
  <f:viewParam name="id" value="#{sampleController.id}" />
  <f:viewParam name="name" value="#{sampleController.name}" />
  <f:viewAction action="#{sampleController.init()}" />
</f:metadata>

<h:form>
  <!-- 普段と変わらないForm -->
  <h:inputText value="#{sampleController.id}" />
  <h:inputText value="#{sampleController.name}" />
  <h:commandButton value="検索" action="#{sampleController.search()}" />
</h:form>

BackingBean

@Getter
@Setter
private String id;

@Getter
@Setter
private String name;

public void init(){
  //idとnameを条件にして検索
}

public String search(){
  //パラメータをつけてリダイレクト
  //※ パラメーターに null とかでないようにちゃんとしてね
  return String.format("search.xhtml?faces-redirect=true&id=%s&name=%s",id,name);
}

こんなふうにすると

検索ボタン - POST -> アクションメソッド - GET -> 検索メソッド

のような流れになって GET で検索しているようにできる。なので もどき
h:commandButtonf:paramincludeViewParams=true を組み合わせればアクションメソッドなしでもできるかもしれない。

以上。

5
6
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
5
6