Popular MVC框架国际化翻译功能@LanguageTranslate使用示例

简介

此项目用于演示如何使用popularmvc提供的响应信息国际化能力。有如下几种场景:

  1. 错误提示国际化,popularmvc框架层自动处理
  2. 通过接口语言类型locale参数进行指定,响应信息自动翻译,使用@LanguageTranslate注解
  3. 响应信息,翻译成指定语言@LanguageTranslate(locale = "en_US")
  4. 使用国际化翻译器手动翻译业务内容,使用国际化管理器LanguageTranslateManager手动翻译

项目示例

1 项目结构

  • 项目结构

    │  pom.xml
    │  README.md
    │      
    └─src
        ├─main
        │  ├─java
        │  │  └─com
        │  │      └─danyuanblog
        │  │          └─framework
        │  │              └─demo
        │  │                  └─popularmvc
        │  │                      │  StartDemoApplication.java
        │  │                      │  
        │  │                      └─controller
        │  │                          │  TestManualTranslteResponseController.java
        │  │                          │  TestTranslateBusinessErrorController.java
        │  │                          │  TestTranslateResponseController.java
        │  │                          │  
        │  │                          └─dto
        │  │                                  CustomResponse.java
        │  │                                  LanguageInfoDto.java
        │  │                                  LicenseDto.java
        │  │                                  
        │  └─resources
        │      │  application.yml
        │      │  
        │      └─i18n
        │          ├─custom
        │          │      systemErrorCodeInfo.properties
        │          │      systemErrorCodeInfo_en_US.properties
        │          │      systemErrorCodeInfo_zh_CN.properties
        │          │      
        │          └─messages
        │                  messages.properties
        │                  messages_en_US.properties
        │                  messages_zh_CN.properties
        │                  
        └─test
            └─java
                └─com
                    └─danyuanblog
                        └─framework
                            └─popular
                                └─mvc
    
  • 引入模块依赖,在pom.xml添加

	<dependency>
		<groupId>com.danyuanblog.framework</groupId>
		<artifactId>popular-web-mvc</artifactId>
		<version>${popular-web-mvc.version}</version>
	</dependency>

2 启用PopularMvc框架

/**  
* Title StartDemoApplication.java  
* Description  
* @author danyuan
* @date Oct 31, 2020
* @version 1.0.0
* site: www.danyuanblog.com
*/ 
package com.danyuanblog.framework.demo.popularmvc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.danyuanblog.framework.popularmvc.annotation.EnablePopularMvc;

@SpringBootApplication
@EnablePopularMvc
public class StartDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(StartDemoApplication.class, args);
	}
}

3 配置信息

3.1 项目配置信息

application.yml

spring.messages: 
  #默认会加载加载i18n/messages/messages字典翻译信息,这里我们再配置自定义国际化系统错误码的字典翻译信息
  basename: i18n/custom/systemErrorCodeInfo

3.2 国际化翻译配置信息

你可以选择都配置在默认的i18n/messages/messages文件中,也可以分类进行存放。

  • 自定义系统错误码国际化翻译

    这里只对’接口未找到错误码做自定义的翻译

    systemErrorCodeInfo_en_US.properties

    #修改默认的系统错误码提示信息
    system.invalidParam=[self-defined]this invalid param{0}[{1}]
    

    systemErrorCodeInfo_zh_CN.properties

    #修改默认的系统错误码提示信息
    system.invalidParam=[自定义]这是无效参数{0}[{1}]
    
  • 自定义业务错误码国际化

    当业务条件不满足时,可以抛出业务错误码提示用户!

    messages_en_US.properties

    #业务错误码翻译
    USER_ACCOUNT_NOT_FOUND=Sorry , The user account[{0}] not found, please check your input.
    USER_PASSWORD_ERROR=Sorry, Password error.
    

    messages_zh_CN.properties

    #业务错误码翻译
    USER_ACCOUNT_NOT_FOUND=对不起,你输入的账号[{0}]没有找到,请检查下你的账号哦!
    USER_PASSWORD_ERROR=对不起,你输入的密码有误,请核对!
    
  • 自定义业务内容国际化翻译

    业务执行过程中也可以对业务数据进行国际化翻译,比如商品名字,描述信息等等。

    messages_en_US.properties

    #业务信息翻译
    danyuan.name=danyuan
    danyuan.info=The universe is invincible, handsome boy!
    danyuan.tags=Sunshine, positive, love life, embrace change, understand tolerance
    
    #只提供了英文版的版权信息,这时候可以指定版权信息只能翻译成英文
    LICENSE= license info.
    

    messages_zh_CN.properties

    #业务信息翻译
    danyuan.name=淡远
    danyuan.info=宇宙无敌帅小伙!
    danyuan.tags=阳光,积极向上,热爱生活,拥抱变化,懂得容忍
    

