JSP/Servlet頁面中文顯示為亂碼的解決方式

          經過網上搜索和自己的經驗,JSP/Servlet頁面的中文顯示為亂碼的問題可以細分為5類:
          1. JSP頁面顯示亂碼。
          2. Servlet接收Form/Request傳遞的參數時顯示為亂碼
          3. JSP接收Form/Request傳遞的參數時顯示為亂碼
          4. 用<jsp:forward page="catalog2.html"></jsp:forward>時頁面顯示亂碼
          5. 數據庫存取的時候產生亂碼。
          解決方式:
          1. JSP頁面顯示亂碼的解決方式:
          第一種方式為在頁面的開頭加上:
          <%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%>
          <!--這里的 GBK可以由 gb2312代替,此處以GBK為例。下同 -->
          注:有時候如果不再頁面開頭加上這句,則頁面中無法保存中文字符,并提示:中文字符在不能被iso-8859-1字符集mapped,這是由于默認情況下,JSP是用iso-8859-1來編碼的,可以在Window->Preferences->General->Content Type選項下,在右邊的窗口選擇Text->Jsp,然后在下面的Default Encoding由默認的iso-8859-1改為GBK,然后點擊update即可解決。
          然而這種方式會帶來一些問題:由于這一句在其他文件include該文件的時候不能被繼承,所以include它的文件也需要在文件開頭加上這句話,此時如果用的是pageEncoding="gbk"則會出現問題。類似于org.apache.jasper.JasperException: /top.jsp(1,1) Page directive: illegal to have multiple occurrences of contentType with different values (old: text/html;charset=GBK, new: text/html;charset=gbk).
          類似地,如果兩個文件一個用的是gbk,一個用的是gb2312也會出現問題。
          另一種更好的解決方式為:
          在項目的web.xml中添加以下片段:
          <!-- 下面的代碼為解決頁面亂碼問題而加入 -->
          <jsp-config>
                      <jsp-property-group>
                          <description>
                             Special property group for JSP Configuration JSP example.
                          </description>
                          <display-name>JSPConfiguration</display-name>
                          <url-pattern>*.jsp</url-pattern>
                          <el-ignored>true</el-ignored>
                          <page-encoding>GBK</page-encoding>
                          <scripting-invalid>false</scripting-invalid>
                          <include-divlude></include-divlude>
                          <include-coda></include-coda>
                      </jsp-property-group>           
                      <jsp-property-group>
                          <description>
                             Special property group for JSP Configuration JSP example.
                          </description>
                          <display-name>JSPConfiguration</display-name>
                          <url-pattern>*.html</url-pattern>
                          <el-ignored>true</el-ignored>
                          <page-encoding>GBK</page-encoding>
                          <scripting-invalid>false</scripting-invalid>
                          <include-divlude></include-divlude>
                          <include-coda></include-coda>
          </jsp-property-group>
          </jsp-config>
          <!--       添加的代碼結束 -->
          2. Servlet接收Form/Request傳遞的參數時顯示為亂碼的解決方式:
          第一種解決方式為在用到request方法的前面加上這條語句:
          request.setCharacterEncoding("GBK");
          同樣地,這也會由于頁面設置中GbK或gB2312大小寫不同或者采用不同的漢語字符集而發生錯誤。
          另一種更好的解決方式為:添加一個名為SetCharacterEncodingFilter的filter。
          filter的源文件為(參見apach安裝目錄下\webapps\jsp-examples\WEB-INF\classes\filters中的SetCharacterEncodingFilter.java文件):

          package com.filters;import java.io.IOException;
          import javax.servlet.Filter;
          import javax.servlet.FilterChain;
          import javax.servlet.FilterConfig;
          import javax.servlet.ServletException;
          import javax.servlet.ServletRequest;
          import javax.servlet.ServletResponse;
          import javax.servlet.UnavailableException;
          public class SetCharacterEncodingFilter implements Filter {

                   protected String encoding = null;
                   protected FilterConfig filterConfig = null;
                   protected boolean ignore = true;
                   public void destroy() {
                       this.encoding = null;
                       this.filterConfig = null;
                   } 
                   public void doFilter(ServletRequest request, ServletResponse response,
                                        FilterChain chain)
          throws IOException, ServletException {
                       // Conditionally select and set the character encoding to be used
                       if (ignore || (request.getCharacterEncoding() == null)) {
                           String encoding = selectEncoding(request);
                           if (encoding != null)
                               request.setCharacterEncoding(encoding);
                       }
          // Pass control on to the next filter
                       chain.doFilter(request, response);
                   }

                  public void init(FilterConfig filterConfig) throws ServletException {
          this.filterConfig = filterConfig;
                       this.encoding = filterConfig.getInitParameter("encoding");
                       String value = filterConfig.getInitParameter("ignore");
                       if (value == null)
                           this.ignore = true;
                       else if (value.equalsIgnoreCase("true"))
                           this.ignore = true;
                       else if (value.equalsIgnoreCase("yes"))
                           this.ignore = true;
                       else
                           this.ignore = false;
                   }
                     protected String selectEncoding(ServletRequest request) {
                       return (this.encoding);
                   }

          }
          同時在web.xml中添加一下片段:
          <!-- 為解決亂碼問題而添加 --> 
                    <filter>
                       <filter-name>SetCharacterEncoding</filter-name>
                       <filter-class>com.filters.SetCharacterEncodingFilter</filter-class>
                       <init-param>
                           <param-name>encoding</param-name>
                           <param-value>GBK</param-value>
                       </init-param>
                    </filter>
                   <filter-mapping>
                       <filter-name>SetCharacterEncoding</filter-name>
                       <url-pattern>/*</url-pattern>
                   </filter-mapping>
          <!-- 添加代碼結束 --> 
          3. JSP接收Form/Request傳遞的參數時顯示為亂碼
          當我們按照第二種亂碼的解決方式修改了web.xml并添加了filter之后,有時候并不一定就對亂碼問題高枕無憂了,有時候我們會奇怪的發現Sevlet接收Form/Request傳遞的參數可以正常顯示了,但是jsp頁面接受Form/Request傳遞的參數卻仍然顯示為亂碼。這是為什么呢?
          對于我遇到的情況而言,我發現是由于我在用Form發送信息的頁面采用了這樣的html:
          <form action="getParam.jsp" >
          姓名<input type="text" name ="UserName"> <br>
          選出你喜歡吃的水果:
          <input type ="checkbox" name = "checkbox1" value = "蘋果"> 蘋果
          <input type ="checkbox" name = "checkbox1" value = "西瓜"> 西瓜
          <input type ="checkbox" name = "checkbox1" value = "桃子"> 桃子
          <input type ="checkbox" name = "checkbox1" value = "葡萄"> 葡萄
          <input type = "submit" value = "提交">
          </form>
          也就是說沒有指定form的method屬性。而問題就發生在此,Form的默認mothod屬性為get.
          而get是通過在發送請求的url后面加?然后加參數和值來傳遞數據的的,編碼格式為ASCII.這就要求我們在傳遞的數據中有非ASCII字符或是超過了100個字符,那么你必須使用method="post",否則就會出現亂碼。
          所以解決方式為:第二種亂碼的解決方式+在發送頁面的Form中指定method為post.
          4. 用<jsp:forward page="catalog2.html"></jsp:forward>時頁面顯示亂碼的解決方式
          此時實際上亂碼的原因和產生其他幾種亂碼的原因不同,它的原因在于我們用eclipse編輯要forward的html或者jsp文件時,采用的編碼是可以產生中文亂碼的編碼而不是GBK或者GB2312.所以解決方式就是把eclipse編輯器的編碼方式改為GBK或者GB2312.
          具體操作方式見:上文紅色字體部分。
          5. 數據庫存取的時候產生亂碼的解決方式(由于尚未遇到此問題,不知道說的是什么,故此部分完全采用楓之閣的文字。如有侵權,請及時聯系我刪除之,謝謝。)
          當然,在寫數據庫時,也要保正數據庫的編碼與其它一致:
          我們可以在系統盤windows目錄下的my.ini文件,在文件中插入一行default-character-set=GBK,但上面說了這么多,大家也應該明白些了吧,改動太多的默認設置不是我的風格,因此上,這一行還是不要加的好。
          但不管怎么樣,我們還是要創建一個基于中文編碼的數據庫,當然,用客戶端登錄的時候,某些客戶用自動把字體編碼轉換成中文編碼。在這里,我想說一下在DOS下創建中文編碼數據庫的方法:
          在進入數據庫的時候,用mysql --default-character-set=gbk -u root -p 這句話進入mysql,然后創建數據庫,如:create database admin;這樣創建起來的數據庫就是基于中文編碼的了。
          用連接數據庫的時候,讀出的數據也可能是亂碼,解決這個問題的方法非常簡單,只要在你建立數據庫連接的時候把URL設置成下面這個樣子就可以了:URL= jdbc:mysql://localhost:3306/my_database?useUnicode=true&characterEncoding=GBK
          好了,說了這么多,總結一句話結束吧,把各種地方的編碼統一起來,那么,所在的亂碼問題就都解決了!

          posted on 2009-04-16 10:22 MichaelLee 閱讀(2378) 評論(1)  編輯  收藏

          評論

          # re: JSP/Servlet頁面中文顯示為亂碼的解決方式[未登錄] 2014-02-24 11:44 longlong

          我按照上面的方法操作,可是還是沒有解決亂碼問題,該怎么辦呢,求教?  回復  更多評論   


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          <2009年4月>
          2930311234
          567891011
          12131415161718
          19202122232425
          262728293012
          3456789

          導航

          統計

          公告

          ====Michael Lee====
          =Java Sofware Engineer=
          =Work @ Beijing=
          ---再煩,也別忘微笑;再急,也要注意語氣;再苦,也別忘堅持;再累,也要愛自己!---
          ---低調做人,你會一次比一次穩健;高調做事,你會一次比一次優秀---
          ---成功的時候不要忘記過去;失敗的時候不要忘記還有未來---

          常用鏈接

          留言簿(2)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 新龙县| 黄冈市| 且末县| 陆良县| 邹平县| 姚安县| 凯里市| 绿春县| 长海县| 罗源县| 东台市| 固始县| 双峰县| 凉城县| 景谷| 成武县| 微博| 中牟县| 房产| 日土县| 乳山市| 乌苏市| 许昌县| 萨嘎县| 延庆县| 新余市| 普宁市| 田东县| 永善县| 比如县| 策勒县| 绥棱县| 容城县| 明星| 嘉峪关市| 九龙城区| 清新县| 孟津县| 交口县| 会宁县| 德令哈市|