请求参数乱码提交的中文乱码解决
Get
1.修改tomcat默认的编码方式
默认情况下,tomcat使用的的编码方式:iso-8859-1
修改tomcat下的conf/server.xml文件
找到如下代码:
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
这段代码规定了Tomcat监听HTTP请求的端口号等信息。
可以在这里添加一个属性:URIEncoding,将该属性值设置为UTF-8,即可让Tomcat(默认ISO-8859-1编码)以UTF-8的编码处理get请求。
修改完成后:
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" />
缺点:不常用,比较死板,如果出现两个项目时一个为utf-8,一个为gbk的时候就会很头疼了
2.先编码再解码
//第一种方法
String username=request.getParameter("username");
//先使用iso-8859-1进行编码
String encodeUsername=URLEncoder.encode(username,"iso-8859-1");
//在使用utf-8进行解码
String username=URLEncoder.encode(encodeUsername,"utf-8");
第二种方法
String username=request.getParameter("username");
username=new String(username.getBytes("iso-8859-1"),"utf-8");
Post
1.先编码再解码
//第一种方法
String username=request.getParameter("username");
username=new String(username.getBytes("iso-8859-1"),"utf-8");
2.设置请求编码(重点)
//第二种方法,这种方法只对请求体有用
request.setCharacterEncoding("utf-8");
String username=request.getParameter("username");