夜的天空

三流程序员 寻找自身价值ing

BlogJava 首页 新随笔 联系 聚合 管理
  0 Posts :: 1 Stories :: 0 Comments :: 0 Trackbacks
    最近工作中,发现某些jsp页面,开头都写着如下内容,所以动手写了个过滤器来解决这个问题:
request.setCharacterEncoding("GBK"); 
response.setContentType("text/html;charset=GBK");
    过滤器代码如下:
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;
import javax.servlet.http.HttpServletResponse;

public class CharacterEncodingFilter implements Filter {

    
protected String encoding = null;
    
protected FilterConfig filterConfig = null;

    
public void destroy() {
        
this.encoding = null;
        
this.filterConfig = null;
    }

    
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        
if (request.getCharacterEncoding() == null) {
            
if (this.encoding != null){
                request.setCharacterEncoding(encoding);
                ((HttpServletResponse) response).setContentType(
"text/html; charset=" + encoding);
            }
        }
        
        chain.doFilter(request, response);

    }

    
public void init(FilterConfig filterConfig) throws ServletException {
        
this.filterConfig = filterConfig;
        
this.encoding = filterConfig.getInitParameter("encoding");
    }

}
    web.xml修改如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
    xmlns
="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation
="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.wangsoft.CharacterEncodingFilter</filter-class>
<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>

</web-app>
    此代码经过测试,欢迎大家品评,共同提高!

posted on 2007-06-19 11:31 阅读(260) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航:
博客园   IT新闻   Chat2DB   C++博客   博问