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);
	}

}

猜你喜欢

转载自blog.csdn.net/mchenys/article/details/80908525