当前位置: 移动技术网 > IT编程>开发语言>Java > 自己动手在Spring-Boot上加强国际化功能的示例

自己动手在Spring-Boot上加强国际化功能的示例

2019年07月19日  | 移动技术网IT编程  | 我要评论

elin 郭晓雯,小柳千春,唤醒小盒子

前言

公司将项目由struts2转到springmvc了,由于公司业务是境外服务,所以对国际化功能需求很高。struts2自带的国际化功能相对springmvc来说更加完善,不过spring很大的特性就是可定定制化性强,所以在公司项目移植的到springmvc的时候增加了其国际化的功能。特此整理记录并且完善了一下。

本文主要实现的功能:

从文件夹中直接加载多个国际化文件后台设置前端页面显示国际化信息的文件利用拦截器和注解自动设置前端页面显示国际化信息的文件

注:本文不详细介绍怎么配置国际化,区域解析器等。

实现

国际化项目初始化

先创建一个基本的spring-boot+thymeleaf+国际化信息(message.properties)项目,如果有需要可以从我的github下载。

简单看一下项目的目录和文件

其中i18napplication.java设置了一个cookielocaleresolver,采用cookie来控制国际化的语言。还设置一个localechangeinterceptor拦截器来拦截国际化语言的变化。

@springbootapplication
@configuration
public class i18napplication {
  public static void main(string[] args) {
    springapplication.run(i18napplication.class, args);
  }

  @bean
  public localeresolver localeresolver() {
    cookielocaleresolver slr = new cookielocaleresolver();
    slr.setcookiemaxage(3600);
    slr.setcookiename("language");//设置存储的cookie的name为language
    return slr;
  }

  @bean
  public webmvcconfigurer webmvcconfigurer() {
    return new webmvcconfigurer() {
      //拦截器
      @override
      public void addinterceptors(interceptorregistry registry) {
        registry.addinterceptor(new localechangeinterceptor()).addpathpatterns("/**");
      }
    };
  }
}

我们再看一下hello.html中写了什么:

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
  <title>hello world!</title>
</head>
<body>
<h1 th:text="#{i18n_page}"></h1>
<h3 th:text="#{hello}"></h3>
</body>
</html>

现在启动项目并且访问http://localhost:9090/hello(我在application.properties)中设置了端口为9090。

由于浏览器默认的语言是中文,所以他默认会去messages_zh_cn.properties中找,如果没有就会去messages.properties中找国际化词。

然后我们在浏览器中输入http://localhost:9090/hello?locale=en_us,语言就会切到英文。同样的如果url后参数设置为locale=zh_ch,语言就会切到中文。

从文件夹中直接加载多个国际化文件

在我们hello.html页面中,只有'i18n_page'和'hello'两个国际化信息,然而在实际项目中肯定不会只有几个国际化信息那么少,通常都是成千上百个的,那我们肯定不能把这么多的国际化信息都放在messages.properties一个文件中,通常都是把国际化信息分类存放在几个文件中。但是当项目大了以后,这些国际化文件也会越来越多,这时候在application.properties文件中一个个的去配置这个文件也是不方便的,所以现在我们实现一个功能自动加载制定目录下所有的国际化文件。

继承resourcebundlemessagesource

在项目下创建一个类继承resourcebundlemessagesource或者reloadableresourcebundlemessagesource,起名为messageresourceextension。并且注入到bean中起名为messagesource,这里我们继承resourcebundlemessagesource。

@component("messagesource")
public class messageresourceextension extends resourcebundlemessagesource {
}

注意这里我们的component名字必须为'messagesource',因为在初始化applicationcontext的时候,会查找bean名为'messagesource'的bean。这个过程在abstractapplicationcontext.java中,我们看一下源代码

/**
* initialize the messagesource.
* use parent's if none defined in this context.
*/
protected void initmessagesource() {
  configurablelistablebeanfactory beanfactory = getbeanfactory();
  if (beanfactory.containslocalbean(message_source_bean_name)) {
    this.messagesource = beanfactory.getbean(message_source_bean_name, messagesource.class);
  ...
  }
}
...

