1

除了我的问题“使用 Facelets 在 Java Server Faces 中创建“编辑我的项目”页面”之外,我还想介绍一个问题。

当我按下 commandButton 时,ID=100 被删除并刷新页面,这是它运行该方法之前,对,所以这意味着当我按下按钮时我没有 ID。

你如何解决这个问题?

通过拥有这个托管 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 返回。

4

3 回答 3

1

有几种方法可以保留原始 GET URL 中的 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 不包含原始查询,因此帖子将从浏览器栏中的 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);
    }
  }
于 2009-10-07T12:30:35.990 回答
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;
}
于 2009-10-07T11:21:27.293 回答
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。

于 2009-10-07T12:23:56.857 回答