Search code examples
jsfjsf-2viewparams

JSF Templating: f:event works, f:viewParam doesn't


Following the example of the spec, I have a template and a template client.

default.xhtml (template):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
  <title>...</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <h:outputStylesheet name="css/screen.css" />
</h:head>
<h:body>
  <f:view>
    <ui:insert name="metadata" />
    <div id="container">
      <div id="header">
        <img src="resources/gfx/logo.png" />
      </div>
      <div id="content">
        <ui:insert name="content" />
      </div>
      <div id="footer">
        <p>
          This is a project.<br />
        </p>
      </div>
    </div>
  </f:view>
</h:body>
</html>

edit.xhtml (template client):

<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  template="/WEB-INF/templates/default.xhtml">

  <ui:define name="metadata">
    <f:metadata>
      <f:viewParam name="id" value="#{myBean.id}" />
      <f:event type="preRenderView" listener="#{myBean.init}"/>
    </f:metadata>
  </ui:define>

  <ui:define name="content">
    ...
  </ui:define>
</ui:composition>

list.xhtml (the caller of the edit view) contains:

<h:commandLink action="edit" value="#{msgs.edit}">
  <f:param name="id" value="#{myentity.id}" />
</h:commandLink>

The f:event gets called, but the id (viewParam) is not assigned to the bean. The id is however present in the request parameter map and can be retrieved like this:

FacesContext ctx = FacesContext.getCurrentInstance();
Map<String, String> parameters = ctx.getExternalContext().getRequestParameterMap();
if (parameters.containsKey("id")) {
  this.id = Long.valueOf(parameters.get("id"));
}

But that's what <f:viewParam ...> should take care of (as far as I understood).

What might be wrong?


Solution

  • This is wrong.

    <h:commandLink action="edit" value="#{msgs.edit}">
      <f:param name="id" value="#{myentity.id}" />
    </h:commandLink>
    

    This sends a POST request, not a GET request.

    You need to use <h:link> instead.

    <h:link outcome="edit" value="#{msgs.edit}">
      <f:param name="id" value="#{myentity.id}" />
    </h:link>
    

    See also: