Content-Type响应头,设置码表

	1.Content-Type响应头的作用
		1.设置了response使用的码表
		2.通知了浏览器使用指定的码表去解码。
	2.常用的方法:
		setHeader(头名称,值);
		setContentType(值); 
	3.乱码的根本原因
		reponse默认使用iso8859-1进行编码,浏览器默认使用utf-8或者gbk解码,因此有乱码。		
		解决方案:让reponse和浏览器使用统一的码表进行编码
	4.代码
		public class ContentTypeServlet extends HttpServlet {
		 
			public void doGet(HttpServletRequest request, HttpServletResponse response)
					throws ServletException, IOException {
	//对浏览器输出一段中文   ,  getByte() 默认使用 系统默认的码表(gbk)码表进行编码, 我们的谷歌浏览器默认也是使用了系统默认码表进行解码。
			/*	OutputStream out = response.getOutputStream();
				out.write("中国".getBytes());
			*/
				
				//设置response使用的码表
				//response.setCharacterEncoding("UTF-8");
				//通过设置Content-Type响应头实现response与浏览器使用统一码表。    
				/*
				 * Content-Type作用:
				 * 			1. 设置了repsonse使用的码表。
				 * 			2. 通知了浏览使用何种码表去解码。
				 */
				//原始的方式:response.setHeader("Content-Type", "text/html;charset=gbk");
				/* 改良的方式*/
			       response.setContentType("text/html;charset=gbk");
				PrintWriter out = response.getWriter();
				out.write("中国");
			}
		 
			public void doPost(HttpServletRequest request, HttpServletResponse response)
					throws ServletException, IOException {
				doGet(request, response);
			}
		}

猜你喜欢

转载自blog.csdn.net/chenzuen113113/article/details/80904590