1:比较土鳖的方式
String name = req.getParameter("name");
name = new String(name.getBytes("iso-8859-1"),"GBK");
2:土鳖方式另一个
req.setCharacterEncoding(encoding);
res.setContentType("text/html;charset="+encoding);
3:比较正规的用Filter过滤
配置xml
<!-- filter xml 配置 -->
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.xiaofu.filter.MyFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
Myfilter类
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 MyFilter implements Filter {
private String encoding = null;
private FilterConfig filterConfig = null;
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
public void doFilter(ServletRequestservletReq,ServletResponseservletRes,
FilterChain chain) throws IOException, ServletException {
if(filterConfig!=null){
servletReq.setCharacterEncoding(encoding);
servletRes.setContentType("text/html;charset="+encoding);
}
chain.doFilter(servletReq, servletRes);
}
public void init(FilterConfigfilterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
}
}
4:Mysql数据库乱码(改完记得重启)
--1步
在D:\MySql下有个my.ini文件编辑打开
找到里面的default-storage-set=XXX(这个东西有的有两个,有的有一个,有几个改几个)
XXX可以替换为utf-8 或者 gbk(首选)
--2步
当在mysql的控制台输入汉字后插入,select后仍然乱码
在控制台输入set names gbk;
5:建表时候设置表编码
--建库
create database 'test' default character set gbk;
--使用库test
use test
--在test库里面建表students
create table students(id int);
此时students表的编码为gbk