public class ResponseDemo1 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
test1(resp);
}
//方法1:
public void test1(HttpServletResponse resp) throws IOException, UnsupportedEncodingException {
resp.setHeader("Content-type", "text/html;charset=utf-8");
String data = "中國";
OutputStream output = resp.getOutputStream();
//程式以什麼編碼輸出,那麼一定要設定瀏覽為相對應的編碼開啟.
output.write(data.getBytes("utf-8"));
}
//方法2:
//模擬meta標籤,設定charset為utf-8,這個方法也行. //用html技術中的meta標籤模擬了一個http響應頭,來控制瀏覽器的行為
public void test2(HttpServletResponse response) throws Exception{
String data = "中國_第二個";
OutputStream output= response.getOutputStream();
output.write("<meta http-equiv='content-type' content='text/html;charset=UTF-8'>".getBytes());
output.write(data.getBytes());
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
//********************************情況2:*************************************
public class ResponseDemo2 extends HttpServlet {
private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
test1(response); } public void test1(HttpServletResponse response) throws IOException {
// 方法1:
// 要設定response,所使用的碼錶,以控制reponse以什麼碼錶向瀏覽器寫入資料
// response.setCharacterEncoding("utf-8");
// 同時設定瀏覽器以何種碼錶開啟,指定瀏覽以什麼 碼錶開啟伺服器傳送的資料
// response.setHeader("content-type", "text/html;charset=utf-8");
// 方法2:
response.setContentType("text/html;charset=utf-8"); String data = "中國";
PrintWriter outputStream = response.getWriter();
outputStream.write(data);
} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response); } }