get和post请求参数乱码的解决方式

请求的中文乱码:
对于get请求:参数追加到地址栏,会使用utf-8编码,服务器(tomcat7)接受到请求之后,使用iso-8859-1解码,所以会出现乱码.
对于post请求,参数是放在请求体中,服务器获取请求体的时候使用iso-8859-1解码,也会出现乱码

解决办法
1.通用的方法:
    new String(参数.getBytes("iso-8859-1"),"utf-8");

2.针对于post请求来说:只需要将请求流的编码设置成utf-8即可
    request.setCharacterEncoding("utf-8");

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

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//request.setCharacterEncoding("utf-8"); get请求设置这个无效果
		String username = request.getParameter("username");//拿到的是乱码,因为tomcat使用ios8859-1来解码,而浏览器是通过utf-8来编码的
		String password = request.getParameter("password");
		
		//通过这种方式解决,先将乱码反编回原来浏览器的编码,然后在用浏览器的编码来解码.
		username = new String(username.getBytes("iso-8859-1"), "utf-8");
		password = new String(password.getBytes("iso-8859-1"), "utf-8");
		System.out.println("get--->username:" + username + " password:" + password);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//针对于post请求来说:只需要将请求流的编码设置成utf-8即可
		request.setCharacterEncoding("utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		System.out.println("post--->username:" + username + " password:" + password);
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值