国际化(简称I18N)指的是在软件设计阶段,就应该使该软件具有支持多种语言和地区的功能。这样,当需要在应用中添加对一种新的语言和国家的支持时,不需要对已经有的软件返工,无需修改应用的程序代码。
1. 在Struts 应用中访问Local对象
java.util.Local类是最重要的JavaI18N类,在java语言中,几乎所有对国际化和本地化的支持都依赖于这个类。
多数WEB浏览器允许你配置Local。如,对于微软的IE浏览器,可以选择【工具】|【Internet选项】命令,单击【语言】按钮,进而就可以设置选择语言了。
我们不需要做什么,在处理每一个用户请求时,ReuestProcessor类都会调用它的processLocale()方法,processLocale()方法把Local对象存储在session范围中。
2. 一个简单的例子,根据用户Locale的不同,显示不同的问候语。
(1)创建视图部分内容,这里只有一个JSP页面。
hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html:html locale="true">
<head>
<title><bean:message key="hello.jsp.title"/></title>
<html:base/>
</head>
<body bgcolor="white"><p>
<h2><bean:message key="hello.jsp.page.heading"/></h2><p>
<html:errors/><p>
<!--如果在request范围内存在personbean,则执行其中的语句--> <logic:present name="personbean" scope="request">
<h2>
<bean:message key="hello.jsp.page.hello"/>
<bean:write name="personbean" property="userName" />!<p>
</h2>
</logic:present>
<html:form action="/HelloWorld.do" focus="userName" >
<bean:message key="hello.jsp.prompt.person"/>
<html:text property="userName" size="16" maxlength="16"/><br>
<html:submit property="submit" >
<bean:message key="hello.jsp.page.submit"/>
</html:submit>
<html:reset property="reset" >
<bean:message key="hello.jsp.page.reset"/>
</html:reset>
</html:form><br>
<html:img pageKey="hello.jsp.page.stutsimage" altKey="hello.jsp.page.struts"/>
</body>
</html:html>
(2)创建FORMBEAN文件,
HelloForm.java
package hello;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
public final class HelloForm extends ActionForm {
private String userName = null;
public String getUserName() {
return (this.userName);
}
public void setUserName(String userName) {
this.userName = userName;
}
/**
* 重新设置userName为null
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.userName = null;
}
/**
* 验证userName,不能为空
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if ((userName == null) || (userName.length() < 1))
errors.add("username", new ActionMessage("hello.no.username.error"));
return errors;
}
}
(3)创建ACTION文件,
HelloAction.java
package hello;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
public final class HelloAction extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
MessageResources messages = getResources(request);
ActionMessages errors = new ActionMessages();
String userName = (String)((HelloForm) form).getUserName();
String badUserName = "Monster";
if (userName.equalsIgnoreCase(badUserName)) {
errors.add("username", new ActionMessage("hello.dont.talk.to.monster", badUserName ));
saveErrors(request, errors);
return (new ActionForward(mapping.getInput()));
}
/*
* Having received and validated the data submitted
* from the View, we now update the model
*/
PersonBean pb = new PersonBean();
pb.setUserName(userName);
pb.saveToPersistentStore();
request.setAttribute(“personbean”, pb);
// Remove the Form Bean - don't need to carry values forward
request.removeAttribute(mapping.getAttribute());
// Forward control to the specified success URI
return (mapping.findForward("SayHello"));
}
}
(4)创建获取用户输入的userName的BEAN文件
PersonBean.java
package hello;
public class PersonBean {
private String userName = null;
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
(5)创建英文资源文件:application_en.properties
#Application Resources for the "Hello" sample application
#Application Resources that are specific to the hello.jsp file
hello.jsp.title=Hello - A first Struts program
hello.jsp.page.heading=Hello World! A first Struts application
hello.jsp.prompt.person=Please enter a UserName to say hello to :
hello.jsp.page.hello=Hello
hello.jsp.page.submit=Submit
hello.jsp.page.reset=Reset
hello.jsp.page.stutsimage=/struts-power.gif
hello.jsp.page.stuts=Powered By Struts
#Validation and error messages for HelloForm.java and HelloAction.java
hello.dont.talk.to.monster=We don't want to say hello to Monster!!!
hello.no.username.error=Please enter a <i>UserName</i> to say hello to!
(6)创建中文资源文件:application_temp.properties
#Application Resources for the "Hello" sample application
#Application Resources that are specific to the hello.jsp file
hello.jsp.title=Hello - 第一个Struts应用
hello.jsp.page.heading=Hello World! 第一个Struts应用
hello.jsp.prompt.person=请输入你想打招呼的用户名:
hello.jsp.page.hello=你好
hello.jsp.page.submit=提交
hello.jsp.page.reset=复位
hello.jsp.page.stutsimage=/struts-power-ch.gif
hello.jsp.page.stuts=基于Struts技术
#Validation and error messages for HelloForm.java and HelloAction.java
hello.dont.talk.to.monster=我们不想对Monster打招呼!!!
hello.no.username.error=请输入你想打招呼的<i>用户名</i>!
接着对临时资源文件进行编码转换,使用encode.bat即可搞定。生成的文件名为:application_zh_CN.properties。
#Application Resources for the "Hello" sample application
#Application Resources that are specific to the hello.jsp file
hello.jsp.title=Hello - /u7b 2c/u4e00/u4e2aStruts/u5e94/u7528
hello.jsp.page.heading=Hello World! /u7b 2c/u4e00/u4e2aStruts/u5e94/u7528
hello.jsp.prompt.person=/u8bf7/u 8f93/u5165/u 4f60/u 60f3/u6253/u62db/u 547c/u7684/u7528/u6237/u540d:
hello.jsp.page.hello=/u 4f60/u597d
hello.jsp.page.submit=/u63d0/u4ea4
hello.jsp.page.reset=/u590d/u 4f4d
hello.jsp.page.stutsimage=/struts-power-ch.gif
hello.jsp.page.stuts=/u57fa/u4e8eStruts/u6280/u 672f
#Validation and error messages for HelloForm.java and HelloAction.java
hello.dont.talk.to.monster=/u6211/u4eec/u4e0d/u 60f3/u5bf9Monster/u6253/u62db/u 547c!!!
hello.no.username.error=/u8bf7/u 8f93/u5165/u 4f60/u 60f3/u6253/u62db/u 547c/u7684<i>/u7528/u6237/u540d</i>!
3. 采用Servlet过滤器设置请求数据的字符编码
SetCharacterEncodingFilter.java
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.UnavailableException;
public class SetCharacterEncodingFilter implements Filter {
/**
* Take this filter out of service.
*/
public void destroy() {
}
/**
* Select and set (if specified) the character encoding to be used to
* interpret request parameters for this request.
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
// 传递控制到下一个过滤器
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
4. 设置struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<form-beans>
<form-bean name="HelloForm" type="hello.HelloForm"/>
</form-beans>
<action-mappings>
<!-- Say Hello! -->
<action path = "/HelloWorld"
type = "hello.HelloAction"
name = "HelloForm"
scope = "request"
validate = "true"
input = "/hello.jsp">
<forward name="SayHello" path="/hello.jsp" />
</action>
</action-mappings>
<message-resources parameter="hello.application_en"/>
</struts-config>
5. 设置web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<display-name>HelloApp Struts Application</display-name>
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>SetCharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Standard Action Servlet Configuration -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- The Usual Welcome File List -->
<welcome-file-list>
<welcome-file>hello.jsp</welcome-file>
</welcome-file-list>
<!-- Struts Tag Library Descriptors -->
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
</web-app>