#get,post请求参数中文乱码解决

请求参数乱码提交的中文乱码解决

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");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值