15

在 JSF+Seam 中更改语言环境的最常见方法之一 - 使用<h:selectOneMenu>

<h:form  action="#{localeSelector.select}" rendered="false">
    <h:selectOneMenu value="#{localeSelector.language}" onchange="submit()">
        <f:selectItem itemLabel="English" itemValue="en" />
        <f:selectItem itemLabel="Francais" itemValue="fr" />
    </h:selectOneMenu>
</h:form>

我想用按钮实现语言环境更改。所以,问题是 - 如何传递参数(en、fr 等)来更新 bean <h:commandButton>?也许<h:inputHidden>会有帮助?

4

1 回答 1

30

要么作为方法参数传递(仅当您的环境支持 EL 2.2 时),

<h:commandButton value="English" action="#{localeSelector.change('en')}" />
<h:commandButton value="Deutsch" action="#{localeSelector.change('de')}" />
<h:commandButton value="Français" action="#{localeSelector.change('fr')}" />

public void change(String language) {
    locale = new Locale(language);
    // ...
}

或使用<f:setPropertyActionListener>

<h:commandButton value="English" action="#{localeSelector.change}">
    <f:setPropertyActionListener target="#{localeSelector.language}" value="en" />
</h:commandButton>
<h:commandButton value="Deutsch" action="#{localeSelector.change}">
    <f:setPropertyActionListener target="#{localeSelector.language}" value="de" />
</h:commandButton>
<h:commandButton value="Français" action="#{localeSelector.change}">
    <f:setPropertyActionListener target="#{localeSelector.language}" value="fr" />
</h:commandButton>

private String language;

public void change() {
    locale = new Locale(language);
    // ...
}

或使用<f:param>

<h:commandButton value="English" action="#{localeSelector.change}">
    <f:param name="language" value="en" />
</h:commandButton>
<h:commandButton value="Deutsch" action="#{localeSelector.change}">
    <f:param name="language" value="de" />
</h:commandButton>
<h:commandButton value="Français" action="#{localeSelector.change}">
    <f:param name="language" value="fr" />
</h:commandButton>

public void change() {
    locale = new Locale(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("language"));
    // ...
}

(您也可以让 JSF 通过 a 自动设置它@ManagedProperty("#{param.language}"),但这需要 bean 是请求范围的,或者 a <f:viewParam>,另请参见ViewParam 与 @ManagedProperty(value = "#{param.id}")


将参数从视图传递到控制器的足够方法。任你选。在<h:inputHidden>JSF 上下文中,它的用途有些不同,它只能由 JavaScript 操作,onclick这很丑陋。

于 2012-10-24T12:31:07.253 回答