在这个初始化messagesource的方法中,beanfactory查找注入名为message_source_bean_name(messagesource)的bean,如果没有找到,就会在其父类中查找是否有该名的bean。

实现文件加载

现在我们可以开始在刚才创建的messageresourceextension

中写加载文件的方法了。

@component("messagesource")
public class messageresourceextension extends resourcebundlemessagesource {

  private final static logger logger = loggerfactory.getlogger(messageresourceextension.class);

  /**
   * 指定的国际化文件目录
   */
  @value(value = "${spring.messages.basefolder:i18n}")
  private string basefolder;

  /**
   * 父messagesource指定的国际化文件
   */
  @value(value = "${spring.messages.basename:message}")
  private string basename;

  @postconstruct
  public void init() {
    logger.info("init messageresourceextension...");
    if (!stringutils.isempty(basefolder)) {
      try {
        this.setbasenames(getallbasenames(basefolder));
      } catch (ioexception e) {
        logger.error(e.getmessage());
      }
    }
    //设置父messagesource
    
    resourcebundlemessagesource parent = new resourcebundlemessagesource();
    parent.setbasename(basename);
    this.setparentmessagesource(parent);
  }

  /**
   * 获取文件夹下所有的国际化文件名
   *
   * @param foldername 文件名
   * @return
   * @throws ioexception
   */
  private string[] getallbasenames(string foldername) throws ioexception {
    resource resource = new classpathresource(foldername);
    file file = resource.getfile();
    list<string> basenames = new arraylist<>();
    if (file.exists() && file.isdirectory()) {
      this.getallfile(basenames, file, "");
    } else {
      logger.error("指定的basefile不存在或者不是文件夹");
    }
    return basenames.toarray(new string[basenames.size()]);
  }

  /**
   * 遍历所有文件
   *
   * @param basenames
   * @param folder
   * @param path
   */
  private void getallfile(list<string> basenames, file folder, string path) {
    if (folder.isdirectory()) {
      for (file file : folder.listfiles()) {
        this.getallfile(basenames, file, path + folder.getname() + file.separator);
      }
    } else {
      string i18name = this.geti18filename(path + folder.getname());
      if (!basenames.contains(i18name)) {
        basenames.add(i18name);
      }

    }
  }

  /**
   * 把普通文件名转换成国际化文件名
   *
   * @param filename
   * @return
   */
  private string geti18filename(string filename) {
    filename = filename.replace(".properties", "");
    for (int i = 0; i < 2; i++) {
      int index = filename.lastindexof("_");
      if (index != -1) {
        filename = filename.substring(0, index);
      }
    }
    return filename;
  }
}

依次解释一下几个方法。

  1. init()方法上有一个@postconstruct注解,这会在messageresourceextension类被实例化之后自动调用init()方法。这个方法获取到basefolder目录下所有的国际化文件并设置到basenameset中。并且设置一个parentmessagesource,这会在找不到国际化信息的时候,调用父messagesource来查找国际化信息。
  2. getallbasenames()方法获取到basefolder的路径,然后调用getallfile()方法获取到该目录下所有的国际化文件的文件名。
  3. getallfile()遍历目录,如果是文件夹就继续遍历,如果是文件就调用geti18filename()把文件名转为'i18n/basename/‘格式的国际化资源名。

所以简单来说就是在messageresourceextension被实例化之后,把'i18n'文件夹下的资源文件的名字,加载到basenames中。现在来看一下效果。

首先我们在application.properties文件中添加一个spring.messages.basefolder=i18n,这会把'i18n'这个值赋值给messageresourceextension中的basefolder

在启动后看到控制台里打印出了init信息,表示被@postconstruct注解的init()方法已经执行。

然后我们再创建两组国际化信息文件:'dashboard'和'merchant',里面分别只有一个国际化信息:'dashboard.hello'和'merchant.hello'。

之后再修改一下hello.html文件,然后访问hello页面。

