常见编码方式:
ISO-8859-1 西欧码
GB2312 简体中文码GBK 大五码
UTF-8 全球码(推荐)
1.页面(HTML,JSP,Servlet)
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
response.setcontentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("中文");
2.上传(控件)
普通字段(上传中增加的):
item.getString("UTF-8");
文件名:
DiskFileUpload dfu = new ...
dfu.setHeaderEcoding("UTF-8");
3.普通表单提交
post方式:
request.setCharacterEncoding("UTF-8");
get方式:
tomcat--->conf--->server.xml---->增加 URIEncoding="UTF-8"
<Connector URIEncoding="UTF-8" port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<!-- A "Connector" using the shared thread pool-->
4.数据库(MySQL)
如何解决MySQL5.1的编码问题:
(1).修改mysql的核心配置文件:(mysql安装目录下)my.ini
两处字符编码改换:u
default-character-set=utf8
(2).重启MySQL服务器
net stop mysql
net start mysql
(3).重新登录,使用mysql的status命令查看状态信息
这样以后创建的数据库和数据表的默认编码方式就是UTF-8
(4).解决残留数据库和数据表的编码问题
alter database [dbName] default character set utf8;
use [dbName];
alter table [tableName] convert to character set utf8;
(5).为了在dos命令行能够看到UTF-8编码的中文,需要
set names gbk;
(6).接收表单数据时第一行JAVA代码加上request.setCharacterEncoding("UTF-8");
5.Ajax中的乱码
get方式提交:
(1)前台一次或没有转码
url = encodeURI(url);
后台转码
name = new String(name.getBytes("ISO-8859-1"),"UTF-8");
pass = new String(pass.getBytes("ISO-8859-1"),"UTF-8");
(2)前台两次转码
url = encodeURI(encodeURI(url));
后台转码
name = URLDecoder.decode(name,"UTF-8");
pass = URLDecoder.decode(pass,"UTF-8");
6.其它
(1).post: method="post" && pageEcoding="UTF-8/GBK" && TestServlet中首行一定要写
request.setCharacterEcoding("UTF-8");
注: Filter 配置过滤器的时候 只能是post有效
(2).GET href="TestServlet" new String(); onclick="js:funA();"
funA(){
var url = "TestServlet?name='中文' ";
url = encodeURI(url);
window.location.href=url;
}
(3).TestServlet.java
username=URLEcncode(username,"UTF-8");
response.sendRedirect("welcome.jsp?name="+name+"&pass="+pass);
welcome.jsp
request.getparameter("name");
request.getparameter("pass");
name = new String(name.getByte("ISO-8859-1"),"UTF-8");
此篇博客系学习中总结,对初学者有一定帮助,其中一些是老师传授,在这里分享一下,欢迎大家补充或提出意见,共勉!