除了我的问题"Creating an “Edit my Item”-page in Java Server Faces with Facelets"之外,我还会介绍这个问题。
当我按下commandButton时,ID = 100被移除并且页面被刷新,这是之前它甚至运行方法,对,这意味着我没有ID我按下按钮。
你是如何解决这个问题的?
拥有此Managed Bean
public class BeanWithId implements Serializable {
private String id;
private String info;
private void populateInfo() {
info = "Some info from data source for id=" + id;
}
public String getId() { return id; }
public void setId(String id) {
this.id = id;
populateInfo();
}
public String getInfo() { return info; }
public void setInfo(String info) { this.info = info; }
public String save() {
System.out.println("Saving changes to persistence store");
return null; // no navigation
}
}
并添加
<p><h:commandButton action="#{beanWithId.save}" value="Save" /></p>
到我的facelet页面。现在我在faces-config.xml中也有正确的信息,当我使用?ID = 100访问我的页面时,我确实得到了正确的Item返回。
答案 0 :(得分:1)
有几种方法可以保留原始GET网址中的ID。我并不是想要全面。
向commandLink
<h:commandLink action="#{beanWithId.save}" value="Save">
<f:param name="ID" value="#{param.ID}" />
</h:commandLink>
每次点击链接时,ID都将从参数设置。
使用隐藏字段
<h:form>
<h:inputHidden value="#{beanWithId.id}" />
<p>ID: <h:outputText value="#{beanWithId.id}" /></p>
<p>Info: <h:inputText value="#{beanWithId.info}" /></p>
<p><h:commandButton action="#{beanWithId.save}" value="Save" /></p>
</h:form>
每次发布表单时,都会从表单中设置ID。
保留网址
由于表单URL不包含原始查询,因此帖子将从浏览器栏中的URL中删除ID。执行操作后,可以通过使用服务器端重定向来纠正此问题。
public String save() {
System.out.println("Saving changes to persistence store: id=" + id);
redirect();
return null; // no navigation
}
private void redirect() {
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext ext = context.getExternalContext();
UIViewRoot view = context.getViewRoot();
String actionUrl = context.getApplication().getViewHandler().getActionURL(
context, view.getViewId());
try {
// TODO encode id value
actionUrl = ext.encodeActionURL(actionUrl + "?ID=" + id);
ext.redirect(actionUrl);
} catch (IOException e) {
throw new FacesException(e);
}
}
答案 1 :(得分:0)
如果使用JSF 1.2或更新版本,可以使用f:setPropertyActionListener设置属性。
<h:commandButton value="Save" action="#{beanWithId.save}">
<f:setPropertyActionListener target="#{beanWithId.id}" value="100" />
</h:commandButton>
如果使用JSF 1.1或更早版本,则可以使用
<f:param name="reqId" value="100" />
但是这次你必须得到参数并在动作中手动设置它,如:
public String save() {
String idParam
=FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("reqId");
setId(idParam);
return null;
}
答案 2 :(得分:0)
这解决了我的问题
<h:commandLink action="#{beanWithId.save}" value="">
<f:verbatim><input type="button" value="Save"/></f:verbatim>
<f:param name="id" value="#{beanWithId.id}"/>
</h:commandLink>
像Charm一样工作,然而它会移除可见的GET参数,但它仍然存储,以便faces-config可以访问param.id。