瀏覽器解析數據的亂碼問題

//用response的outputStream輸出中文
public class ResponseDemo1 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		test4(response);
	}
	
	//方法二,用meta標籤模似一個http響應頭,控制瀏覽器以u8打開
	private void test2(HttpServletResponse response)
		throws UnsupportedEncodingException, IOException {
		
		String data = "中國";
		byte b[] = data.getBytes("UTF-8");
		
		response.getOutputStream().write("<meta http-equiv='content-type' content='text/html;charset=UTF-8'>".getBytes());
		response.getOutputStream().write(b);
	}
	//方法一
	private void test1(HttpServletResponse response)
			throws UnsupportedEncodingException, IOException {
		//設置一個頭信息,通知瀏覽器以U8打開
		response.setHeader("content-type", "text/html;charset=UTF-8");
		
		String data = "中國";
		byte b[] = data.getBytes("UTF-8");
		response.getOutputStream().write(b);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

二,用response的write寫數據:html

//response的write流輸出中文的問題
public class ResponseDemo2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//用write流寫字符,它會默認查詢ISO8859-1的碼錶
		//這句話是讓它去查u8的碼錶
		response.setCharacterEncoding("UTF-8");
		
		//在通知瀏覽器以u8打開
		response.setHeader("content-type", "text/html;charset=UTF-8");
		
		//寫了這句話就至關於上面兩句話
//		response.setContentType("text/html;charset=UTF-8");
		
		String data = "中國";
		response.getWriter().write(data);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
相關文章
相關標籤/搜索