Java服務器端處理亂碼問題
1.字節流輸出
resp.getOutputStream().write(s.getBytes());//這樣不會出現亂碼
resp.getOutputStream().write(s.getBytes("UTF-8"));// 出現亂碼 用戶修改編碼格式即可恢復正常
解決亂碼的方式
//1.通知瀏覽器採用某種方式進行編碼
resp.setHeader("Content-Type", "text/html;charset=UTF-8");
//2.讓服務器的編碼用一種編碼,通知瀏覽器的編碼
resp.setCharacterEncoding("utf-8");
resp.setHeader("Content-Type", "text/html;charset=UTF-8");
resp.getOutputStream().write(s.getBytes("UTF-8"));
//3.推薦方法
resp.setContentType("text/html;charset=utf-8");// 設定服務器將數據編碼時用的碼錶,通知瀏覽器解碼用的碼錶
resp.getOutputStream().write(s.getBytes("utf-8"));
字符流輸出時
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().write(s);
Request解決亂碼問題
//採用post方法的時候採用這個解決中文亂碼問題
request.setCharacterEncoding("UTF-8");
//採用get方法的時候採用這個解決中文亂碼問題
String name = new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
如果獲取的中文控件較多的話,像上述解決方法太麻煩,可以修改tomcat中的配置文件打開tomcat文件夾中的conf->server.xml
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding = "UTF-8"/>
//後面的URIEncrding = "utf-8"就是我們需要添加的內容