Spring MVC international configuration

What is internationalization?

Internationalization is the development of technologies that support multiple languages and data formats. In fact, it dynamically responds localized resources to users according to external characteristics.

Localization resource profile

To realize internationalization in spring MVC is to save the language of each region in the configuration file. The configuration content is key/value pair, key is string, value can be string, or any other type of object.
A configuration file represents a language. If you want to support both Chinese and English, you need to provide two property files with the same value in both Chinese and English, corresponding to the same key.
The name of the configuration file is: basename? languageCode? Countrycode.properties, for example, the default file messages.properties, messages? Cn.properties in Chinese. When the configuration file cannot be obtained according to the languageCode, the default configuration file will be used
To convert Chinese characters to Unicode, there are two steps to create a Chinese configuration file:

  1. Create a text file at will
  2. Converting the contents of a text file to a unicode representation

Create the following in the idea. Note that the US in messages [en] us.properties can be removed in fact, usually. Resource Bundle 'messages' is not a folder. This will appear after the configuration file is generated, which actually represents that messages are basename.

If the Chinese in idea is already unicode, but you want to see Chinese

Spring MVC configuration

  1. Annotation driven

    <mvc:annotation-driven validator="validator" />
    
  2. Load international resource file

    <bean id="messageSource"
       class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
     <!-- Specify the profile path and basename -->
    	<property name="basename" value="classpath:config/i18n/messages" />
    	<property name="fileEncodings" value="utf-8" />
    	<!-- cache120s,Can be loaded dynamically messages.properties Data in (modify file data without restart) -->
    	<property name="cacheSeconds" value="120" />
    </bean>
    
  3. Load verifier, need to inject into annotation driver

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    	<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
    	<property name="validationMessageSource" ref="messageSource" />
    </bean>
    
  4. Loading international language region parser: browser language parser

    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver" />
    
  5. Language area change interceptor. When testing and verifying, it is found that it is OK to not configure it

    <mvc:interceptors>
       <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
    </mvc:interceptors>
    

Test code

// Verification tools
public class ValidatorUtils {
    private static final Logger logger = LoggerFactory.getLogger(ValidatorUtils.class);
    public static void beanValid(BindingResult bindingResult, LocaleService localeService) {
        if (bindingResult.hasErrors()) {
            StringBuilder joinMessage = new StringBuilder();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                joinMessage.append(",").append(localeService.getMessage(objectError.getDefaultMessage()));
            }
            if (joinMessage.length() > 0) {
                String message = joinMessage.deleteCharAt(0).toString();
                logger.info("i18n message:" + message);
                throw new RequestParamException(message);
            }
        }
    }
}

// Replace display from messages
@Component
public class LocaleService {
    @Autowired
    private MessageSource messageSource;
    public String getMessage(String code) {
        Locale locale = LocaleContextHolder.getLocale();
        String message = messageSource.getMessage(code, new Object[]{}, locale);
        if (StringUtils.isNotBlank(message)) {
            return message;
        }
        return code;
    }
}

// abnormal
@RestControllerAdvice
public class ExceptionHandle {
    @ExceptionHandler(RequestParamException.class)
    public Object handleRequestParamException(RequestParamException e) {
        Map result = new HashMap();
        result.put("code", 200);
        result.put("message", e.getMsg());
        return result;
    }
}

public class RequestParamException extends RuntimeException{
    public RequestParamException(String msg) {
        this.msg = msg;
    }
    private String msg;
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
}

// Test interface and entity
@RestController
@RequestMapping("/bindingResult")
public class BindingResultController {

    @Resource
    private LocaleService localeService;

    @RequestMapping("/test")
    public Object test(@Valid Person person, BindingResult result) {
        ValidatorUtils.beanValid(result, localeService);
        return new Object();
    }
}
// Omit set and get methods
public class Person implements Serializable {
   @NotNull(message = "person.name_is_null")
   private String name;
   @NotNull(message = "person.age_is_null")
   @Range(min = 1, max = 200, message = "person.age_is_illegal")
   private Integer age;
}

Test screenshots

p7+
172 original articles published, 723 praised, 410000 visitors+
His message board follow

Keywords: Spring Hibernate

Added by Locust on Thu, 05 Mar 2020 07:39:05 +0200