在PrimeFaces中,如果启用了焦点组件<p:focus>
:加载页面时,它将聚焦于第一个可见的输入字段; 如果验证失败,它将自动关注第一个错误字段。 它工作得非常好,并且在表单处理中必须使用组件。 只是想知道为什么不默认启用它?
在本教程中,我们将向您展示一个简单的注册表单,使用<p:focus>
专注于错误字段。
使用的工具 :
- PrimeFaces 3.3
- JSF 2.1.11
- Eclipse 4.2
- Maven 3
- 雄猫7
1.注册表格
一个简单的表单,用户名和密码字段。
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 – Do nothing, if everything is ok, redirect to thanks page.
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";
}
}
2.演示
http:// localhost:8080 / primefaces / index.jsf
图片:页面已加载,重点放在第一个输入,即用户名字段。
图片:验证失败,重点放在引起错误的第一个字段上。
下载源代码
下载它– primefaces-focus-example.zip (12 KB)
参考文献
翻译自: https://mkyong.com/jsf2/primefaces/primefaces-focus-error-field-automatically/