萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> jsp編程 >> 常見JSP中文亂碼例子及其解決方法

常見JSP中文亂碼例子及其解決方法

      JSP開發應用是,中文亂碼是個比較常見的問題,其根源是:Web容器默認的字符處理編碼是ISO-8859-1。

實例一、JSP頁面顯示時

  1. <html> 
  2.     <head> 
  3.        <title>中文亂碼——JSP頁面顯示時</title> 
  4.     </head> 
  5.     <body> 
  6.        <center> 
  7.            <br/> 
  8.            <h1>木蘭辭擬古決絕詞柬友</h1> 
  9.            <p>人生若只如初見,何事秋風悲畫扇。</p> 
  10.        <p>等閒變卻故人心,卻道故人心易變。</p> 
  11.        <p>骊山語罷清宵半,淚雨霖鈴終不怨。</p> 
  12.        <p>何如薄幸錦衣郎,比翼連枝當日願。</p> 
  13.        </center> 
  14.     </body> 
  15. </html> 

運行結果:

解決方法:為其指定中文字符集,<html>前加入

  1. <%@ page contentType="text/html;charset=gb2312" %> 

實例二、JSP頁面傳遞中文參數時

注冊頁面:

  1. <%@ page contentType="text/html;charset=gb2312" %> 
  2. <html> 
  3.     <head> 
  4.        <title>中文亂碼——JSP頁面傳遞中文參數時</title> 
  5.     </head> 
  6.     <body> 
  7.        <h2>申請賬號:</h2> 
  8.        <form action="userMsg.jsp" method="POST"> 
  9.            <p>郵箱:&nbsp;<input type="text"name="email" id="email"/><p/> 
  10.            <p>昵稱:&nbsp;<input type="text"name="nickname" id="nickname"/><p/> 
  11.  &n

bsp;         <p>密碼:&nbsp;<input type="password"name="password" id="password"/><p/> 

  •            <p>性別:&nbsp;<input type="radio"name="sex" id="sex"value="男" /> 男  
  •                          <input type="radio" name="sex"id="sex" value="女" /> 女<p/> 
  •            <textarea  name="introduction"id="introduction" rows="5" cols="27">一句話介紹自己...</textarea> 
  •            <p><input type="submit"value="提交申請"></p> 
  •        </form> 
  •     </body> 
  • </html> 

個人信息頁面:

  1. <%@ page contentType="text/html;charset=gb2312" %> 
  2. <html> 
  3.     <head> 
  4.        <title>中文亂碼——JSP頁面傳遞中文參數時 </title> 
  5.     </head> 
  6.     <body> 
  7.        <center> 
  8.            <h2>用戶信息:</h2> 
  9.            <% String email = request.getParameter("email"); %> 
  10.            <% String nickname = request.getParameter("nickname"); %> 
  11.            <% String password = request.getParameter("password"); %> 
  12.            <% String sex = request.getParameter("sex"); %> 
  13.            <% String introduction = request.getParameter("introduction");%> 
  14.            <p>郵箱:&nbsp;<

;% out.print(email); %><p/> 

  •            <p>昵稱:&nbsp;<% out.print(nickname); %><p/> 
  •            <p>密碼:&nbsp;<% out.print(password); %><p/> 
  •            <p>性別:&nbsp;<% out.print(sex); %><p/> 
  •            <p>個人介紹:<%out.print(introduction); %></p> 
  •        </center> 
  •     </body> 
  • </html> 

運行結果:

解決方法:修改個人信息頁面如下

  1. <%@ page contentType="text/html;charset=gb2312" %> 
  2. <html> 
  3.     <head> 
  4.        <title>中文亂碼——JSP頁面傳遞中文參數時 </title> 
  5.     </head> 
  6.     <body> 
  7.        <h2>用戶信息:</h2> 
  8.        <%&nb
copyright © 萬盛學電腦網 all rights reserved