做国际化分为三步:
1,加入资源文件
2,在strust-config.xml中指定资源文件
3,在页面中用<bean:message key=".."/>显示
在formbean里面validate方法里面验证没有通过的时候,返回错误信息到页面:
配置文件中:
title.username=user name
title.password=password
button.submit=submit
button.reset=reset
errors.required=you must fill {0}
prompt.username=user name
prompt.password=password
errors.minLength=the length of {0}havetogreater than{1}
errors.maxLength=the length of {0}mustlessthan {1}
在页面中使用struts的标签要先导入标签库:、
<html:form action="/login" method="post">
<bean:message key="title.username"/>:<html:textproperty="username"/><html:errorsproperty="errorsUsername"/><br/>
<bean:message key="title.password"/>:<html:passwordproperty="password"/><html:errorsproperty="errorsPassword"/><br/>
<html:submit><bean:messagekey="button.submit"/></html:submit>
<html:reset><bean:messagekey="button.reset"/></html:reset>
</html:form>
formbean中的validate方法:
public ActionErrors validate(ActionMapping mapping,
HttpServletRequestrequest) {
ActionErrors errors =newActionErrors();
//因为这个方法是在action类里面的,所以这里要从源码里面得到MessageResource
//得到资源文件--去action类--getResource方法找,在Action中可以这样得到资源文件中的值
//在Action中的话,就可以直接是 gettResources(request);获得MessageResources对象
MessageResources resources = (MessageResources) request.getAttribute(Globals.MESSAGES_KEY);
//得到客户端的语言
Locale locale =RequestUtils.getUserLocale(request,null);
if(username==null ||username.trim().length()== 0){
//如果资源文件里面不要填充值,就直接可以用ActionMessage("key",true);实现国际化
//这里可以看做生成一个message,这个message需要填充配置文件中几个变量值,而且要决定是用哪种语言,所以要得到locale
ActionMessagemessage = newActionMessage("errors.required",
resources.getMessage(locale,"prompt.username"));
errors.add("errorsUsername",message);
}
if(password==null ||password.length()<3){
ActionMessagemessage = newActionMessage("errors.minLength",
resources.getMessage(locale,"prompt.password"),3);
errors.add("errorsPassword",message);
}
else if(password.length()>6){
ActionMessage message = new ActionMessage("errors.maxLength",
resources.getMessage(locale,"prompt.password"),6);
errors.add("errorsPassword",message);
}
return errors;
}
struts-config.xml中:
<struts-config>
<form-beans>
<form-bean name="loginForm" type="hwt.formBean.LoginForm"/>
</form-beans>
<action-mappings>
<action path="/login" type="hwt.action.LoginAction"parameter="method"name="loginForm"input="/WEB-INF/page/Login.jsp">
<forward name="success" path="/WEB-INF/page/Success.jsp"/>
</action>
<action path="/goLogin" forward="/WEB-INF/page/Login.jsp"/>
</action-mappings>
<!--这里不要写key-->
<message-resourcesparameter="hwt.resources.ApplicationResources"/>
</struts-config>
Stringlanguage = request.getParameter("language");
Localekey = new Locale(language);
request.getSession().setAttribute(Globals.LOCALE_KEY,key);