问题
1.Tomcat默认字符集为ISO-8859-1,应该为UTF-8中文字符集。
2.Servlet中请求与响应都需要设置UTF-8字符集。
解决办法
Html中设置UTF-8中文字符集
<head>
<meta charset="UTF-8">
</head>
通过new String()将ISO-8859-1转换为UTF-8
String userName= request.getParameter("userName");//此处获取的userName为ISO-8859-1字符集格式
String name = new String( userName.getBytes("iso-8859-1"),"utf-8");//name即为utf-8格式
将Post请求中request请求体中字符集设置为UTF-8
(注意:get方法无请求体,因此此方法仅对post方法有效)
requesr.setCharacterEncoding("UTF-8");
将Get请求中Request的字符集设置为UTF-8
1.对于Tomcat8.X版本,默认get方法字符集为utf-8,无需处理。
2.对于tomcat7及早期版本,需要在配置文件server.xml中设置,路径为:tomcat文件安装路径/conf/server.xml,在该文件标签中添加URIEncoding=“UTF-8”
例如:
<connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>
将响应的字符集设置为UTF-8
response.setContentType("text/html;charset=utf-8");