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); } }
时间: 2024-12-23 19:12:29