本文简单介绍下如何利用spring3.0 改变cookie来进行国际化,当然spring国际化有几种方式,本文只是简单使用cookie这种方式,配置的大致代码如下:
applicationcontext.xml
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>message</value>
</property>
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="cookieName" value="clientlanguage" />
<property name="cookieMaxAge" value="94608000" />
<property name="defaultLocale" value="zh" />
</bean>
messageSource 这个主要是加载国际化文件和配置文件的前缀,CookieLocaleResolver这个主要是用来配置cookie存活时间和默认显示。
下面是配置文件名称的格式
resource files
message_en.properties
message_zh.properties
控制改变cookie code:
package com.softterk.controller.front;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.propertyeditors.LocaleEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.support.RequestContextUtils;
import com.softterk.util.AjaxUtil;
@Controller
public class ChangeLanguageController {
private static Logger LOG =Logger.getLogger(ChangeLanguageController.class);
@RequestMapping(value="/changelanguage",method=RequestMethod.POST)
public void changelanguage(@RequestParam String new_lang,HttpServletResponse response,HttpServletRequest request)
{
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
if (localeResolver == null) {
LOG.error("No LocaleResolver found: not in a DispatcherServlet request?");
throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
}
LocaleEditor localeEditor = new LocaleEditor();
localeEditor.setAsText(new_lang);
localeResolver.setLocale(request, response, (Locale)localeEditor.getValue());
RequestContext requestContext = new RequestContext(request);
Locale locale = requestContext.getLocale();
request.setAttribute("locale", locale.toString());
if(LOG.isDebugEnabled())
LOG.debug("locale=="+locale.toString());
AjaxUtil.backData(response, "1");
}
}
jsp page:这里写的是一个js 方法,用来动态改变。
function changeLanguage(language)
{
$.ajax({
type: "POST",
url: "<%=path%>/changelanguage",
data: "new_lang="+language,
dataType:"text",
async: true,
error: function(data, error) {
alert("error!please try it again soon");
},
success: function(data)
{
window.location.reload();
}
});
}
获得配置文件的内容的话,就直接使用jstl的fmt和spring的标签都可以获得。