客户端提交数据给服务器端,如果数据中带有中文的话,有可能会出现乱码情况,那么可以参照以下方法解决。
* 如果是GET方式
1. 代码转码
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("userName="+username+"==password="+password);
//get请求过来的数据,在url地址栏上就已经经过编码了,所以我们取到的就是乱码,
//tomcat收到了这批数据,getParameter 默认使用ISO-8859-1去解码
//先让文字回到ISO-8859-1对应的字节数组 , 然后再按utf-8组拼字符串
username = new String(username.getBytes("ISO-8859-1") , "UTF-8");
System.out.println("userName="+username+"==password="+password);
直接在tomcat里面做配置,以后get请求过来的数据永远都是用UTF-8编码。
2. 可以在tomcat里面做设置处理 conf/server.xml 加上URIEncoding="utf-8"
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>
* 如果是POST方式
这个说的是设置请求体里面的文字编码。
request.setCharacterEncoding("UTF-8");
这行设置一定要写在getParameter之前。