jsp数据添加乱码mysql_JSP插入MySQL数据库中文乱码问题解决
通过JSP页面向MySQL数据库插入中文数据时乱码问题
刚开始插入数据时,mysql数据库表内显示???,读取时同样也是???
对此查找了相关资料,首先注意保持服务器、数据库、项目、以及前端编码一致。
具体做法是:
一、项目编码,Eclipse设置。
Eclipse Java EE IDE for Web Developers ->右键项目 -> Properties -> Resource -> Text file encoding ->other utf-8 ->apply and close
二、tomcat服务器编码设置(conf\server.xml)
connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8"/>
三、数据库mysql的my.ini配置文件
[client]
port = 3306
default-character-set=utf8
[mysqldump]
quick
max_allowed_packet = 16M
[mysql]
no-auto-rehash
; Remove the next comment character if you are not familiar with SQL
;safe-updates
default-character-set=utf8
[isamchk]
key_buffer_size = 20M
sort_buffer_size = 20M
read_buffer_size = 2M
write_buffer_size = 2M
[myisamchk]
key_buffer_size = 20M
sort_buffer_size_size = 20M
read_buffer_size = 2M
write_buffer_size = 2M
[mysqlhotcopy]
interactive-timeout
[mysqld]
port = 3306
character-set-server = utf8
修改文件后需要使用net stop mysql/net start mysql关闭开启mysql服务重启mysql服务
四、项目
检查项目中有前端编码的地方
a. JSP页面
pageEncoding="utf-8"%>
b. Servlet服务器端
response.setCharacterEncoding("UTF-8");
c. 其它有编码的地方。
把所有的编码设置一致。本例是为UTF-8.
通过以上步骤还款解决的话,可以在项目中加一个Filter:
package com.kh.utils;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class SetCharacterEncodingFilter implements Filter {
protected String encoding = null;
protected FilterConfig filterConfig = null;
protected boolean ignore = true;
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// Conditionally select and set the character encoding to be used
if (ignore || (request.getCharacterEncoding() == null)) {
String encoding = selectEncoding(request);
if (encoding != null)
request.setCharacterEncoding(encoding);
}
// Pass control on to the next filter
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else if (value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
}
在Web.xml中加入配置代码:
encodingFilter
com.kh.utils.SetCharacterEncodingFilter
encoding
UTF-8
ignore
true
encodingFilter
/*