java get 请求 返回值乱码

Python019

java get 请求 返回值乱码,第1张

您好,提问者:

    如果包含中文,不建议使用get方式,可采用post提交方式。

//可以采用加密、解码的方式进行加码提交,例如:

//加码

String str = java.net.URLEncoder.encode("中国","UTF-8")

//解码

String jiema = java.net.URLDecoder.decode(str,"UTF-8")

get方式提交的参数编码,只支持iso8859-1编码。

因此,如果里面有中文。

在后台就需要转换编码,如下

String zhongwen = request.getParameter("zhongwen")

zhongwen = new String(zhongwen.getBytes("iso8859-1"),"GBK")

前提是你页面编码就是GBK,如果是utf-8,那上面那句代码后面就改成utf-8

编码问题首先检查编码和解码是否一致。看下你的jsp是否编码设置了utf-8,默认是iso-8859-1,

然后就是解码的时候的编码,在你的servlet或者controller中检查request和response是否设置了编码,一般是request.setCharacterEncoding("utf-8")response.set...

如果都设置了的话,post发送数据应该是不会乱码的。get发送数据乱码,是因为你的jsp中设置的编码utf-8没有生效在get请求下,解决方案两种:1、修改服务器中的默认编码,

在tomcat安装目录下的conf/server.xml中,有如下的配置:

<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>可以设置端口

这里呢,也可以设置另外一个跟上述编码问题有关的参数信息:URIEncoding,该配置决定了使用get请求通过浏览器地址栏访问tomcat时的编码方式,默认的编码方式使ISO8859-1,这一点我们可以从官网文档(https://tomcat.apache.org/tomcat-7.0-doc/config/http.html) 获悉:

URIEncoding:This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, ISO-8859-1 will be used.

知道了这点,接下来就简单了,我们可以这样配置,则上述代码中,就不需要再从ISO8859-1转为UTF-8了:

URIEncoding="UTF-8"

就是改成这样: <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>

即可。

或者使用后台手动进行解码:

String s=new String(str.getbyte("iso-8859-1"),"utf-8")

先解码后编码。

如果嫌每次这样麻烦,可以写过滤器拦截你的get清秀将request中的parameter转换编码