4 源码示例说明

4.1 响应信息国际化

我们可以对响应内容的全部字符串信息进行自动国际化翻译,也可以只对其中的某些字段进行国际化翻译。

  • 接口源码TestTranslateResponseController.java

    /**  
    * Title TestTranslateResponseController.java  
    * Description  
    * @author danyuan
    * @date Jan 4, 2021
    * @version 1.0.0
    * site: www.danyuanblog.com
    */ 
    package com.danyuanblog.framework.demo.popularmvc.controller;
    
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.danyuanblog.framework.demo.popularmvc.controller.dto.CustomResponse;
    import com.danyuanblog.framework.demo.popularmvc.controller.dto.LanguageInfoDto;
    import com.danyuanblog.framework.demo.popularmvc.controller.dto.LicenseDto;
    
    @Api(tags = "测试自动翻译响应信息相关接口列表")
    @RestController
    public class TestTranslateResponseController {
    
    	@GetMapping("getLanguageInfo")
    	@ApiOperation(value="测试信息国际化自动翻译整个对象", notes="测试信息国际化自动翻译整个对象")
    	public LanguageInfoDto getLanguageObjectInfo(@RequestParam(name = "info", required = false) String info){
    		return new LanguageInfoDto(info,"danyuan.name");
    	}
    	
    	@GetMapping("getLanguageFieldInfo")
    	@ApiOperation(value="测试信息国际化自动翻译某些字段", notes="测试信息国际化自动翻译某些字段")
    	public CustomResponse getLanguageFieldInfo(){
    		return new CustomResponse("danyuan.name", 22, true, "danyuan.info", "danyuan.tags");
    	}
    	
    	@GetMapping("getEnglishLicence")
    	@ApiOperation(value="测试获取指定语言的版权信息", notes="测试获取指定语言的版权信息")
    	public LicenseDto getEnglishLicence(){
    		return new LicenseDto("LICENSE");
    	}
    }
    
  • 其他dto信息

    CustomResponse.java

    /**  
    * Title CustomResponse.java  
    * Description  
    * @author danyuan
    * @date Jan 3, 2021
    * @version 1.0.0
    * site: www.danyuanblog.com
    */ 
    package com.danyuanblog.framework.demo.popularmvc.controller.dto;
    
    import java.io.Serializable;
    
    import com.danyuanblog.framework.popularmvc.annotation.LanguageTranslate;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import lombok.experimental.Accessors;
    
    @Data
    @Accessors(chain = true)
    @AllArgsConstructor
    @NoArgsConstructor
    public class CustomResponse implements Serializable{/** 
    	 *serialVersionUID
    	 */
    	private static final long serialVersionUID = 1L;
    	
    	@LanguageTranslate
    	private String name;
    	
    	private Integer age;
    	
    	private Boolean sex;
    	
    	@LanguageTranslate
    	private String info;
    	
    	@LanguageTranslate
    	private String tags;
    }
    

    LanguageInfoDto.java

    /**  
    * Title LanguageInfoDto.java  
    * Description  
    * @author danyuan
    * @date Nov 16, 2020
    * @version 1.0.0
    * site: www.danyuanblog.com
    */ 
    package com.danyuanblog.framework.demo.popularmvc.controller.dto;
    
    import java.io.Serializable;
    
    import com.danyuanblog.framework.popularmvc.annotation.LanguageTranslate;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    @Data
    @LanguageTranslate
    @AllArgsConstructor
    @NoArgsConstructor
    public class LanguageInfoDto implements Serializable{
    
    	/** 
    	 *serialVersionUID
    	 */
    	private static final long serialVersionUID = 1L;
    
    	private String info;
    	
    	private String name;
    }
    

    LicenseDto.java

    /**  
    * Title LicenseDto.java  
    * Description  
    * @author danyuan
    * @date Jan 4, 2021
    * @version 1.0.0
    * site: www.danyuanblog.com
    */ 
    package com.danyuanblog.framework.demo.popularmvc.controller.dto;
    
    import java.io.Serializable;
    
    import com.danyuanblog.framework.popularmvc.annotation.LanguageTranslate;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class LicenseDto implements Serializable{/** 
    	 *serialVersionUID
    	 */
    	private static final long serialVersionUID = 1L;
    
    	@LanguageTranslate(locale = "en_US")
    	private String licence;
    }
    

