servlet 解決中文亂碼
阿新 • • 發佈:2020-10-28
目錄
1 get請求request亂碼
在Tomcat7及以下版本,客戶端以UTF-8的編碼傳輸資料到伺服器端,而伺服器端的request物件使用的是ISO8859-1這個字元編碼來接收資料,伺服器和客戶端溝通的編碼不一致因此才會產生中文亂碼的。
解決辦法:在接收到資料後,先獲取request物件以ISo8859-1字元編碼接收到的原始資料的位元組陣列,然後通過位元組陣列以指定的編碼構建字串,解決亂碼問題。
Tomcat8的版本中get方式不會出現亂碼了,因為伺服器對url的編碼格式可以進行自動轉換。
tomcat8以下版本解決get中文亂碼
String username = req.getParameter("username");
username = new String(username.getBytes("iso8859-1"), "utf-8");
2 post請求request亂碼
在獲取引數前設定setCharacterEncoding
為utf-8
req.setCharacterEncoding("UTF-8");
String username = req.getParameter("username");
3 response亂碼
方式一:
resp.setCharacterEncoding("utf-8"); //設定 HttpServletResponse使用utf-8編碼 resp.setHeader("Content-Type", "text/html;charset=utf-8"); //通知瀏覽器使用utf-8解碼
方式二(優先使用):
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
riter.println("註冊成功");
4 使用例子
package com.zjw; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/rs") public class RegisterServlet extends HttpsServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); //tomcat8及以上版本不要使用轉碼,否則會亂碼 // username = new String(username.getBytes("iso8859-1"), "utf-8"); String password = req.getParameter("password"); System.out.println(username + " " + password); PrintWriter writer = resp.getWriter(); writer.println("註冊成功"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //解決post中request中文亂碼 req.setCharacterEncoding("UTF-8"); String username = req.getParameter("username"); String password = req.getParameter("password"); System.out.println(username + " " + password); //響應給客戶端 //解決response中文亂碼 resp.setContentType("text/html;charset=utf-8"); PrintWriter writer = resp.getWriter(); writer.println("註冊成功"); } }