Resolving spring:messages in javascript for i18n internationalization

后端 未结 4 2223
醉梦人生
醉梦人生 2020-12-02 15:57

I\'m attempting to internationalize some of our code. I have a page in JSPX which is using the tag to resolve strings from a messag

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 16:36

    Thanks for your answer. Here is a more generic solution.

    The idea is to provide a dynamic javascript file named "string.js", containing an associative array of messages registered in the java resource bundle, using current user language.

    1) Create a method in Spring Controller to load all resource keys from resource bundle, and return the view "spring.jsp"

    @RequestMapping(value="strings.js")
    public ModelAndView strings(HttpServletRequest request) {
        // Retrieve the locale of the User
        Locale locale = RequestContextUtils.getLocale(request);
        // Use the path to your bundle
        ResourceBundle bundle = ResourceBundle.getBundle("WEB-INF.i18n.messages", locale);  
        // Call the string.jsp view
        return new ModelAndView("strings.jsp", "keys", bundle.getKeys());
    }
    

    2) Implement the View "strings.jsp"

    <%@page contentType="text/javascript" pageEncoding="UTF-8"
    %><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"
    %><%@taglib prefix="spring" uri="http://www.springframework.org/tags"
    %>var messages = new Array();
    
    messages[""] = "";
    
    

    3) Import "spring.js" in your HTML source code. Messages array is available and loaded with the right language.

    Possible issue: If user change his language, "spring.js" must be reloaded by the navigator, but it will be cached. Clearing the cache is needed when user change his language (or other trick to get the file reloaded).

提交回复
热议问题