首页 > 其他分享 >中文乱码问题

中文乱码问题

时间:2022-11-08 09:35:37浏览次数:55  
标签:问题 中文 String ename request 乱码 address

在Servlet中POST请求中文乱码,Get请求与响应中文乱码。
中文乱码解决方法:
POST

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		post方法在请求时出现乱码的情况
//		方法二:request.setCharacterEncoding 方法用于将请求体重的字符集转换为UTF-8,需要放在第一行
		request.setCharacterEncoding("UTF-8");
		String ename = request.getParameter("ename");
		String address = request.getParameter("address");
//     	        方法一:使用如下方法
//		String utf8Ename = new String(ename.getBytes("iso-8859-1"),"utf-8");
//		String utf8Address = new String(address.getBytes("iso-8859-1"),"utf-8");
//		System.out.println(utf8Ename+":"+utf8Address);
	}

GET

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		对于Tomcat8.x的版本,默认get请求发送中文就是UTF-8的格式,因此无需转换
		String ename = request.getParameter("ename");
		String address = request.getParameter("address");
		System.out.println(ename+":"+address);
//		响应时的中文乱码解决方法如下,POST和GET相同的方法
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().println(ename+":"+address);
	}

若是Tomacat是8.X之前的版本,需要自行设置。需要在Tomcat的conf目录下的server.xml中大概63行左右的位置添加 URIEncoding="UTF-8"。

标签:问题,中文,String,ename,request,乱码,address
From: https://www.cnblogs.com/LittleKevin/p/16868551.html

相关文章