通過前端模態框,進行插入中文的操作,發現傳入數據庫的值是亂碼
servlet源代碼如下:
通過獲取request域中的各個parameter,獲得對應的值。
經過排查後發現,問題出現在JSP傳入值到servlet這段區間。
可能的問題出現在:
1.servlet接收值
2.JSP編碼
3.tomcat編碼
於是一個個進行排查
1.對servlet代碼進行修改:
在doGet方法前幾行加上:
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
發現並不奏效
2.對JSP的代碼進行檢查,將所有編碼屬性設置爲UTF-8,並且進入eclipse,將對應的編碼都改爲UTF-8
仍然不奏效,還是亂碼
3.剩下的可能只有tomcat編碼
於是通過在servlet doGet方法中,進行編碼轉換:
代碼爲:
String name = new String(request.getParameter("qname").getBytes("ISO-8859-1"),"UTF-8");
System.out.println(name);
int question_type_id = Integer.parseInt(request.getParameter("qtype"));
System.out.println(question_type_id);
String content = new String(request.getParameter("qcontent").getBytes("ISO-8859-1"),"UTF-8");
System.out.println(content);
String answer = new String(request.getParameter("qanswer").getBytes("ISO-8859-1"),"UTF-8");
System.out.println(answer);
tomcat默認編碼是ISO-8859-1,我們要通過String的有參構造函數,將其轉換爲UTF-8編碼。
發現有效:
PS:想嘗試通過修改tomcat安裝目錄的conf目錄下的server.xml的屬性:
經嘗試後發現無效。
所以暫定方案爲servlet轉換接收字符串編碼。