...
<body>
<h1>国际化页面!</h1>
<p th:text="#{hello}"></p>
<p th:text="#{merchant.hello}"></p>
<p th:text="#{dashboard.hello}"></p>
</body>
...

可以看到网页中加载了'message','dashboard'和'merchant'中的国际化信息,说明我们已经成功一次性加载了'i18n'文件夹下的文件。

后台设置前端页面显示国际化信息的文件

s刚才那一节我们成功加载了多个国际化文件并显示出了他们的国际化信息。但是'dashboard.properties'中的国际化信息为'dashboard.hello'而'merchant.properties'中的是'merchant.hello',这样每个都要写一个前缀岂不是很麻烦,现在我想要在'dashboard'和'merchant'的国际化文件中都只写'hello'但是显示的是'dashboard'或'merchant'中的国际化信息。

messageresourceextension重写resolvecodewithoutarguments方法(如果有字符格式化的需求就重写resolvecode方法)。

@component("messagesource")
public class messageresourceextension extends resourcebundlemessagesource {
  ...
  public static string i18n_attribute = "i18n_attribute";
  
  @override
  protected string resolvecodewithoutarguments(string code, locale locale) {
    // 获取request中设置的指定国际化文件名
    servletrequestattributes attr = (servletrequestattributes) requestcontextholder.currentrequestattributes();
    final string i18file = (string) attr.getattribute(i18n_attribute, requestattributes.scope_request);
    if (!stringutils.isempty(i18file)) {
      //获取在basenameset中匹配的国际化文件名
      string basename = getbasenameset().stream()
          .filter(name -> stringutils.endswithignorecase(name, i18file))
          .findfirst().orelse(null);
      if (!stringutils.isempty(basename)) {
        //得到指定的国际化文件资源
        resourcebundle bundle = getresourcebundle(basename, locale);
        if (bundle != null) {
          return getstringornull(bundle, code);
        }
      }
    }
    //如果指定i18文件夹中没有该国际化字段,返回null会在parentmessagesource中查找
    return null;
  }
  ...
}

在我们重写的resolvecodewithoutarguments方法中,从httpservletrequest中获取到‘i18n_attribute'(等下再说这个在哪里设置),这个对应我们想要显示的国际化文件名,然后我们在basenameset中查找该文件,再通过getresourcebundle获取到资源,最后再getstringornull获取到对应的国际化信息。

现在我们到我们的hellocontroller里加两个方法。

@controller
public class hellocontroller {

  @getmapping("/hello")
  public string index(httpservletrequest request) {
    request.setattribute(messageresourceextension.i18n_attribute, "hello");
    return "system/hello";
  }

  @getmapping("/dashboard")
  public string dashboard(httpservletrequest request) {
    request.setattribute(messageresourceextension.i18n_attribute, "dashboard");
    return "dashboard";
  }

  @getmapping("/merchant")
  public string merchant(httpservletrequest request) {
    request.setattribute(messageresourceextension.i18n_attribute, "merchant");
    return "merchant";
  }
}

看到我们在每个方法中都设置一个对应的'i18n_attribute',这会在每次请求中设置对应的国际化文件,然后在messageresourceextension中获取。

这时我们看一下我们的国际化文件,我们可以看到所有关键字都是'hello',但是信息却不同。

同时新增两个html文件分别是'dashboard.html'和'merchant.html',里面只有一个'hello'的国际化信息和用于区分的标题。

<!-- 这是hello.html -->
<body>
<h1>国际化页面!</h1>
<p th:text="#{hello}"></p>
</body>
<!-- 这是dashboard.html -->
<body>
<h1>国际化页面(dashboard)!</h1>
<p th:text="#{hello}"></p>
</body>
<!-- 这是merchant.html -->
<body>
<h1>国际化页面(merchant)!</h1>
<p th:text="#{hello}"></p>
</body>

这时我们启动项目看一下。

可以看到虽然在每个页面的国际化词都是'hello',但是我们在对应的页面显示了我们想要显示的信息。

利用拦截器和注解自动设置前端页面显示国际化信息的文件