4.2 业务错误自动翻译

异常信息也能自动翻译,无需做任何处理,只需要接口调用者指定自己需要的语言类型即可,框架自动进行转换。

  • 接口源码TestTranslateBusinessErrorController.java

    /**  
    * Title TestTranslateBusinessErrorController.java  
    * Description  
    * @author danyuan
    * @date Jan 4, 2021
    * @version 1.0.0
    * site: www.danyuanblog.com
    */ 
    package com.danyuanblog.framework.demo.popularmvc.controller;
    
    import javax.validation.Valid;
    import javax.validation.constraints.NotEmpty;
    
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    
    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.danyuanblog.framework.popularmvc.exception.BusinessException;
    
    
    @Api(tags = "测试自动翻译业务异常信息相关接口列表")
    @RestController
    @Validated
    public class TestTranslateBusinessErrorController {
    	
    	@PostMapping("getLanguageInfo")
    	@ApiOperation(value="测试登录失败", notes="测试提示账户存在错误")
    	public void login(@Valid @NotEmpty String account, @Valid @NotEmpty String password){
    		//TODO: 执行业务逻辑
    		
    		//TODO:当发现账户信息不存在,直接抛出异常即可
    		if(!"admin".equals(account)){
    			throw new BusinessException("USER_ACCOUNT_NOT_FOUND").setParam(account);
    		}
    		
    		//TODO:当发现密码错误时,直接抛出异常
    		if(!"123456".equals(password)){
    			throw new BusinessException("USER_PASSWORD_ERROR");
    		}
    		
    		//TODO:组装响应信息,然后返回
    		
    	}
    }
    

4.3 手动翻译

