PrimeFacesフォーカスエラーフィールドを自動的にフォーカスする
PrimeFacesでは、フォーカスコンポーネント `<p:focus>`が有効な場合:ページが読み込まれると、最初に表示される入力フィールドにフォーカスします。検証に失敗すると、自動的に最初のエラーフィールドにフォーカスします。非常にうまく動作し、フォーム処理にコンポーネントを使用する必要があります。デフォルトで有効にしないのはなぜでしょうか?
このチュートリアルでは、簡単なサインアップフォームを表示し、 `<p:focus>`を使用してエラーフィールドに焦点を当てます。
使用されるツール:
-
PrimeFaces 3.3
-
JSF 2.1.11
-
Eclipse 4.2
-
Maven 3
-
Tomcat 7
1. SignUpフォーム
シンプルなフォーム、ユーザー名とパスワードのフィールド。
index.xhtml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<f:facet name="last">
<h:outputStylesheet library="default" name="css/style.css"/>
</f:facet>
<h1>PrimeFaces focus example</h1>
<div style="width: 500px">
<h:form>
<p:panel id="panel-signup">
<!-- enable focus component -->
<p:focus context="panel-signup"/>
<p:inputText id="username" required="true" label="username"
size="40" requiredMessage="Please enter your username."
value="#{userAction.username}">
</p:inputText>
<p:watermark for="username" value="Username ** "/>
<p:message for="username"/>
<p:password id="password" required="true" label="password" size="40"
requiredMessage="Please enter your password."
match="confirmPassword" value="#{userAction.password}"
maxlength="20">
</p:password>
<p:watermark for="password" value="Password ** "/>
<p:message for="password"/>
<p:password id="confirmPassword" required="true" size="40"
requiredMessage="Please confirm your password."
label="confirmPassword" value="#{userAction.password}"
maxlength="20">
</p:password>
<p:watermark for="confirmPassword" value="Type Password Again ** "/>
<p:message for="confirmPassword"/>
<p:commandButton value="Register" style="margin:20px"
action="#{userAction.register}" ajax="false"/>
</p:panel>
</h:form>
</div>
</h:body>
</html>
UserBean.java – 何もしないでください。すべてがOKならば、感謝のページにリダイレクトしてください。
package com.mkyong;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "userAction")
@SessionScoped
public class UserBean {
String username;
String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String register() {
return "thanks?faces-redirect=true";
}
}
デモ
図:ページがロードされ、ユーザー名フィールドである最初の入力に注目します。
最初の入力フィールド、title = “primefaces-focus-first-input”、width = 563、height = 450]にフォーカスを当ててください:image://wp-content/uploads/2012/10/primefaces-focus-first-input.png[
図:検証が失敗しました。エラーの原因となった最初のフィールドに焦点を当てます。

ソースコードをダウンロードする
ダウンロードする –
primefaces-focus-example.zip
(12 KB)
参考文献
-
http://www.primefaces.org/showcase/ui/focus.jsf
[PrimeFaces focus
コンポーネントショーケース]。
http://www.primefaces.org/docs/api/3.4/org/primefaces/component/password/Password.html
[PrimeFaces
パスワードJavaDoc]