虽然已经可以指定对应的国际化信息,但是这样要在每个controller里的httpservletrequest中设置国际化文件实在太麻烦了,所以现在我们实现自动判定来显示对应的文件。

首先我们创建一个注解,这个注解可以放在类上或者方法上。

@target({elementtype.type, elementtype.method})
@retention(retentionpolicy.runtime)
public @interface i18n {
  /**
   * 国际化文件名
   */
  string value();
}

然后我们把这个创建的i18n 注解放在刚才的controller方法中,为了显示他的效果,我们再创建一个shopcontrollerusercontroller,同时也创建对应的'shop'和'user'的国际化文件,内容也都是一个'hello'。

@controller
public class hellocontroller {
  @getmapping("/hello")
  public string index() {
    return "system/hello";
  }

  @i18n("dashboard")
  @getmapping("/dashboard")
  public string dashboard() {
    return "dashboard";
  }

  @i18n("merchant")
  @getmapping("/merchant")
  public string merchant() {
    return "merchant";
  }
}
@i18n("shop")
@controller
public class shopcontroller {
  @getmapping("shop")
  public string shop() {
    return "shop";
  }
}
@controller
public class usercontroller {
  @getmapping("user")
  public string user() {
    return "user";
  }
}

我们把i18n注解分别放在hellocontroller下的dashboardmerchant方法下,和shopcontroller类上。并且去除了原来dashboardmerchant方法下设置‘i18n_attribute'的语句。

准备工作都做好了,现在看看如何实现根据这些注解自动的指定国际化文件。

public class messageresourceinterceptor implements handlerinterceptor {
  @override
  public void posthandle(httpservletrequest req, httpservletresponse rep, object handler, modelandview modelandview) {

    // 在方法中设置i18路径
    if (null != req.getattribute(messageresourceextension.i18n_attribute)) {
      return;
    }

    handlermethod method = (handlermethod) handler;
    // 在method上注解了i18
    i18n i18nmethod = method.getmethodannotation(i18n.class);
    if (null != i18nmethod) {
      req.setattribute(messageresourceextension.i18n_attribute, i18nmethod.value());
      return;
    }

    // 在controller上注解了i18
    i18n i18ncontroller = method.getbeantype().getannotation(i18n.class);
    if (null != i18ncontroller) {
      req.setattribute(messageresourceextension.i18n_attribute, i18ncontroller.value());
      return;
    }

    // 根据controller名字设置i18
    string controller = method.getbeantype().getname();
    int index = controller.lastindexof(".");
    if (index != -1) {
      controller = controller.substring(index + 1, controller.length());
    }
    index = controller.touppercase().indexof("controller");
    if (index != -1) {
      controller = controller.substring(0, index);
    }
    req.setattribute(messageresourceextension.i18n_attribute, controller);
  }

  @override
  public boolean prehandle(httpservletrequest req, httpservletresponse rep, object handler) {
    // 在跳转到该方法先清除request中的国际化信息
    req.removeattribute(messageresourceextension.i18n_attribute);
    return true;
  }
}

简单讲解一下这个拦截器。

首先,如果request中已经有'i18n_attribute',说明在controller的方法中指定设置了,就不再判断。

然后判断一下进入拦截器的方法上有没有i18n的注解,如果有就设置'i18n_attribute'到request中并退出拦截器,如果没有就继续。

再判断进入拦截的类上有没有i18n的注解,如果有就设置'i18n_attribute'到request中并退出拦截器,如果没有就继续。

最后假如方法和类上都没有i18n的注解,那我们可以根据controller名自动设置指定的国际化文件,比如'usercontroller'那么就会去找'user'的国际化文件。

现在我们再运行一下看看效果,看到每个链接都显示的他们对应的国际化信息里的内容。

最后

刚才完成了我们整个国际化增强的基本功能,最后我把全部代码整理了一下,并且整合了bootstrap4来展示了一下功能的实现效果。

详细的代码可以看我github上spring-boot-i18n-pro的代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网