HttpServletResponse应用(一)---解决中文乱码问题

一、解决中文输出乱码问题

由于计算机中的数据都是以二进制形式存储的,因此,当传输文本时,就会发生字符和字节之间的转换。字符与字节之间的转换是通过查码表完成的,将字符转换成字节的过程称为编码,将字节转换成字符的过程称为解码,如果编码和解码使用的码表不一致就会导致乱码问题

1.创建Servlet

public class ChineseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String data="中国人";
		PrintWriter out=response.getWriter();
		out.println(data);
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	//浏览器测试网址 http://localhost:8080/chapter04/ChineseServlet
}

2.运行结果出现乱码

HttpServletResponse应用(一)---解决中文乱码问题
出现乱码问题

3.两种方法解决乱码问题

第一种方式:

//设置HttpServletResponse使用utf-8编码
response.setCharacterEncoding("tuf-8");
//通知浏览器使用utf-8解码
response.setHrader("Content-Type","text/html;charset=utf-8");

第二种方式:

//包含第一种方式的两个功能
response.setContentType("text/html;charset=utf-8");

两种方法中所用方法的功能描述传送门

通常为了代码简洁使用第二种方式。

修改上面的代码,再次运行:

public class ChineseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//解决中文乱码
		//方法1
		//设置HttpServletResponse使用utf-8编码
		response.setCharacterEncoding("utf-8");
		//通知浏览器使用utf-8编码
		response.setHeader("Content-Type","text/html;charset=utf-8");
		/*/
		 * 方法二
		 * response.setContentType("text/html;charset=utf-8");
		 */
		
		String data="中国人";
		PrintWriter out=response.getWriter();
		out.println(data);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	//浏览器测试网址 http://localhost:8080/chapter04/ChineseServlet
}

运行结果
HttpServletResponse应用(一)---解决中文乱码问题
中文乱码问题完美解决!

上一篇:HttpServletRequest初识


下一篇:k8s 20220222 Service