【问题标题】:Handling currency using <h:selectOneMenu> in JSF在 JSF 中使用 <h:selectOneMenu> 处理货币
【发布时间】:2014-05-05 09:17:54
【问题描述】:

我在模板&lt;p:layoutUnit position="north".../&gt; 的标题上使用&lt;h:selectOneMenu&gt;,如下所示。

<h:selectOneMenu value="#{currencyRateBean.currency}" onchange="submit();">
    <f:selectItems var="row" value="#{currencyBean.currency}" itemLabel="#{row}" itemValue="#{row}"/>
</h:selectOneMenu>

此列表使用代表货币列表的List&lt;String&gt; 填充。该列表存储在应用程序范围的 bean 中,CurrencyBean

涉及的JSF托管bean如下。

@ManagedBean
@SessionScoped
public final class CurrencyRateBean implements Serializable
{
    private static final long serialVersionUID = 1L;
    private String currency;
    private BigDecimal currencyRate;

    public CurrencyRateBean() {}

    @PostConstruct
    private void init()
    {
        currencyRate=new BigDecimal(1);
    }

    public BigDecimal getCurrencyRate() {
        return currencyRate;
    }

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String currency) throws MalformedURLException, IOException
    {
        BufferedReader in = null;
        URLConnection connection;

        try
        {
            URL url = new URL("http://www.exchangerate-api.com/INR/"+currency+"/1?k=FQRxs-xT2tk-NExQj");
            connection = url.openConnection();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String jsonObject = "";
            String line;

            while ((line = in.readLine()) != null)
            {
                jsonObject += line;
            }

            this.currencyRate = new Gson().fromJson(jsonObject, BigDecimal.class);
            this.currency = currency;
        }
        finally
        {
            if(in!=null){in.close();}
        }
    }
}

setCurrency() 方法在更改&lt;h:selectOneMenu&gt; (onchange="submit();") 中的货币时调用,这是一个 POST 请求

此请求完成后,刷新页面时会出现重复页面提交。为了避免这种重复提交,在发出这个 POST 请求之后应该产生一个 GET Http 请求。

这是怎么做到的?

如果有更好的、新的、精确的替代方案来处理多币种应用程序,请提出建议。

【问题讨论】:

  • 这取决于您真正需要和想要的。是否需要实时货币数据或以固定时间间隔(如每 1 天、1 小时、1 分钟或 x 频率)获得的数据?您可以简单地拥有一个容器管理的计时器,用于更新应用程序范围 bean 中的货币数据。然后,您可以在 Web 应用程序的任何其他部分使用该应用程序范围的数据。这很好用并且可以减少过载。
  • 问题与货币无关。实时汇率是从给定的 URL 正确获取的。问题是关于重复提交的表单(即使在这种情况下重复提交,不执行任何多功能,我非常不喜欢它)。
  • 去掉onchange事件监听器,使用p:ajax

标签: jsf currency jsf-2.2


【解决方案1】:

试试这个,并尽可能避免onchange

<h:selectOneMenu value="#{currencyRateBean.currency}">
<p:ajax event="valueChange" update="here write the id(s) of component(s) or "@all" to rerender the whole page (which is really bad)" process="@this" partialSubmit="true"/>
<f:selectItems var="row" value="#{currencyBean.currency}" itemLabel="#{row}" itemValue="#{row}"/>
</h:selectOneMenu>

【讨论】:

  • 我可以知道partialSubmit&lt;p:ajax&gt;这里的用法吗?
猜你喜欢
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 2021-12-27
  • 2018-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-22
相关资源
最近更新 更多