① 本身编写filter类html
public class CharsetEncodingFilter implements Filter {mysql
private String charsetEncoding = null;web
private String enable = null;spring
public void destroy() {sql
this.charsetEncoding = null;数据库
this.enable = null;tomcat
}app
public void doFilter(ServletRequest request, ServletResponse response,this
FilterChain arg2) throws IOException, ServletException {编码
if(this.enable.equals("true")) {
request.setCharacterEncoding(charsetEncoding);
response.setContentType("text/html;charset=" + charsetEncoding);
arg2.doFilter(request, response);
}
}
public void init(FilterConfig config) throws ServletException {
this.charsetEncoding = config.getInitParameter("CharsetEncoding");
this.enable = config.getInitParameter("enable");
}
}
说明:上面的encoding根据你用的编码类型决定,在这里我用utf-8
② 在web.xml中配置上面的filter
<filter>
<filter-name>charFilter</filter-name>
<filter-class>com.landtofrest.util.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>charFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
说明:<filter-class>是上面filter类的路径:包.类名
<filter-name>命名随便
或直接在web.xml配置以下:
<filter>
<filter-name>SpringCharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SpringCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
③ 在tomcat中配置server.xml,个人是MYEclipse自带的。我在myEclipse里面找不到tomcat的server.xml。而是在workspace->.metadata->.me_tcat->conf->server.xml那里找到
修改:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8"/>
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8"/>
说明:红色部分是要添上去的
④ 应该能够运行了!?页面参数传到action在控制台输出已经不是乱码,但是数据库查询仍是查不到记录,后面查了不少资料,才知道,mysql中编码也是有讲究的。
找到mysql安装目录,打开my.ini文档,把这句default-character-set=Latin1改为这样子default-character-set=utf8。注意是default-character-set有两句哟。
说明:若是在建表时下面的第⑤步已经作了的话,第④步是没有必要滴。
若是已经作了第④步,第⑤步中建表时有没有必要在指定引擎后再添加DEFAULT CHARSET =utf8,这个我尚未试验…
⑤ 应该能够运行了!?仍是不行。
由于我在mysql用命令【show create table 表名;】查看本身在建表的时候默认的是Latin1,因此得改过来,建表时应该【create 表名()ENGINE=引擎 DEFAULT CHARSET =utf8;】。
或者这样比较麻烦,能够有另外一种办法就是在建表以前用【set names utf8;】命令,这样在关闭mysql以前都用utf8而不用再在建每一个表都是这样。
你会发现若是用【set names utf8;】而没改的话,用insert插入数据时就出现data too long的错误,因此,用想要插入得用【set names gb2312或者gbk;】,习惯用gbk,这样就能够插入数据了。