Web Project 3 乱码解决方案小结

1. 数据库乱码
使用EMS SQL Manager for MySQL可以容易地解决这个问题,在table的属性对话框中将Character Set设为GBK即可。

2. Ajax应用中Servlet返回内容乱码
设置响应报头的编码即可
response.setHeader("Content-Type", "text/html;charset=GB2312");

3. JSP页面显示乱码
在页面开头加上
<%@ page pageEncoding="GBK"%>

4. request.getParameter产生乱码
用post方法只要在获取参数前设置编码即可
request.setCharacterEncoding("GBK");
get方法还需要在获取参数后转换编码
name = new String(name.getBytes("ISO8859-1"), "GBK");

5. google到的另一个解决方法,不过貌似不成功 -,-
package  filter;

import  javax.servlet.Filter;
import  javax.servlet.FilterConfig;
import  javax.servlet.ServletException;
import  javax.servlet.ServletRequest;
import  javax.servlet.ServletResponse;
import  javax.servlet.FilterChain;
import  java.io.IOException;

public   class  EncodingFilter  implements  Filter  {
  
protected FilterConfig filterConfig;

  
protected String encodingName;

  
protected boolean enable;

  
public EncodingFilter() {
    
this.encodingName = "UTF-8";
    
this.enable = false;
  }


  
public void init(FilterConfig filterConfig) throws ServletException {
    
this.filterConfig = filterConfig;
    loadConfigParams();
  }


  
private void loadConfigParams() {
    
this.encodingName = this.filterConfig.getInitParameter("encoding");
    String strIgnoreFlag 
= this.filterConfig.getInitParameter("enable");
    
if (strIgnoreFlag.equalsIgnoreCase("true")) {
      
this.enable = true;
    }
 else {
      
this.enable = false;
    }

  }


  
public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) 
throws IOException, ServletException {
    
if (this.enable) {
      request.setCharacterEncoding(
this.encodingName);
    }

    chain.doFilter(request, response);
  }


  
public void destroy() {
  }

}
web.xml
  < filter >
    
< filter-name > EncodingFilter </ filter-name >
    
< filter-class > filter.EncodingFilter </ filter-class >
    
< init-param >
      
< param-name > encoding </ param-name >
      
< param-value > UTF-8 </ param-value >
    
</ init-param >
    
< init-param >
      
< param-name > enable </ param-name >
      
< param-value > true </ param-value >
    
</ init-param >
  
</ filter >
  
< filter-mapping >
    
< filter-name > EncodingFilter </ filter-name >
    
< url-pattern > /user/* </ url-pattern >
  
</ filter-mapping >
  
< filter-mapping >
    
< filter-name > EncodingFilter </ filter-name >
    
< url-pattern > /manager/* </ url-pattern >
  
</ filter-mapping >   
  

你可能感兴趣的:(Web Project 3 乱码解决方案小结)