在部署tomcat项目时经常会遇到中文乱码问题,解决的方法可参考以下步骤。
1、更改Tomcat安装目录下的conf\server.xml,指定浏览器的编码格式为“utf-8”格式:
方法是更改 server.xml 中的
<Connector port="8080" maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" URIEncoding='utf-8' />
注意设置URIEncoding='utf-8'
2、设置servlet过滤器
方法是在项目的web.xml文件中加入以下filter
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>net.servlet.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
net.servlet.CharacterEncodingFilter中的代码如下
package net.servlet; 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 CharacterEncodingFilter implements Filter { private static String encoding = "utf-8";
private boolean ignore=true; protected String getEncoding(){
return this.encoding;
} @Override
public void destroy() {
// TODO Auto-generated method stub } @Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
String pencoding="utf-8";
if(ignore||null==request.getCharacterEncoding()){
if(pencoding!=null){
request.setCharacterEncoding(pencoding);
}
}
// System.out.println("encoding===="+encoding);
response.setContentType("text/html;charset="+pencoding);
// do something here
//当前工作全部完成后,将请求放开给过滤器链的下一filter
chain.doFilter(request, response); } @Override
public void init(FilterConfig filterConfig) throws ServletException {
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;
}
}
}3、如果以上两个步骤还没有解决乱码问题,那就有可能是数据库本身的问题。应当将数据库的编码方式统一设置为utf-8。此外,还应注意设置数据库连接的编码类型。如果使用mysql数据库,在指定数据库连接url时应指定characterEncoding。
<DataSources>
<ds name="MyPrintPhoto">
<username>root</username>
<password>123456</password>
<dburl>jdbc:mysql://localhost:3306/myprintphoto?useUnicode=true&characterEncoding=utf8&useOldAliasMetadataBehavior=true
</dburl>
<classname>com.mysql.jdbc.Driver</classname>
</ds>
</DataSources>