一。URL:
修改%TOMCAT_HOME%\conf\server.xml文件
找到如下内容:
<Connector
port="80" maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
debug="0" connectionTimeout="20000"
disableUploadTimeout="true" />
添加:URIEncoding="utf-8"
修改后内容如下:
<Connector
port="80" maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
debug="0" connectionTimeout="20000"
disableUploadTimeout="true" URIEncoding="utf-8" />
二。处理表单乱码:
用过滤器吧。
下面是用于处理表单的一个filter
package hrl.util.filter;
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 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
this.ignore=false;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO 自动生成方法存根
if (ignore || (request.getCharacterEncoding() == null)) {
String encoding = selectEncoding(request);
if (encoding != null){
request.setCharacterEncoding(encoding);
}else
System.out.println("encoding has not set");
}
chain.doFilter(request, response);
}
public void destroy() {
// TODO 自动生成方法存根
this.encoding = null;
this.filterConfig = null;
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
}
在web.xml里配置此filter,将其影射到所有页面上
<filter>
<filter-name>encoding filter</filter-name>
<filter-class>hrl.util.filter.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
三。处理jsp&servlet页面显示乱码
JSP中:
最顶端加入如下代码:
<%@ page language="java" pageEncoding="UTF-8"%>
servlet中:
在doGet 或doPost方法中加入如下代码:
response.setCharacterEncoding("utf-8");
四。读取properties文件时出现乱码
如果properties文件里含有中文时不可以用ResourceBundle度取,需先对properties文件进行编码转换
在JDK中提供了native2ascii命令 他能够实现字符编码的转换。
假设message.properties 文件在目录WEB-INF/resource目录下
在命令行模式下进入WEB-INF/resource目录,然后执行如下命令
native2ascii –encoding utf-8 message.properties message_zh_CN.properties
参数-encoding表示要转换成的编码格式
执行以上命令以后将生成message_zh_CN.properties文件 现在就可以用ResourceBundle类进行读取了。
五。MYSQL数据库乱码
修改my.ini中关于字体的设置。在连接数据库的URL中指定字符
评论