好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Springboot+AOP实现返回数据提示语国际化的示例代码

前言

本篇内容:
提示语的国际化返回,自定义多语言。
本文使用aop方式,拦截接口返回的数据,进行转换。

正文  

先看这次示例教学的项目 目录结构:

 (当然resource里面的i18n文件夹和三个properties文件也是要我们自己建的,但是 那个resource bundle 不用管,这个在yml加上对应配置项自动生成的。 不清楚的继续往下看教学就好)

开始敲(cv)代码:

pom.xml 依赖:

?

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

<dependencies>

         <dependency>

             <groupid>org.springframework.boot</groupid>

             <artifactid>spring-boot-starter-web</artifactid>

         </dependency>

         <dependency>

             <groupid>com.alibaba</groupid>

             <artifactid>fastjson</artifactid>

             <version> 1.2 . 68 </version>

         </dependency>

         <dependency>

             <groupid>org.apache.commons</groupid>

             <artifactid>commons-lang3</artifactid>

             <version> 3.9 </version>

         </dependency>

         <dependency>

             <groupid>org.projectlombok</groupid>

             <artifactid>lombok</artifactid>

             <version> 1.18 . 10 </version>

             <scope>provided</scope>

         </dependency>

         <dependency>

             <groupid>org.springframework.boot</groupid>

             <artifactid>spring-boot-starter-aop</artifactid>

         </dependency>

         <dependency>

             <groupid>org.springframework.boot</groupid>

             <artifactid>spring-boot-starter-test</artifactid>

             <scope>test</scope>

         </dependency>

     </dependencies>

返回码的枚举

codeenum.java

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

/**

  * @author jcccc

  */

public enum codeenum {

 

     success( 1000 , "请求成功" ),

     fail( 2000 , "请求失败" );

     public final int code;

     public final string msg;

     public integer getcode() {

         return this .code;

     }

     codeenum( int code, string msg) {

         this .code = code;

         this .msg = msg;

     }

     public string getmsg() {

         return this .msg;

     }

}

返回数据的简单封装

resultdata.java 

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

import com.test.myi18n.enums.codeenum;

import lombok.data;

 

/**

  * @author jcccc

  */

@data

public class resultdata<t> {

     private integer code;

     private string message;

     private t data;

     public resultdata( int code, string message) {

         this .code = code;

         this .message = message;

     }

     public static resultdata success(codeenum codeenum) {

         return new resultdata(codeenum.code, codeenum.msg);

     }

     public static resultdata success(string msg) {

         return new resultdata(codeenum.success.getcode(),msg);

     }

}

locale、 messagesource的简单方法封装

localemessage.java

?

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

import org.springframework.beans.factory.annotation.autowired;

import org.springframework.context.messagesource;

import org.springframework.context.i18n.localecontextholder;

import org.springframework.stereotype.component;

 

import java.util.locale;

 

/**

  * @author jcccc

  */

@component

public class localemessage {

     @autowired

     private messagesource messagesource;

     public string getmessage(string code){

         return this .getmessage(code, new object[]{});

     }

     public string getmessage(string code,string defaultmessage){

         return this .getmessage(code, null ,defaultmessage);

     }

     public string getmessage(string code,string defaultmessage,locale locale){ return this .getmessage(code, null ,defaultmessage,locale); }

     public string getmessage(string code,locale locale){

         return this .getmessage(code, null , "" ,locale);

     }

     public string getmessage(string code,object[] args){ return this .getmessage(code,args, "" ); }

     public string getmessage(string code,object[] args,locale locale){

         return this .getmessage(code,args, "" ,locale);

     }

     public string getmessage(string code,object[] args,string defaultmessage){ return this .getmessage(code,args, defaultmessage,localecontextholder.getlocale()); }

     public string getmessage(string code,object[]args,string defaultmessage,locale locale){ return messagesource.getmessage(code,args, defaultmessage,locale); }

}

i18n语言转换工具类

i18nutils.java

?

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

import java.util.locale;

import com.test.myi18n.message.localemessage;

import org.springframework.beans.factory.annotation.autowired;

import org.springframework.stereotype.component;

 

@component

public class i18nutils {

 

     @autowired

     private localemessage localemessage;

 

     /**

      * 获取key

      *

      * @param key

      * @return

      */

     public   string getkey(string key) {

         string name = localemessage.getmessage(key);

         return name;

     }

 

     /**

      * 获取指定哪个配置文件下的key

      *

      * @param key

      * @param local

      * @return

      */

     public   string getkey(string key, locale local) {

         string name = localemessage.getmessage(key, local);

         return name;

     }

}

