web應用程序在提交中文數據的時候,後臺常常出現亂碼現象。爲了完全分析產生緣由,作了一個簡單測試:html
建立一個簡單的java web應用程序,沒有使用任何框架,部署在tomcat環境中。java
使用谷歌和ie瀏覽器分別進行測試,測試結果以下:web
Browser | Method | Tomcat URIEncoding | httpServletRequest | System.out |
Chrome | GET | - | - | (亂碼) |
Chrome | GET | - | setCharacterEncoding("gb2312") | (亂碼) |
Chrome | GET | - | setCharacterEncoding("utf-8") | (亂碼) |
Chrome | GET | URIEncoding="gb2312" | - | (亂碼) |
Chrome | GET | URIEncoding="gb2312" | setCharacterEncoding("gb2312") | (亂碼) |
Chrome | GET | URIEncoding="gb2312" | setCharacterEncoding("utf-8") | (亂碼) |
Chrome | GET | URIEncoding="utf-8" | - | 中文正常顯示 |
Chrome | GET | URIEncoding="utf-8" | setCharacterEncoding("gb2312") | 中文正常顯示 |
Chrome | GET | URIEncoding="utf-8" | setCharacterEncoding("utf-8") | 中文正常顯示 |
Chrome | POST | - | - | (亂碼) |
Chrome | POST | - | setCharacterEncoding("gb2312") | (亂碼) |
Chrome | POST | - | setCharacterEncoding("utf-8") | 中文正常顯示 |
Chrome | POST | URIEncoding="gb2312" | - | (亂碼) |
Chrome | POST | URIEncoding="gb2312" | setCharacterEncoding("gb2312") | (亂碼) |
Chrome | POST | URIEncoding="gb2312" | setCharacterEncoding("utf-8") | 中文正常顯示 |
Chrome | POST | URIEncoding="utf-8" | - | (亂碼) |
Chrome | POST | URIEncoding="utf-8" | setCharacterEncoding("gb2312") | (亂碼) |
Chrome | POST | URIEncoding="utf-8" | setCharacterEncoding("utf-8") | 中文正常顯示 |
IE11 | GET | - | - | (亂碼) |
IE11 | GET | - | setCharacterEncoding("gb2312") | (亂碼) |
IE11 | GET | - | setCharacterEncoding("utf-8") | (亂碼) |
IE11 | GET | URIEncoding="gb2312" | - | (亂碼) |
IE11 | GET | URIEncoding="gb2312" | setCharacterEncoding("gb2312") | (亂碼) |
IE11 | GET | URIEncoding="gb2312" | setCharacterEncoding("utf-8") | (亂碼) |
IE11 | GET | URIEncoding="utf-8" | - | 中文正常顯示 |
IE11 | GET | URIEncoding="utf-8" | setCharacterEncoding("gb2312") | 中文正常顯示 |
IE11 | GET | URIEncoding="utf-8" | setCharacterEncoding("utf-8") | 中文正常顯示 |
IE11 | POST | - | - | (亂碼) |
IE11 | POST | - | setCharacterEncoding("gb2312") | (亂碼) |
IE11 | POST | - | setCharacterEncoding("utf-8") | 中文正常顯示 |
IE11 | POST | URIEncoding="gb2312" | - | (亂碼) |
IE11 | POST | URIEncoding="gb2312" | setCharacterEncoding("gb2312") | (亂碼) |
IE11 | POST | URIEncoding="gb2312" | setCharacterEncoding("utf-8") | 中文正常顯示 |
IE11 | POST | URIEncoding="utf-8" | - | (亂碼) |
IE11 | POST | URIEncoding="utf-8" | setCharacterEncoding("gb2312") | (亂碼) |
IE11 | POST | URIEncoding="utf-8" | setCharacterEncoding("utf-8") | 中文正常顯示 |
從上面的測試結果看出:瀏覽器
1.若是是GET請求,應在tomcat的server.xml中設置 URLEncoding="UTF-8" 。tomcat
2.若是是POST請求,請在後臺設置 httpServletRequest.setCharacterEncoding("utf-8"); 或經過使用MVC框架並設置字符編碼參數來解決亂碼問題。框架
如下是測試頁面代碼:post
<html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <title>字符編碼測試</title> </head> <body> <form name="posttest" action="/posttest" method="post"> 提交測試(POST): <input type="text" name="user" value="中文正常顯示" /> <input type="submit" value="Submit" /> </form> <br /> <a href="/gettest?user=中文正常顯示">請點擊這裏進行GET測試</a> </body> </html>