---
title: "jsf中的 国际化，验证和转换"
author: "zyl"
date: "2007-05-24T13:29:46Z"
tags: []
categories: ["非技术"]
slug: "jsf"
draft: false
lastmod: "2007-05-24T13:29:46Z"
id: 82572
url: "https://zyl.iteye.com/blog/82572"
---

这些东东，对于web框架来说，是必不可少的，来看看jsf是如何实现的。首先看一下国际化，默认的情况下，会选择默认的locale，以及相应的资源文件。当然可以通过以下方式进行配置：

```

<application>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>en</supported-locale>
<supported-locale>es</supported-locale>
</locale-config>
<message-bundle>CustomMessages</message-bundle>
</application>

```

资源文件，也是和其他web应用一致。

```

halloween=Every day is like Halloween.
numberOfVisits=You have visited us {0} time(s), {1}. Rock on!
toggleLocale=Translate to Spanish
helloImage=../images/hello.gif

```


如果需要在页面中使用相应的bundle，需要使用以下的标记：

```

<f:loadBundle basename="LocalizationResources" var="bundle"/>
<h:outputText value="#{bundle.halloween}"/>

```


当然这是使用默认的locale设置，如果想动态切换locale，目前我的处理方式是这样的：

```

<f:loadBundle basename="messages_#{localeBean.locale}" var="msg"/>

```

当然localeBean.locale的值是动态更改的，可以为en,zh_CN，等等。
个人觉得和spring 的web framework相比，没有spring的那么灵活，不过基本上都能解决问题，凑合着用吧。

如果想在代码中使用，还是需要使用以下方法：

```

public static String getMessageString(String name, Object params) {
    String str = "";
    FacesContext facesContext = FacesContext.getCurrentInstance();
    String bundleName = facesContext.getApplication().getMessageBundle();
    if (bundleName != null) {
        Locale locale = facesContext.getViewRoot().getLocale();
        ResourceBundle bundle = ResourceBundle.getBundle(bundleName,
            locale, getCurrentClassLoader(params));
        str = bundle.getString(name);
    }
    return str;
    }

```

    对于验证机制，基本的接口为Validator,只有一个方法validate。通常的验证机制，都是通过服务端来实现。如果想支持客户端支持，估计还得自己写一套接口去替换。不过看了其生命周期，觉得很难实现，除非脱离其生命周期。当然，这些使用ajax来处理，可能会减少服务端的通信负担。
   其默认的验证实现，包括以下几个：

```

   DoubleRange：<f:validateDoubleRange>
      Length：<f:validateLength>
      LongRange：<f:validateLongRange>

```

   从字面意思可以看出来。
   当然，每个组件都有默认的验证器required。只要设置其属性为ture，就会进行空值判断。
  
   对于组件来说，支持多个验证器。但是没有看到关联组件的验证器，需要自己实现。如password的是否一致

   类型转换，接口Converter，包括两个方法:

```

    public Object getAsObject(FacesContext context, UIComponent component,
                              String value);
    public String getAsString(FacesContext context, UIComponent component,
                              Object value);

```

  
  前者转化为对象，后者为用于页面输出。
  在进行验证前，都会先进行值转换。
  对于转换,内部已经提供了基本类型的实现，包括数字，日期，boolean型。
  当然Converter另外一个功能，就是提供格式化输出，支持NumberFormat和DateFormat的输出：
  包括：<f:convertDateTime>和<f:convertNumber pattern="###,###.##;(###,###.##)"/>其样式，完全采用相应的java样式。