struts2國際化和語言轉換遇到的一些問題和解決方案及瞭解到的2.0的特性

國際化和語言轉換 一些基本代碼步驟  我這裏就不寫了,網上很多

我只說做的時候遇到的一些關鍵性問題:

1.struts.properties這個資源文件中 

      struts.custom.i18n.resources=resources.Messages

這條語句的意思是什麼?  其實很簡單,resources是路徑的名字,在項目中的體現是resources包下的message.properties

文件,這個包下不僅是這個文件,還有你的語言包格式爲 名稱_語言代碼_國家代碼  如: Messages_zh_CN.properties和Messages_en_US.properties   

關於資源文件轉碼問題推薦一個Eclipse插件叫Arbitrary    url爲http://propedit.sourceforge.jp/eclipse/updates/

 

 

 

 

 

語言切換原理:它的原理爲在執行Action方法前,i18n攔截器查找請求中的一個名爲"request_locale"的參數。如果其存在,攔截器就將其作爲參數實例化Locale對象,並將其設爲用戶默認的區域(Locale),最後,將此Locale對象保存在session的名爲“WW_TRANS_I18N_LOCALE”的屬性中   (這裏也就是說session中保存的WW_TRANS_I18N_LOCALE這個值決定了這個請求的語言包)

 代碼演示:

public class SwitchLanguageAction extends BaseAction {
 private String referer;
 private static Logger logger = Logger.getLogger(SwitchLanguageAction.class);

 public String execute() throws Exception {
  String request_locale = request.getParameter("request_locale");
  if (request_locale.equals("zh_CN"))
   request.getSession().setAttribute("WW_TRANS_I18N_LOCALE",
     java.util.Locale.CHINA);
  if (request_locale.equals("en_US"))
   request.getSession().setAttribute("WW_TRANS_I18N_LOCALE",
     java.util.Locale.US);
  Cookie cookie = new Cookie(LanguageGlobals.USER_SESSION_NAME + "_LANG",
    request_locale);
  cookie.setMaxAge(31536000);
  cookie.setPath("/");
  response.addCookie(cookie);
  logger.debug(request_locale);

  String ref = request.getHeader("referer");
  if (null != referer) {
   setReferer(ref);
  }
  return SUCCESS;
 }

 public String getReferer() {
  return referer;
 }

 public void setReferer(String referer) {
  this.referer = referer;
 }

}

上面的代碼中有個referer屬性: 它是記錄之前的url  請看我的配置文件

<action name="language" class="com.szc.Action.SwitchLanguageAction">
   <result name="success">${referer}</result>
  </action>

這裏的${referer}用到了動態result,它指定的是action的屬性

 

 

language.action?request_locale=zh_CN  這是我的頁面url   根據之前的經驗參數的name 做好起request_locale

 

 

爲了保持修改語言後 在本臺機器上的其他同樣瀏覽器也能起作用 我用到了cookie 作爲保存語言的手段 所以我又寫了個filter  代碼如下:

 

public class LanguageFilter implements Filter 
{
 private static Logger logger = Logger.getLogger(LanguageFilter.class);
 public void destroy() {
 }

 public void doFilter(ServletRequest arg0, ServletResponse arg1,
   FilterChain arg2) throws IOException, ServletException {
  
  HttpServletRequest request = (HttpServletRequest)arg0;
  HttpServletResponse response=(HttpServletResponse)arg1;
  request.setCharacterEncoding("utf-8");
  
  HttpSession session = request.getSession();
  
  String request_locale = request.getParameter("request_locale");
  logger.debug("---------request_locale:"+request_locale);
  Locale locale = (Locale) session.getAttribute("WW_TRANS_I18N_LOCALE");
  if(locale == null)
  {
   Cookie[] allcookies = request.getCookies();
   if(allcookies!=null)
   {
    for(int i=0;i<allcookies.length;i++)
    {
     if(allcookies[i].getName().equalsIgnoreCase(LanguageGlobals.USER_SESSION_NAME+"_LANG"))
     {
      if(allcookies[i].getValue().equalsIgnoreCase("zh_CN"))
       locale = Locale.CHINA;
      else if(allcookies[i].getValue().equalsIgnoreCase("zh_TW"))
       locale = Locale.TAIWAN;
      else if(allcookies[i].getValue().equalsIgnoreCase("en_US"))
       locale = Locale.US;
     }
    }
   }
  }
  if(locale==null)
  {
   locale = request.getLocale();
  }
  logger.debug(request.getLocale());
  
  request.getSession().setAttribute("WW_TRANS_I18N_LOCALE", locale);
  logger.debug("-----------language:"+locale);
  
  arg2.doFilter(request, response);
  
 }

