开发者

Seam: How do you use converters to derive a value from a page param?

开发者 https://www.devze.com 2023-02-22 05:27 出处:网络
I simply want to convert a URL param for the navigation, e.g. 2010, to a String like \"Season 2010/11\". I thought of a converter, used like:

I simply want to convert a URL param for the navigation, e.g. 2010, to a String like "Season 2010/11". I thought of a converter, used like:

<ui:define name="navigation">
  <li>
    <开发者_运维问答s:link view="/season-list.xhtml" value="#{seasonHome.id}" styleClass="selected" rendered="#{not empty seasonHome.id}" converter="#{startYearLabelConverter}" />
  </li>
  ...
</ui:define>

Converter Code:

@Name("startYearLabelConverter")
@BypassInterceptors
@Converter
public class StartYearLabelConverter implements javax.faces.convert.Converter
{
    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String s)
    {
        // "Season 2010/11" -> 2010 (as new Integer)
        ...
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object obj)
    {
        // 2010 (as Integer) -> "Season 2010/11"
        ...
    }
}

Obviously s:link doesn't have the "converter" attribute. How is it done as a "best practice" without having to repeat EL code like s:link ... value="Season #{seasonHome.id}/#{(seasonHome.id + 1).toString().substring(2)}"?


Converters are for "bound" properties - you read and write them back. The example you've given needs no converter.

All you've got to do is write in your SeasonHome bean a method:

public String getSeasonDescription() {
    return "Season " + id + "/" + new Integer(id + 1).toString().substring(2);
}

and then use it in your XHTML:

<ui:define name="navigation">
    <li><s:link view="/season-list.xhtml" value="#{seasonHome.seasonDescription}" styleClass="selected" rendered="#{not empty seasonHome.id}" converter="#{startYearLabelConverter}" />
    </li>
    ...
</ui:define>


we have also built some custom converters. And we found that they can be called quite nicely if you add another simple format() method to the converter like this.

@Name("myConverter")
@Converter(forClass = XXX.class)
@BypassInterceptors
public class MyConverter implements javax.faces.convert.Converter {

 /* standard asObject/asString methods skipped */

 public String format(XXX value) {
    return this.getAsString(null, null, value);
 }

Then we call this converter by it's bean name to format a value:

<f:param
   value="#{myConverter.format(value)}" />

I don't know if you need the FacesContext in your converter, but it shouldn't be a problem to get the instance when you need it.

Best regards, Alexander.

0

精彩评论

暂无评论...
验证码 换一张
取 消