HttpServlet中解決中文輸出瀏覽器亂碼問題

出現亂碼的原因:瀏覽器端編碼格式與服務器端編碼格式不一樣

字節流輸出中文亂碼

public class TestClass extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String outContent = "中文";
		//獲取響應輸出流
		ServletOutputStream sos = response.getOutputStream();
		//設置瀏覽器端的編碼
		response.setHeader("Content-type", "text/html;charset=utf-8");
		//也可以簡寫response.setContentType("text/html;charset=utf-8");
		//設置服務端寫出的格式
		sos.write(outContent.getBytes("utf-8"));
		
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

字符流輸出中文亂碼

private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String outContent = "中文666!@#";
		//設置服務端和客戶端的編碼形式
		response.setContentType("text/html;charset=utf-8");
		PrintWriter pw = response.getWriter();
		pw.write(outContent);
		
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

設置編碼格式,儘量使用response.setContentType(“text/html;charset=utf-8”)方法,可以一步到位

常見支持中文的編碼

GBK GB18030 GB2312,支持中文的編碼,也支持其他一些字符

UTF-8萬能碼,支持所有字符

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章