Spring MVC 国际化,通过登录页面选择语言,系统根据配置信息显示什么语言

在页面通过spring标签的那种效果其他帖子都已经有了,这个我主要说的是,将提示信息添加入资源配置文件中,根据用户登录的时候去选择的语言,来动态的去显示什么语言。

1、首先得有一个spring mvc 项目。

2、    在mvc.xml文件中加入如下配置

 <bean id="messageSource" class="com.hxd.isp.publics.utils.IspResourceBundleMessageSource">
         <!-- 国际化资源文件配置,指定properties文件存放位置 -->
         <!-- <property name="basename" value="classpath:message/**" /> -->
         <property name="basenames">
            <list>
                <value>classpath:message/**/*.properties</value>
            </list>
        </property>
         <!-- 如果在国际化资源文件中找不到对应代码的信息,就用这个代码作为名称  -->               
         <property name="useCodeAsDefaultMessage" value="true" />
     </bean>
     <!-- 动态切换国际化 ,国际化放在session中 -->
     <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
     <mvc:interceptors>
         <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 -->
         <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
             <!-- 通过这个参数来决定获取那个配置文件 -->
             <property name="paramName" value="language" />
         </bean>
     </mvc:interceptors>

其中的IspResourceBundleMessageSource 需要根据路径获取出来的资源配置文件重新给basenames set一下值,因为我们的value中的值 只需要配置文件的“_”下划线之前的文件名称,至于后面的国家简称、语言简称都不需要。

3、给basenames数组设置值,

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

public class IspResourceBundleMessageSource extends ReloadableResourceBundleMessageSource{
    
    private static String PROPERTY_POSTFIX = "_";
    
    private static String PROPERTY_POSTFIX_A = ".properties";
    
    private static final XLogger log = XLoggerFactory.getXLogger(IspResourceBundleMessageSource.class);
    
    private PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();

    public void setBasenames(String[] basenames) {
          if (basenames == null)
            {
              super.setBasenames(null);
            }

            List baseNameList = new ArrayList();

            for (String baseName : basenames)
            {
              try
              {
                Resource[] resources = this.patternResolver.getResources(baseName);

                for (Resource resource : resources)
                {
                  String fileName = resource.getURI().toString();
                  int size = fileName.indexOf(PROPERTY_POSTFIX);
                  if(size==-1){
                      size = fileName.indexOf(PROPERTY_POSTFIX_A);
                  }
                  baseNameList.add(fileName.substring(0, size));

                  if (!this.logger.isDebugEnabled())
                    continue;
                  this.logger.debug("Add properties file: [" + 
                    resource.getDescription() + "]");
                }

              }
              catch (IOException e)
              {
                log.throwing(e);
              }

              super.setBasenames((String[])baseNameList.toArray(
                new String[baseNameList
                .size()]));
            }
    }
    
    

}

在方法中写了两个 PROPERTY_POSTFIX的目的是:如果你只有某些模块需要进行语言之间的切换,就造成有的提示信息的配置文件名称格式不是有“_”下划线格式的,加两个的效果就是既可以读取需要语言切换的配置文件也可以读取不需要语言切换的配置文件。

4、登录页面添加选择语言框。

                        <tr>
                            <td class="listt">系统语言:</td>
                            <td colspan="2" align="left">
                                <div style="display:inline-block;">
                                  <input type="radio" id="language" value="zh_CN" name="language" checked="true"><span class="blackgray" >中文</span>
                                 </div>
                                <div style="display:inline-block;">
                                  <input type="radio" id="language" value="en_US" name="language"><span class="blackgray" >ENGLISH</span>
                                 </div>
                            </td>
                        </tr>

5、新建一个类继承UsernamePasswordAuthenticationFilter 重写setDetails方法

@Override
    protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
        Map<String, Object> detailMap = new HashMap<String, Object>(3);
        detailMap.put("language", request.getParameter("language"));
        detailMap.put("password", (String) authRequest.getCredentials());
        detailMap.put(SecurityConstant.REQUEST_DETAIL_KEY, authenticationDetailsSource.buildDetails(request));
        authRequest.setDetails(detailMap);
    }

6、新建一个类继承DaoAuthenticationProvider 重写additionalAuthenticationChecks(UserDetails userDetails,
            UsernamePasswordAuthenticationToken authentication)方法,下面为和获取语言相关的代码。

       UserDetail person = (UserDetail) userDetails;
        Map<String, Object> detailMap =(Map) authentication.getDetails();
        if(!StringUtils.isEmpty(detailMap)&&!StringUtils.isEmpty(detailMap.get("language"))){
            person.setLanguage(detailMap.get("language").toString());
        }

以上操作完成后,就可以通过 

Authentication authentication = null;

SecurityContext context = SecurityContextHolder.getContext();
        if (context != null) {
            authentication  =context.getAuthentication();
        }

if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof User) {
                //这里就可以获取到language这个参数
            }
        }

在用MessageSource的getMessage 之前, Locale locale = new Locale(language); 直接把这个locale传入getMessage方法中,就可以自动去获取不同人配置资源文件了!!!!!!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值