 public void init(FilterConfig arg0) throws ServletException {
  // TODO Auto-generated method stub
  
 }

 

 

 這段代碼 取得local的順序要注意!! 先session  然後cookie   最後纔是request中的本地locale

頁面部分:

<%@ page language="java" pageEncoding="UTF-8"%>

<%@taglib uri="/WEB-INF/c.tld" prefix="c" %>
<%@taglib prefix="s" uri="/struts-tags"%>
<%@taglib uri="http://jsptags.com/tags/navigation/pager" prefix="pg"%>
<html>

  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  </head>
  <script src="js/jquery/jquery.js" type="text/javascript"></script>
  <script type="text/javascript">
  $(document).ready(function() {
  
  })
  </script>
  <body>
  <a href="language.action?request_locale=zh_CN"><s:text name="index.chinese"/></a>    <a href="language.action?request_locale=en_US"><s:text name="index.english"/></a>
   <form action="lucene.action" method="post" id="serchSucene" name="serchSucene">
     <s:text name="index.keywordAndId"/><input type="text" id="keyword" name="keyword" value="${keyword}"/>
     <input type="submit"/>
     </form> 
   <a href="#"> onclik!!</a>  
    <pg:pager items="${totalRows}" url="lucene.action" index="half-full" maxPageItems="5" maxIndexPages="5" isOffset="<%=false%>" export="pageOffset,currentPageNumber=pageNumber" scope="request">
  <pg:param name="pageSize" value="5"/>
  <pg:param name="keyword" value="${keyword}"/>
  <table align="center">
     <tr>
      <th>id</th>
      <th>CN_N</th>
      <th>created_at</th>
     </tr>
    <c:forEach items="${auctionList}" var="auction">
      <tr>
          <td >${auction.id }</td>
      <td>${auction.cn_n}</td>
       <td>${auction.created_at}</td>
      </tr>
    </c:forEach>
  </table>
    <pg:index>
    <center>
      <table border=0 cellpadding=0 width=10% cellspacing=0>
        <tr align=center valign=top>
<td valign=bottom>
<pg:prev ifnull="true">
<%if (pageUrl != null) {%>
  <td align=right>
    <A HREF="<%=pageUrl%>&pageNo=<%=pageNumber%>">
      <IMG SRC=http://www.google.com/nav_previous.gif alt="" border=0>
      <br>
      <b>上一頁</b>
    </A>
  </td>
<%} else {%>
  <td>
    <IMG SRC=http://www.google.com/nav_first.gif alt="" border=0>
  </td>
<%}%>
</pg:prev>
<pg:pages>
<%if (pageNumber == currentPageNumber) {%>
  <td>
    <IMG SRC=http://www.google.com/nav_current.gif alt="">
    <br>
    <font color=#A90A08><%= pageNumber %>    </font>
  </td>
<%} else {%>
  <td>
    <A HREF="<%=pageUrl%>&pageNo=<%=pageNumber%>">
      <IMG SRC=http://www.google.com/nav_page.gif alt="" border=0>
      <br><%=pageNumber%></A>
  </td>
<%}%>
</pg:pages>
<pg:next ifnull="true">
<%if (pageUrl != null) {%>
  <td>
    <A HREF="<%=pageUrl%>&pageNo=<%=pageNumber%>">
      <IMG SRC=http://www.google.com/nav_next.gif alt="" border=0>
      <br>
      <b>下一頁</b>
    </A>
  </td>
<%} else {%>
  <td>
    <IMG SRC=http://www.google.com/nav_last.gif alt="" border=0>
  </td>
<%}%>
</pg:next>
</td>
        </tr>
      </table>
    </center>
  </pg:index>
    </pg:pager>
  </body>
 
</html>

 

但我項目弄完後  還有一個小問題  就是當cookie中的語言是英文的時候,我重新開個瀏覽器起訪問確是中文的,但我做一個請求處理就變回英文了,我隱約感覺到 它最後還是取的本地locale(也就是request中的locale),如果有知道爲什麼的,希望告訴我聲,有需要我代碼的加我qq  365328730

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章