也可以注入LanguageTranslateManager语言翻译管理器进行手动翻译。

  • 接口源码TestManualTranslteResponseController.java

    /**  
    * Title TestManualTranslteResponseController.java  
    * Description  
    * @author danyuan
    * @date Jan 4, 2021
    * @version 1.0.0
    * site: www.danyuanblog.com
    */ 
    package com.danyuanblog.framework.demo.popularmvc.controller;
    
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Lazy;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.danyuanblog.framework.popularmvc.LanguageTranslateManager;
    
    @Api(tags = "测试手动翻译响应内容接口列表")
    @RestController
    public class TestManualTranslteResponseController {
    
    	@Autowired
    	@Lazy
    	private LanguageTranslateManager languageTranslateManager;
    	
    	@GetMapping("getUserEnDesc")
    	@ApiOperation(value="测试获取用户英文描述信息", notes="测试获取用户英文描述信息")
    	public String getUserEnDesc(@RequestParam(name = "infoDict", required = false) String infoDict){
    		if(StringUtils.isEmpty(infoDict)){
    			infoDict = "danyuan.info";
    		}
    		return languageTranslateManager.get(infoDict, "en_US");
    	}
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
外文文献: 1. Spring Framework: A Comprehensive Overview The Spring Framework is a popular open-source framework for building enterprise applications in Java. It provides a comprehensive programming and configuration model for modern Java-based enterprise applications on any deployment platform. This article provides a comprehensive overview of the Spring Framework, including its architecture, key features, and benefits. 2. The Spring Framework: A Survey of its Usage and Popularity The Spring Framework is one of the most popular Java frameworks for building enterprise applications. This article presents a survey of the usage and popularity of the Spring Framework among Java developers. The survey covers topics such as the usage of Spring's core features, the adoption of Spring Boot, and the popularity of Spring-based frameworks such as Spring Data and Spring Security. 3. Spring Boot: A Practical Guide to Building Modern Applications Spring Boot is a popular framework for building modern Java-based applications. It provides a set of opinionated defaults and tools that simplify the development of Spring-powered applications. This article provides a practical guide to building modern applications with Spring Boot, including topics such as creating a new Spring Boot project, configuring the application, and deploying it to production. 4. Spring Security: A Comprehensive Guide to Securing Modern Applications Spring Security is a powerful and flexible framework for securing modern Java-based applications. It provides a comprehensive set of security features, including authentication, authorization, and secure communication. This article provides a comprehensive guide to securing modern applications with Spring Security, including topics such as configuring authentication and authorization, securing REST APIs, and implementing secure communication. 5. Spring Data: A Comprehensive Guide to Data Access in Spring Spring Data is a framework that provides a set of abstractions and tools for working with data in Spring-based applications. It supports a wide range of data stores, including relational databases, NoSQL databases, and in-memory data structures. This article provides a comprehensive guide to data access in Spring with Spring Data, including topics such as configuring data sources, mapping data models, and implementing data repositories. 翻译: 1. Spring Framework:综合概述 Spring Framework是一个流行的开源框架,用于在Java上构建企业应用程序。它为现代基于Java的企业应用程序在任何部署平台上提供了全面的编程和配置模型。本文提供了Spring Framework的综合概述,包括其架构、关键特性和优势。 2. Spring Framework:使用和流行度调查 Spring Framework 是构建企业应用程序的最受欢迎的 Java 框架之一。本文针对 Java 开发人员对 Spring Framework 的使用和流行度进行了调查。调查涵盖了 Spring 的核心功能使用情况、Spring Boot 的采用情况以及基于 Spring框架,如 Spring Data 和 Spring Security 的流行度。 3. Spring Boot:构建现代应用程序的实用指南 Spring Boot 是一个流行的框架,用于构建基于 Java 的现代应用程序。它提供了一组默认值和工具,简化了 Spring 引擎应用程序的开发。本文提供了一个关于使用 Spring Boot 构建现代应用程序的实用指南,包括创建一个新的 Spring Boot 项目、配置应用程序以及将其部署到生产环境等主题。 4. Spring Security:保护现代应用程序的综合指南 Spring Security 是一个功能强大且灵活的框架,用于保护现代基于 Java 的应用程序。它提供了全面的安全功能,包括身份验证、授权和安全通信。本文提供了一个保护现代应用程序的综合指南,包括配置身份验证和授权、保护 REST API 和实现安全通信等主题。 5. Spring Data:Spring 中数据访问的综合指南 Spring Data 是一个框架,提供了一组抽象和工具,用于在基于 Spring 的应用程序中处理数据。它支持各种数据存储,包括关系型数据库、NoSQL 数据库和内存数据结构。本文提供了一个关于使用 Spring Data 进行数据访问的综合指南,包括配置数据源、映射数据模型和实现数据仓库等主题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值