Grails国际化实例

2019-01-04 11:26:47

Grails实现国际化(中英文切换)

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

英文配置messages.properties

  1. user.username=Username
  2. user.password=Password
  3. username.tip=Enter username
  4. password.tip=Enter password

中文配置messages_zh_CN.properties

  1. user.username=用户名
  2. user.password=密码
  3. username.tip=请输入用户名
  4. password.tip=请输入密码

gsp页面代码

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta name="layout" content="main"/>
  5. <title>Welcome to Grails</title>
  6. <asset:link rel="icon" href="favicon.ico" type="image/x-ico" />
  7. </head>
  8. <body>
  9. <div class="main">
  10. <form action="${createLink(controller: "lang",action: "index")}" autocomplete="off">
  11. <table>
  12. <tr>
  13. <td colspan="2">
  14. <a href="${request.contextPath}/lang/index/zh_CN" class="btn btn-danger">中文</a>
  15. <a href="${request.contextPath}/lang/index/en_US" class="btn btn-info">英文</a>
  16. </td>
  17. </tr>
  18. <tr>
  19. <td class="col-lg-1">
  20. <g:message code="user.username" />
  21. </td>
  22. <td class="col-lg-11">
  23. <input type="text" name="username" placeholder="<g:message code="username.tip"/>" class="form-control">
  24. </td>
  25. </tr>
  26. <tr>
  27. <td>
  28. <g:message code="user.password" />
  29. </td>
  30. <td>
  31. <input type="password" name="username" placeholder="<g:message code="password.tip"/>" class="form-control">
  32. </td>
  33. </tr>
  34. <tr>
  35. <td colspan="2">
  36. <input type="button" class="btn btn-default" value="登录">
  37. </td>
  38. </tr>
  39. </table>
  40. </form>
  41. </div>
  42. </body>
  43. </html>

控制器

  1. package i18n
  2. import org.springframework.web.servlet.LocaleResolver
  3. import org.springframework.web.servlet.support.RequestContextUtils
  4. class LangController {
  5. def index() {
  6. LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request)
  7. if("zh_CN".equals(params.id)) {
  8. localeResolver.setLocale(request, response, new Locale("zh", "CN"))
  9. } else {
  10. localeResolver.setLocale(request, response, new Locale("en", "US"))
  11. }
  12. redirect(uri:"/")
  13. }
  14. }

实现效果


0
1
0

添加评论

正在回复:
取消
3
0
1
0