Servlet學習筆記心得(二)

二,在使用html表單傳遞信息時,出現了中文顯示亂碼(亂碼和??)都出現過,遂進行實驗考察,在網上搜尋方法解決。css

親測好評:blog.csdn.net/xiazdong/article/details/7217022/html

實驗過程以下:java

在webroot下新建MyHtml.html
<!DOCTYPE html>
<html>
  <head>
    <title>MyHtml.html</title>
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=GB2312">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
  </head>
  
  <body>
    This is my HTML page. <br>
    <form action="servlet/Test" method="GET">
    名字:<input type="text" name="name">
    <br />
    密碼:<input type="text" name="pwd" />
    <input type="submit" value="提交" />
    </form>
  </body>
</html>
<meta http-equiv="content-type" content="text/html; charset=GB2312">

當charset=GB2312時,不管servlet的.java文件內是否添加web

response.setCharacterEncoding("UTF-8");

語句,輸入的名字和密碼中的 中文 都沒法傳遞到地址欄,即html表單的編碼有問題,jsp

因而改成charset=UTF-8ide

結果是中文能夠傳遞到地址欄,即servlet能夠進行讀取,可是否有對應字符的編碼就須要在.java中添加語句:測試

response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");

測試成功~
ui


回想一下,??的出現是由於根本沒有對應編碼,亂碼是編碼的不統一,因此接下來實驗一下兩邊(html和java)編碼的對應關係:this

當html編碼爲UTF-8時,不管java中是UTF-8仍是GB2312,均無問題;編碼


此時發現index.jsp中沒法顯示中文,查看編碼方式爲ISO-8859-1,改爲UTF-8後測試成功。

相關文章
相關標籤/搜索