`

jee6 学习笔记 10: Internationalizing the web app

    博客分类:
  • JEE
阅读更多

Making a web app to support multiple languages.

 

This is achieved in JSF2 by using message properties files (resource bundles) and load the correct key/value pair from these resource files, based on the current locale the web application is set.

 

One configuration is in the "faces-config.xml", to setup the default locale and the location of the messages files. JSF would load these resources once accessed.

 

Here's the relevant section in "faces-config.xml":

 

<application>
   	<locale-config>
   	   	<default-locale>en</default-locale>
   	   	<supported-locale>zh</supported-locale>
   	 </locale-config>
	 <resource-bundle>
		<base-name>com.jxee.messages</base-name>
		<var>msgs</var>
	</resource-bundle>
</application>

 

Note: According to the above configuration, the message resource bundle should reside in this directory: "web_application_classpath_root/com/jxee". This means that a valid place would be "WEB-INF/classes/com/jxee". Since we are supporting English and Chinese in this example, two resource files should be created, one for English and one for Chinese.

 

The following is the proejct directory screen shot for these two files:


 

The JSF pages need to set the current locale when rendering the pages. This can be done by the following code ( Since every page needs to set this property, the template is a good place to put it):

 

<f:view locale="#{langBean.appLocale}">

 

 

This example enables the web application user to choose the language, by using a Primefaces context menu. The backing bean of the context menu would set the current local for the web application.

 

Here's the context menu soruce (again, the template is a good place to include it):

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">
    <h:form>
	<p:contextMenu>
	    <p:menuitem value="#{msgs.english}" 
	    	actionListener="#{langBean.change2English}" 
	    	rendered="#{langBean.appLocale.language != 'en'}" 
	    	immediate="true" ajax="false"/>
	    	
	    <p:menuitem value="#{msgs.chinese}" 
	    	action="#{langBean.change2Chinese}" 
	    	rendered="#{langBean.appLocale.language != 'zh'}" 
	    	immediate="true" ajax="false"/>
	    	
	    <p:separator/>
	    
	    <p:menuitem value="Primefaces Homepage" url="http://www.primefaces.org"/>  
	</p:contextMenu>
	</h:form>
</html>
 

One thing need to mention in the above code is that since we use Primefaces tags, we need to set attribute ajax="false" , in order to make the form submitted and re-rendered, after the backing bean change the current locale for the whole application. Otherwise it would only change the labels with a refresh/redirect.

 

Here's the backing bean for the above context menu to change the application locale:

 

package com.jxee.action;

import java.io.Serializable;
import java.util.Locale;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.log4j.Logger;
 
@SessionScoped
@ManagedBean(name="langBean")
public class LocaleBean implements Serializable{
 
  private static Logger log = Logger.getLogger(LocaleBean.class);
  private Locale appLocale = Locale.ENGLISH;
  
  @PostConstruct
  public void init() {
    FacesContext.getCurrentInstance().getViewRoot().setLocale(this.appLocale);
    log.debug(">>> locale inited to: " + this.appLocale.getLanguage());
  }
  
  public Locale getAppLocale() {
    return appLocale;
  }

  public void setAppLocale(Locale appLocale) {
    this.appLocale = appLocale;
  }
  
  // as an action listener
  public void change2English(ActionEvent e) {
    this.appLocale = Locale.ENGLISH;
    FacesContext.getCurrentInstance().getViewRoot().setLocale(this.appLocale);
    log.debug(">>> locale changed to English: " + this.appLocale.getLanguage());
  }
  
  // as an action method
  public String change2Chinese() {
    this.appLocale = Locale.CHINESE;
    FacesContext.getCurrentInstance().getViewRoot().setLocale(this.appLocale);
    log.debug(">>> locale changed to Chinese: " + this.appLocale.getLanguage());
    return null;
  }
}

 

OK, looks like everything is setup. Now just need to change the "/template/template1.xhtml" to include the <f:view locale="..."/> and the language chooser context menu. Then in the JSF page sources, we need to change very hard coded labels to something like "#{msgs.label_key_name}".

 

Here's the updated template1.xhtml:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
   	xmlns:ui="http://java.sun.com/jsf/facelets"
   	xmlns:p="http://primefaces.org/ui">
   	
  <f:view locale="#{langBean.appLocale}">
	  <h:head>
	    <title>
	      <ui:insert name="title">Title</ui:insert>
	    </title> 
	  </h:head>
	  
	  <h:body>  
	     <ui:insert name="menu">
	     	<ui:include src="menubar.xhtml"/>
	     	<ui:include src="contextmenu.xhtml"/>
	     </ui:insert>
	     
	     <p:spacer height="20"/>
	     	
	     <ui:insert name="content"/>
	  </h:body> 
  </f:view>
</html>
 

The updated JSF page "/tst/testSingleton.xhtml" (also updated main menu and studentSearch.xhtml):

 

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
   				xmlns:h="http://java.sun.com/jsf/html"
      			xmlns:f="http://java.sun.com/jsf/core"
      			xmlns:ui="http://java.sun.com/jsf/facelets"
      			xmlns:p="http://primefaces.org/ui"
   				template="/template/template1.xhtml">

<ui:define name="title">Test EJB3.1 @Singleton</ui:define>

<ui:define name="content">
	<h:form>
    <p:panel header="#{msgs.testSingletonHeader}" toggleable="true" style="width:60%">
    	<h:panelGrid columns="1">
        	Click "Test" to see if it's the same instance:
        	<h:outputText id="out" value="#{st.message}" escape="false"/>
        </h:panelGrid>
        <p:separator/>
        <p:commandButton value="#{msgs['test']}" action="#{st.test}" update="out"/>
        <p:spacer width="7"/>
        <p:commandButton value="#{msgs.clear}" actionListener="#{st.reset}" update="out"/>
    </p:panel>
    </h:form>
</ui:define>
</ui:composition>

 

 

Here's the "com.jxee.messages_zh.properties" (with Eclipse 3.7 "Indigo", it translated to unicode while i inputing Chinese, that cool! Othewise, you might want use JDK tool "native2ascii" to translate the Chinese characters to unicode):

 

### main menu labels
student=\u5B66\u751F
studentSearch=\u5B66\u751F\u67E5\u8BE2
studentNew=\u8F93\u5165\u65B0\u751F
blah=blah and blah

ajaxTest=Ajax \u8BD5\u9A8C
getParamTest=Get Param \u8BD5\u9A8C
ejbTest=EJB \u8BD5\u9A8C
asyncEjbTest=Asnyc EJB \u8BD5\u9A8C
singletonEjbTest=Singleton EJB \u8BD5\u9A8C

username=\u7528\u6237\u540D
password=\u53E3\u4EE4
login=\u829D\u9EBB\u5F00\u95E8
logout=\u79BB\u5F00

search=\u67E5\u8BE2

### context menu labels: for Chinese locale, shows English labels
english=English
chinese=Chinese

### test Singleton ejb labels
test=\u8BD5\u9A8C
clear=\u518D\u6765\u4E00\u904D\u5E7F\u64AD\u4F53\u64CD (-;
testSingletonHeader=\u8BD5\u9A8C EJB3.1 @Singleton

### student search screen
name=\u59D3\u540D
mobile=\u624B\u673A
createdDate=\u8F93\u5165\u65E5\u671F
studentFound=\u67E5\u8BE2\u5230\u7684\u5B66\u751F
addNewStudent=\u6DFB\u52A0\u5B66\u751F
 

 

Now take a look at what we've got:

 

ss1: The language chooser context menu, before switching to Chinese:


 

ss2: The language chooser context menu, after switched to Chinese:


 

ss3: The i18Ned screen "/student/studentSearch.jsf":


 

not too bad!

  • 大小: 33.6 KB
  • 大小: 24.7 KB
  • 大小: 28.5 KB
  • 大小: 25.1 KB
分享到:
评论

相关推荐

    jee6 学习笔记 6.3 - @Asynchronous

    在Java企业版(Java EE)6中,`@Asynchronous`注解是一个非常重要的特性,它使得开发者可以方便地在应用程序中实现异步处理。这个注解是Java EE并发编程的一部分,主要应用于EJB(Enterprise JavaBeans)环境,用于...

    jee6 学习笔记 1 - 开发环境的配置

    NULL 博文链接:https://jxee.iteye.com/blog/1575432

    jee6 学习笔记 5 - Struggling with JSF2 binding GET params

    这篇"jee6 学习笔记 5 - Struggling with JSF2 binding GET params"主要探讨了开发者在使用JSF2绑定GET参数时可能遇到的挑战和解决方案。 JSF2是一个基于MVC(模型-视图-控制器)设计模式的Java框架,用于创建交互...

    JEE企业应用笔记

    ### JEE企业应用笔记 #### 一、JSP与Servlet **JSP (Java Server Pages)** 和 **Servlet** 是Java Web开发中的两个核心组件。它们共同构建了动态Web应用程序的基础。 ##### JSP基本语法 在JSP页面中,可以通过...

    Restlet所需要的所有jar包

    Restlet是一款开源的Java框架,专门用于构建RESTful(Representational State Transfer)Web服务。REST是一种轻量级的架构风格,常用于构建高效、可扩展的网络应用程序。本压缩包包含Restlet框架运行所需的全部jar...

    JEE6编程模型

    JEE6(Java Platform, Enterprise Edition 6)是Java EE的第六个版本,它在Java EE 5的基础上对Java的企业级应用开发进行了进一步的优化和增强。JEE6不仅包括了Java EE 5的大多数特性,还引入了更多的新功能和技术,...

    jee 入门(深入浅出学习JEE)

    【JEE入门(深入浅出学习JEE)】 Java企业版(Java Enterprise Edition,简称JEE),也称为Java EE,是Oracle公司推出的企业级应用程序开发平台。它为开发分布式、多层架构的Web应用程序提供了全面的框架和服务。JEE...

    Atlas2.3.0依赖: org.restlet/sqoop-1.4.6.2.3.99.0-195

    Restlet是一个轻量级的Java RESTful(Representational State Transfer)Web服务框架。REST是一种软件架构风格,用于构建可伸缩的、分布式的网络应用程序。Restlet库提供了开发RESTful API所需的一系列组件和工具,...

    ssm+mysql+maven+jeeweb-mybatis

    6. **Jeeweb-Mybatis**:Jeeweb是一个基于Spring Boot、Spring Cloud和SSM的快速开发平台,它包含了很多企业级功能,如权限管理、工作流、报表、图表等。Jeeweb-Mybatis可能是该项目中的核心模块,专注于MyBatis的...

    jee_paper_checker:h

    【jee_paper_checker:h】项目是一个使用Python编写的工具,主要功能是处理和检查教育考试中的试题和答案。这个工具的目的是帮助教师或教育工作者更有效地管理考试材料,特别是那些包含大量选择题的标准化测试,如...

    JeeWeb敏捷开发平台

    JeeWeb是一款基于SpringMVC+Spring+Hibernate的敏捷开发系统;它是一款具有代码生成功能的智能快速开发平台;是以Spring Framework为核心容器,Spring MVC为模型视图控制器,Hibernate为数据访问层, Apache Shiro为...

    jee6 学习系列告一段落,uploaded zipped project after JAAS security

    标题中的“JEE6 学习系列告一段落,uploaded zipped project after JAAS security”表明这是一个关于Java Enterprise Edition(JEE)6的项目,特别关注了Java Authentication and Authorization Service (JAAS)的...

    org.restlet-2.3.0.jar

    Restlet项目为“建立REST概念与Java类之间的映射”提供了一个轻量级而全面的框架。它可用于实现任何种类的REST式系统,而不仅仅是REST式Web服务

    jee6-petclinic2:Spring Pet Clinic 到 JEE 的另一个迁移示例

    jee6-petclinic2 要使用 mysql jndi 资源: 要将 mysql 数据源安装到 Wildfly 8.1 上,请运行“mvn verify -Pds” 在 conf/persistence.xml jta-data-source 和 comment 属性中取消注释。

    JEE_hibernate_test:wakul的属性

    10. **集成测试(Integration Testing)**:为了验证整个系统,包括数据库交互,可能还需要进行集成测试,例如使用Arquillian等工具在真实的JEE环境中运行测试。 综上所述,"JEE_hibernate_test:wakul的属性"涵盖了...

    jee webserver cluser web 集群

    【标题】:“jee webserver cluser web 集群” 【描述】:“描述了一个网页的集群组织与介绍,对呀我们java web 编程人员是有一定好处的” 在这个主题中,我们将深入探讨Java Enterprise Edition (Java EE) 中的...

    JEE-Mains-AnswerKeys:一个自动填充的存储库,其中包含JSON格式的JEE Mains考试的答案键

    JEE-Mains-AnswerKeys:一个自动填充的存储库,其中包含JSON格式的JEE Mains考试的答案键

    JEE-cdi-playgound:JEE CDI 游乐场

    在“JEE-cdi-playgound-master”这个项目中,开发者可以通过实际操作,学习如何创建和配置CDI Bean,使用不同的作用域,监听和发布事件,以及如何定义和应用拦截器。项目可能包含了示例代码、教程文档和测试用例,...

    bee-jee-test-task:MVC简单应用

    6. **Vendor**(如果使用Composer管理依赖):存储第三方库和框架核心组件。 完成这个“bee-jee-test-task”将使开发者掌握PHP MVC框架的基本工作流程,包括如何组织代码、如何处理请求和响应、以及如何使用模型...

    开源bbs源码java-jeeweb2:jeeweb2

    JeeWeb敏捷开发平台 QQ交流群: 570062301(满)、522959928 官方网站: 文档地址: 项目演示: 前后端分离版本项目演示: 分离开发前端项目地址: 简介 JeeWeb是一款基于SpringBoot 2+Spring+Mybatis+Hibernate的...

Global site tag (gtag.js) - Google Analytics