zoukankan      html  css  js  c++  java
  • Structs2 request_locale国际化介绍

    众所周知,struts2中使用了大量的拦截器(即是传说中的interceptor),其中国际化使用的拦截器为com.opensymphony.xwork2.interceptor.I18nInterceptor,那么接下来分析一下I18nInterceptor这个类。

    一.属性

      I18nInterceptor有三个属性,分别为parameterName,requestOnlyParameterName,attributeName。

      parameterName:http request请求中的参数名字,该参数反映了应该转向的locale,并且保存在session中,所以会话过程都有效。默认为request_locale。

      requestOnlyParameterName:http request请求中的参数名字,该参数反映了应该转向的locale,不保存在session中,所以只对当前请求有效。默认为request_only_locale。

      attributeName:session中保存用户选择的locale值对应的key值。默认值为WW_TRANS_I18N_LOCALE

    二.方法

      拦截器中最重要的方法当属intercept方法,其他方法暂时忽略。该方法的逻辑如下:

      1.获取parameters对象。Map<String, Object> params = invocation.getInvocationContext().getParameters()

      2.在params在取出并移除request_locale。  Object requested_locale = params.remove(parameterName);(parameters对象获取参数得到的是一个字符串数组)

          2.1 requested_locale不为null,是Array,长度为1,取出requested_locale的值。否则,2.2

          2.2 返回requested_locale

      3.在step2中获取到的request_locale如果为空,则将2中的parameterName换成requestOnlyParameterName,执行step2,返回requested_locale

      4.如果通过step2和step3获取到的requested_locale不为null,则将requested_locale转换成locale并保存在session中(注意:如果获取到的requested_locale.toString()为null或空字符串或者"_",此时locale=Locale.getDefault())。

      5.如果通过step2和step3获取到的requested_locale为null,则判断session中key=attributeName的value值是否存在,若存在则locale=session.get(attributeName),否则locale = invocation.getInvocationContext().getLocale()(此处意思是没有找到重写的locale定义,则保持当前的invocation locale,即用户在浏览器中设置的语言)。

      至此,通过I18nInterceptor得到了locale,此后的处理就不言而喻了,肯定就是根据locale取值了。

     可以看出:用户在画面设置的locale优先级高于浏览器设置语言得到的locale。

    可以看到此处超链接处设置request_locale=en_US,这样struts2获取到的locale当然就是en_US,此时不管浏览器语言设置成什么,画面显示的都是英文的资源,并且在会话期间都有效。若设置的是request_only_locale=en_US,这样只是在当前请求下会显示英文界面,刷新页面就会显示中文了。

  • 相关阅读:
    BZOJ 4016: [FJOI2014]最短路径树问题
    BZOJ 2599: [IOI2011]Race
    BZOJ 2152: 聪聪可可
    Codeforces Round #532 (Div. 2) Solution
    KEYENCE Programming Contest 2019 Solution
    AISing Programming Contest 2019 Solution
    Educational Codeforces Round 58 Solution
    2018-2019 ACM-ICPC, Asia East Continent Finals Solution
    Codeforces Round #530 (Div. 2) Solution
    Hello 2019 Solution
  • 原文地址:https://www.cnblogs.com/lechance/p/4373273.html
Copyright © 2011-2022 走看看