持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第2天,点击查看活动详情
(3)java代码:HelloServlet.java【基本一样】
一、表单get提交中文参数,乱码问题
(1)配置 web.xml 文件【无需修改】
(2)get 提交方式的表单
这个只是复制一份上面的 greeting_post.html ,命名为 greeting_get.html,
把提交方式由 post 改为 get,如:method="get"
然后把"个人信息post" 改为"个人信息get", 方便区别
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body style="font-size:30px; font-style:italic;">
<form action="hello" method="get">
<fieldset>
<legend>个人信息get</legend>
姓名:<input name="name" /><br /> 年龄:<input name="age" /><br /> 城市:
北京<input type="checkbox" name="city" value="bj" checked="checked" />
上海<input type="checkbox" name="city" value="sh" /> 武汉<input
type="checkbox" name="city" value="wh" /><br /> <input
type="submit" value="提交" />
</fieldset>
</form>
</body>
</html>
(3)java代码:HelloServlet.java【基本一样】
(4)效果演示说明
我们注释掉这两句代码
//只对post提交方式有效,一般表单使用post提交方式
//request.setCharacterEncoding("utf-8");
//这种方式对get和post提交方式,都有效
//注意:tomact 8.x以后默认为UTF-8,就不需要使用此行代码了
//name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
我们重新部署,使用表单get提交方式,在浏览器输入地址:http://localhost:8080/web02/greeting_get.html
编辑
填入信息,点击提交,你会发现 get 提交方式并不会出现乱码。
编辑
或是在浏览器上直接输入,带中文参数的 get请求方式 链接:http://localhost:8080/web02/hello?name=yyh_帅气华
它也不会出现乱码的情况,如下:
编辑
需要注意的是
那是因为:Tomcat8.x默认编码格式是utf-8,Tomcat8之前默认编码格式的都是iso8859-1
我目前使用的是tomact8.5,而我那时候实习的时候最新的是 tomcat6
所以这个要看 tomact 的版本,如果默认情况下,tomcat8之前使用的的编码方式:iso8859-1
出现乱码的时候,那么它的解决方式如下:
解决方式1
把上面 java 代码这句打开
//name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
如果是Tomcat8.x,它的默认编码格式是utf-8,使用上面这句代码,get提交方式反而会出现乱码,如下:
编辑
解决方式2(不推荐)
修改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" />
二、如何知道tomcat默认的编码
1、找到我的 tomact 8.5的安装路径:/ApacheTomcat/webapps/docs/config/http.html
用文本编辑器 Sublime Text 打开 http.html ,搜索 URIEncoding,然后有说明:
This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, UTF-8 will be used unless the org.apache.catalina.STRICT_SERVLET_COMPLIANCE system property is set to true in which case ISO-8859-1 will be used.
翻译过来说是:默认使用了UTF-8编码
2、找到我的 tomact 7.0.100 的安装路径:/ApacheTomcat-7.0.100/webapps/docs/config/http.html
用文本编辑器 Sublime Text 打开 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.
翻译过来说是:默认使用了ISO-8859-1编码
其实在上篇博文:原创 java服务器端开发-servlet:2、Servlet执行过程介绍:常见错误及解决方式、响应数据包、get请求与post请求、编码相关等 的第6点 6、编码相关的问题 也有对编码的相关说明,可以回顾复习一下
另外推荐的博文: