天天看點

【JSP開發】response輸出中文和資料的問題

package cn.edu.Response;


import java.io.IOException;
import java.io.OutputStream; 
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;


import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


//servlet中用OutputStream輸出中文和資料的問題
public class ResponseDemo1 extends HttpServlet {




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


	private void test1(HttpServletResponse response) throws IOException,
			UnsupportedEncodingException {
		//程式以什麼碼表輸出了,程式就一定要控制浏覽器以什麼碼表打開
		//text/html;如果寫成text/html,的話浏覽器會提示下載下傳
		response.setHeader("Content-type", "text/html;charset=UTF-8");
        String data="中國";
        
        ServletOutputStream out =response.getOutputStream(); 
        //浏覽器預設的位元組編碼是gb2312
        out.write(data.getBytes("UTF-8"));
	}
	
	private void test2(HttpServletResponse response) throws IOException,
	UnsupportedEncodingException {
	String data="中國";
	
	OutputStream out =response.getOutputStream(); 
	//用html技術中meta标簽模拟了一個http響應頭,來控制浏覽器的行為
	out.write("<meta http-equiv='content-type'  content='text/html;charset=UTF-8'>".getBytes());
	out.write(data.getBytes("UTF-8"));
	
	out.write((1+"").getBytes());//這樣寫1才會出來
}




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


		doGet(request,response);
	}


}
           

繼續閱讀