解决Spring国际化文案占位符失效问题的方法

时间:2022-06-01 02:38:10

写在前面:接下来很长一段时间的文章主要会记录一些项目中实际遇到的问题及对应的解决方案,在相应代码分析时会直指问题所在,不会将无关的流程代码贴出,感兴趣的读者可以自行跟踪。同时希望大家能够将心得体会在评论区分享出来,让大家共同进步!

环境或版本:spring 3.2.3

现象:利用spring自带的messagesource来处理国际化文案,us状态下的文案有部分占位符未被替换,cn状态下的正常。文案如下:

tms.pallet.order.box.qty=the total palletized boxes quantity {0} doesn't match with the received boxes quantity {1},please double check!
tms.pallet.order.box.qty=打板总箱数件{0},与订单收货总箱数{1}不一致。请检查!

直觉:是不是英文文案太长了,spring处理时对长度做了限制,仔细想了想spring应该不会设计的这么坑。

排查:断点跟踪spring源码(入口:messagesource的getmessage方法),最后发现了messageformat中这样的一段处理方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// indices for segments
  private static final int seg_raw   = 0;
  private static final int seg_index  = 1;
  private static final int seg_type   = 2;
  private static final int seg_modifier = 3; // modifier or subformat
 
/**
   * sets the pattern used by this message format.
   * the method parses the pattern and creates a list of subformats
   * for the format elements contained in it.
   * patterns and their interpretation are specified in the
   * <a href="#patterns" rel="external nofollow" >class description</a>.
   *
   * @param pattern the pattern for this message format
   * @exception illegalargumentexception if the pattern is invalid
   */
  @suppresswarnings("fallthrough") // fallthrough in switch is expected, suppress it
  public void applypattern(string pattern) {
      stringbuilder[] segments = new stringbuilder[4];
      // allocate only segments[seg_raw] here. the rest are
      // allocated on demand.
      segments[seg_raw] = new stringbuilder();
 
      int part = seg_raw;
      int formatnumber = 0;
      boolean inquote = false;
      int bracestack = 0;
      maxoffset = -1;
      for (int i = 0; i < pattern.length(); ++i) {
        char ch = pattern.charat(i);
        if (part == seg_raw) {
          if (ch == '\'') {
            if (i + 1 < pattern.length()
              && pattern.charat(i+1) == '\'') {
              segments[part].append(ch); // handle doubles
              ++i;
            } else {
              inquote = !inquote;
            }
          } else if (ch == '{' && !inquote) {
            part = seg_index;
            if (segments[seg_index] == null) {
              segments[seg_index] = new stringbuilder();
            }
          } else {
            segments[part].append(ch);
          }
        } else {
          if (inquote) {       // just copy quotes in parts
            segments[part].append(ch);
            if (ch == '\'') {
              inquote = false;
            }
          } else {
            switch (ch) {
            case ',':
              if (part < seg_modifier) {
                if (segments[++part] == null) {
                  segments[part] = new stringbuilder();
                }
              } else {
                segments[part].append(ch);
              }
              break;
            case '{':
              ++bracestack;
              segments[part].append(ch);
              break;
            case '}':
              if (bracestack == 0) {
                part = seg_raw;
                makeformat(i, formatnumber, segments);
                formatnumber++;
                // throw away other segments
                segments[seg_index] = null;
                segments[seg_type] = null;
                segments[seg_modifier] = null;
              } else {
                --bracestack;
                segments[part].append(ch);
              }
              break;
            case ' ':
              // skip any leading space chars for seg_type.
              if (part != seg_type || segments[seg_type].length() > 0) {
                segments[part].append(ch);
              }
              break;
            case '\'':
              inquote = true;
              // fall through, so we keep quotes in other parts
            default:
              segments[part].append(ch);
              break;
            }
          }
        }
      }
      if (bracestack == 0 && part != 0) {
        maxoffset = -1;
        throw new illegalargumentexception("unmatched braces in the pattern.");
      }
      this.pattern = segments[0].tostring();
  }

上面的这段代码写的有点让人费解,略微奇特,我们主要看第一个逻辑分支:对每一个待处理的国际化文案模板串中的字符进行遍历,当字符为"'"时,判断后一个字符是否也为“'”,如果是则将“‘”拼接到已处理的stringbuilder中,不是则将inquote至为true,如果该字符不会‘{'且inquote为false则将part重新置为0,并且segments[seg_index]=null的话重新创建stringbuilder对象,否则继续拼接。

原因分析:

  1. 结合我们配置的英文文案(其中一共有两个占位符,在这这两占位符之前有一个单引号),根据上面spring的处理源码看,实际处理会是:对该字符串进行逐个字符处理,逐个拼接到已处理的stringbuilder中,当处理到‘{'时,此处part将被置为1,同时segments第1个存储位上会引用stringbuilder类型的对象,程序继续处理下面的待处理的字符,继续拼接(请自行看part!= seg_raw的逻辑分支),直到处理到‘}'时,part被重新赋值为0,sefgments的其他位被清空,于是继续处理下面的字符串继续拼接,处理到单引号时,inquote被置为true,接下来就一路拼接了,不再对后面的“{“做占位符处理。
  2. 中文文案中两个占位符之间并没有出现单引号,因此解决了问题现象中的第二点,中文文案显示正常。

解决方案:

从源码看只有一种解决方式,{}之间的单引号需要成对出现,我们的处理方式是将文案修改为了:

tms.pallet.order.box.qty=the total palletized boxes quantity {0} doesn''t match with the received boxes quantity {1},please double check!

直接修改文案其实并不是一种很好的解决方法,最好是能够重写spring调用applypattern方法前的某一方法来将单引号替换为双引号。无奈spring 3.2.3版本中对应国际化的处理方法一路private,不给你重写的机会。

查阅相关资料得知,在spring4.3.2版本中可以通过重写resourcebundlemessagesource类中的getstringornull方法来实现。

长远方案:升级项目中的spring版本,同时使用更多的新版特性。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://my.oschina.net/u/3345762/blog/1790216