接下来是我们转换的一个关键环节, aop方式拦截 controller接口返回的数据:
 

languageaspect.java

?

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

import lombok.allargsconstructor;

import org.apache.commons.lang3.stringutils;

import org.aspectj.lang.joinpoint;

import org.aspectj.lang.annotation.afterreturning;

import org.aspectj.lang.annotation.aspect;

import org.aspectj.lang.annotation.pointcut;

import org.springframework.beans.factory.annotation.autowired;

import org.springframework.boot.autoconfigure.condition.conditionalonproperty;

import org.springframework.stereotype.component;

import org.springframework.web.context.request.requestattributes;

import org.springframework.web.context.request.requestcontextholder;

 

import javax.servlet.http.httpservletrequest;

import java.util.*;

 

/**

  * @author jcccc

  */

@aspect

@component

@allargsconstructor

@conditionalonproperty (prefix = "lang" , name = "open" , havingvalue = "true" )

public class languageaspect {

     @autowired

     i18nutils i18nutils;

 

     @pointcut ( "execution(* com.test.myi18n.controller.*.*(..)))" )

     public void annotationlangcut() {

     }

 

     /**

      * 拦截controller层返回的结果,修改msg字段

      *

      * @param point

      * @param obj

      */

     @afterreturning (pointcut = "annotationlangcut()" , returning = "obj" )

     public void around(joinpoint point, object obj) {

         object resultobject = obj;

         try {

             requestattributes requestattributes = requestcontextholder.getrequestattributes();

             //从获取requestattributes中获取httpservletrequest的信息

             httpservletrequest request = (httpservletrequest) requestattributes.resolvereference(requestattributes.reference_request);

             string langflag = request.getheader( "lang" );

             if ( null != langflag) {

                 resultdata r = (resultdata) obj;

                 string msg = r.getmessage().trim();

                 if (stringutils.isnotempty(msg)) {

                     if ( "cn" .equals(langflag)) {

                         locale locale = locale.china;

                         msg = i18nutils.getkey(msg, locale);

                     } else if ( "en" .equals(langflag)) {

                         locale locale = locale.us;

                         msg = i18nutils.getkey(msg, locale);

                     } else {

                         msg = i18nutils.getkey(msg);

                     }

                 }

                 r.setmessage(msg);

             }

         } catch (exception e) {

             e.printstacktrace();

             //返回原值

             obj = resultobject;

         }

     }

}

代码简单解读: 

 1.  annotationlangcut 上面切点管控的地址 需要自己改下,改成自己想管控的文件夹路径

 2.  @conditionalonproperty 注解,读取yml 里面lang开头的配置项,key为 open ,value 为true

只有为true,这个aop拦截才会生效

3.  string langflag = request.getheader("lang");
从这句可以看到我这次文章采取的是让对接接口方(前端)在header里面传入需要使用的语言flag。 例如传入 en (英文),意思就是需要把提示语转为英文。

大家可以结合自己的项目实际情况,改为从yml读取或者从数据库读取或者从redis读取等等都可以。

4.  resultdata r = (resultdata) obj;
     string msg = r.getmessage().trim();

这两行代码为了就是把拦截到的obj中的message提示语获取出来, 如果大家项目的返回数据不是我文中使用的 resultdata,则需要自己进行魔改调整。

最后是 三份 mess properties文件:

mess.properties 

自定义的返回语= 您好,如果文章对你有用,请关注+收藏+评论

这个文件按照本文里aop的拦截方式,会先检测 当前 的 语言flag值,如果检测不到就h会到
mess.properties 文件里面找。

mess_en_us.properties

请求成功=success
请求失败=fail

mess_zh_cn.properties

请求成功=请求成功
请求失败=请求失败
success=请求成功
fail=请求失败

最后写个测试接口给大家演示一下效果:
 

?

1

2

3

4

5

6

7

8

9

10

11

12

13

@getmapping ( "test" )

    public resultdata test( @requestparam int testnum) {

        if ( 1 ==testnum){

            return resultdata.success(codeenum.success);

        }

        if ( 2 ==testnum){

            return resultdata.success(codeenum.fail);

        }

        if ( 3 ==testnum){

            return resultdata.success( "自定义的返回语" );

        }

        return resultdata.success(codeenum.success);

    }

调用测试: 

 

好,就先到这。

到此这篇关于springboot+aop实现返回数据提示语国际化的示例代码的文章就介绍到这了,更多相关springboot 返回数据提示语内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/qq_35387940/article/details/118992865

查看更多关于Springboot+AOP实现返回数据提示语国际化的示例代码的详细内容...

  阅读:18次