欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Response的学习

程序员文章站 2022-04-23 16:53:08
...
/**
 * Response第四个案例:中文乱码问题
 * @author FXC
 *
 */
public class RandomCodeServlet extends HttpServlet {

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		ziFuLiuRandomCode2(resp);
	}

	/**
	 * 1、当【输出流】的编码方式和【浏览器】的编码方式不同时,就会产生乱码的现象
	 * 2、解决方案:使两者的编码方式一致
	 * 	1).设置输出流的编码方式    getBytes("编码方式");
	 * 	2).设置浏览器的编码方式:resp.setHeader("Content-type","text/html;charset=编码方式");
	 * 3、getBytes()这个方法的默认编码方式是GBK,当然也可以通过方法中的参数来改变它的编码方式
	 * @param resp
	 * @throws IOException
	 */
	private void ziFuLiuRandomCode(HttpServletResponse resp) throws IOException {
		resp.setHeader("Content-type", "text/html;charset=utf-8");
		resp.getOutputStream().write("Response的第四个案例:中文乱码问题之字节流对乱码的处理方式。  ".getBytes("utf-8"));
		resp.getOutputStream().write("当【输出流】的编码方式和【浏览器】的编码方式不同时,就会产生乱码的现象。".getBytes("utf-8"));
		resp.getOutputStream().write("解决方案:使两者的编码方式一致".getBytes("utf-8"));
		resp.getOutputStream().write("getBytes()这个方法的默认编码方式是GBK,当然也可以通过方法中的参数来改变它的编码方式".getBytes("utf-8"));
	}
	
    /**
     * 1、字符流有缓存流,它的编码方式是ISO-8859-1
     * 2、解决乱码的方案:使输出流和浏览器的编码方式保持一致
     * 	1)、设置输出流的编码方式:resp.setCharacterEncoding("编码方式");
     * 	2)、设置浏览器的编码方式:resp.setHeader("Content-type","text/html;charset=编码方式");
     * @param resp
     * @throws IOException
     */
	private void ziFuLiuRandomCode2(HttpServletResponse resp) throws IOException {
		resp.setCharacterEncoding("GBK");
		resp.setHeader("Content-type", "GBK");
		resp.getWriter().write("字符流乱码问题的解决方案:1、设置输出流的编码方式,2、设置浏览器的编码方式 ");
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	}

	
}