JPBC ing: 留言板之二:处理jsp中出现的中文乱码问题--字符过滤器

JPBC ing: 留言板之二:处理jsp中出现的中文乱码问题--字符过滤器

      在参数传递过程中,经常会碰到中文乱码问题,有好多种解决方法,其中一种就是用到过滤器。

CharacterEncodingFilter.java
package  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;
/** */ /**
 * jsp中文乱码的Filter过滤器
 * 
@author nonels
 *
 
*/


public   class  CharacterEncodingFilter  implements  Filter  {
    
protected String encoding;    //    字符编码
    protected boolean ignore;    //    是否忽略大小写
    public void init(FilterConfig filterConfig) throws ServletException {
        encoding 
= filterConfig.getInitParameter("encoding");
        String value 
= filterConfig.getInitParameter("ignore");
        
if (value == null{
            ignore 
= true;
        }
 else if (value.equalsIgnoreCase("true")) {
            ignore 
= true;
        }
 else if (value.equalsIgnoreCase("yes")) {
            ignore 
= true;
        }

    }


    
public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filterChain) 
throws IOException, ServletException {
        
if (ignore == true || encoding != null{
             request.setCharacterEncoding(encoding);
             filterChain.doFilter(request, response);
        }

    }


    
public void destroy() {
        encoding 
= null;
    }

    

}


XML中的配置加上以下:
       < filter >
        
< filter-name > CharacterEncodingFilter </ filter-name >
        
< filter-class > filter.CharacterEncodingFilter </ filter-class >
        
< init-param >
            
< param-name > ignore </ param-name >
            
< param-value > true </ param-value >
        
</ init-param >
        
< init-param >
            
< param-name > encoding </ param-name >
            
< param-value > GBK </ param-value >
        
</ init-param >
    
</ filter >
    
< filter-mapping >
        
< filter-name > CharacterEncodingFilter </ filter-name >
        
< url-pattern > /* </ url-pattern >
    
</ filter-mapping >

你可能感兴趣的:(JPBC ing: 留言板之二:处理jsp中出现的中文乱码问题--字符过滤器)