Grails國際化例項

Genee發表於2019-01-04

Grails實現國際化(中英文切換)

  • grails-app/i18n分別配置英文(messages.properties),中文:(messages_zh_CN.properties

英文配置messages.properties

user.username=Username
user.password=Password
username.tip=Enter username
password.tip=Enter password
複製程式碼

中文配置messages_zh_CN.properties

user.username=使用者名稱
user.password=密碼
username.tip=請輸入使用者名稱
password.tip=請輸入密碼
複製程式碼

gsp頁面程式碼

<!doctype html>
<html>
<head>
    <meta name="layout" content="main"/>
    <title>Welcome to Grails</title>

    <asset:link rel="icon" href="favicon.ico" type="image/x-ico" />
</head>
<body>
    <div class="main">
        <form action="${createLink(controller: "lang",action: "index")}" autocomplete="off">
            <table>
                <tr>
                    <td colspan="2">
                        <a href="${request.contextPath}/lang/index/zh_CN" class="btn btn-danger">中文</a>
                        <a href="${request.contextPath}/lang/index/en_US" class="btn btn-info">英文</a>
                    </td>
                </tr>
                <tr>
                    <td class="col-lg-1">
                        <g:message code="user.username" />
                    </td>
                    <td class="col-lg-11">
                        <input type="text" name="username" placeholder="<g:message code="username.tip"/>" class="form-control">
                    </td>
                </tr>
                <tr>
                    <td>
                        <g:message code="user.password" />
                    </td>
                    <td>
                        <input type="password" name="username" placeholder="<g:message code="password.tip"/>" class="form-control">
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="button" class="btn btn-default" value="登入">
                    </td>
                </tr>
            </table>
        </form>
    </div>
</body>
</html>
複製程式碼

控制器

package i18n

import org.springframework.web.servlet.LocaleResolver
import org.springframework.web.servlet.support.RequestContextUtils

class LangController {

    def index() {
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request)
        if("zh_CN".equals(params.id)) {
            localeResolver.setLocale(request, response, new Locale("zh", "CN"))
        } else {
            localeResolver.setLocale(request, response, new Locale("en", "US"))
        }
        redirect(uri:"/")
    }
}
複製程式碼

實現效果

Grails國際化例項

相關文章