我想创建一个JSF应用程序用户必须提供其年龄。这将默认为18并且是可编辑的(如果用户想要提供不同的值(。
如何实现此功能?
用户提供的输入值或默认值即18将保存在数据库中
<h:form>
<p:panel id="panel" header="New User">
<h:panelGrid columns="3" cellpadding="5">
<p:outputLabel for="age" value="Age:" />
<p:inputText id="age" value="#{managedBean.entityBean.age}" required="true" label="Age">
</p:inputText>
</h:panelGrid>
<p:commandButton value="Save" update="panel" action="#{managedBean.save}" />
</p:panel>
</h:form>
Entity.java
public class Entity implements Serializable {
@Column(name = "AGE")
private Integer age;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
managedBean.java
@ManagedBean(name = "managedBeanJava")
@ViewScoped
public class managedBeanJava implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory.getLogger(managedBeanJava.class);
private Entity entityBean;
public Entity getEntityBean() {
return entityBean;
}
public void setEntityBean(Entity entityBean) {
this.entityBean = entityBean;
}
private Integer age = 50;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@PostConstruct
public void init() {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, String> params = externalContext.getRequestParameterMap();
}
public void save(AjaxBehaviorEvent event) {
FacesContext facesContext = FacesContext.getCurrentInstance();
try {
entityBean.setAge(this.entityBean.getAge());
}
}
您可以直接在托管bean中定义<h:inputText>
的默认值。
private Integer age = 18;