为什么get post会产生乱码?

本文探讨了在Servlet/JSP环境中GET与POST请求下中文乱码的问题及其解决方案。GET请求中,通过调整Tomcat配置使用UTF-8解码;POST请求则需设置request.setCharacterEncoding(UTF-8)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GET

我们一般会把中文进行utf-8 urlencode,然后拼到url后面。 但是在servlet/jsp中用request.getParameter("kw")拿出来然后在urldecode的话还是乱码。为什么会发生这个问题呢? 原来tomcat默认会用iso-8859-1对字符进行urldecode,所以我们decode后还是乱码。 解决办法为

new String(request.getParameter("kw").getBytes("ISO-8859-1"),"UTF-8") 


或者更改tomcat的server.xml让tomcat用UTF-8 decode。

<Connector port="8080" protocol="HTTP/1.1" maxThreads="150" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8"/> 


POST

保证你的html是用UTF-8编码的。 在head里面包含

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>


这样浏览器会以meta中指定的字符集对form里面的数据进行编码。这里我们需要在调用request.getParameter("kw")之前调用request.setCharacterEncoding("UTF-8")。看看这个访问的javadoc

[quote] /**
* Overrides the name of the character encoding used in the body of this
* request. This method must be called prior to reading request parameters
* or reading input using getReader().
*
* @param env a <code>String</code> containing the name of
* the chararacter encoding.
*
* @throws java.io.UnsupportedEncodingException if this is not a valid encoding
*/[/quote]

这个可以指定request body的字符集(所以这个方法对于get是没有用的,get的参数不是在request body里面。)。

POST中只要调用request.setCharacterEncoding("UTF-8")然后request.getParameter("kw")就能拿到正确的结果了。

参考:[url]http://wdlisoft.iteye.com/blog/522026[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值