中文转码Filter

在Struts中经常会碰到中文转码的问题,最简单的办法就是直接写一个ServletFilter
代码如下:
ChineseFilter.class


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.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ChineseFilter extends HttpServlet implements Filter {

 private FilterConfig filterConfig;
     //Handle the passed-in FilterConfig
     public void init(FilterConfig filterConfig) throws ServletException {
         this.filterConfig = filterConfig;
     }
     //Process the request/response pair
     public void doFilter(ServletRequest request, ServletResponse response,
                          FilterChain filterChain) {
         try {
          
          String encoding=filterConfig.getInitParameter("encoding");//从WEB.xml配置文件中取出参数,这样我们可以通过配置修改编码格式.                  
             request.setCharacterEncoding(encoding);//设置请求的编码格式
             filterChain.doFilter(request, response);
         } catch (ServletException sx) {
             filterConfig.getServletContext().log(sx.getMessage());
         } catch (IOException iox) {
             filterConfig.getServletContext().log(iox.getMessage());
         }
     }

     //Clean up resources
     public void destroy() {
     }

  protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
   // TODO Auto-generated method stub
   super.doGet(arg0, arg1);  
  }

  protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
   // TODO Auto-generated method stub
   super.doPost(arg0, arg1);   
  } 
}

写完过滤器剩下的就是配置Web.xml了

 <filter>
  <filter-name>ChineseFilter</filter-name>
  <filter-class>com.blog.filter.ChineseFilter</filter-class>
<init-param>
    <param-name>encoding</param-name>
    <param-value>GBK</param-value> 配置编码格式,可以配置成你想要的编码(GBK,bg-2312)

</init-param>
  </filter>
   <filter-mapping>
    <filter-name>ChineseFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

好了,简单的Filter就完成了.当然也有现成的包,比如你用Struts+Spring的话,那Spring中就有现成的转码过滤器,我们只要在WEB.xml中配置一下就OK了.

<filter>
<filter-name>encodingFilter</filter-name>
 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
 <init-param>
 <param-name>encoding</param-name>
. <param-value>GBK</param-value>
 </init-param>
 </filter>
<filter-mapping>
 <filter-name>encodingFilter</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>

posted on 2006-07-08 15:21 Redish 阅读(821) 评论(0)  编辑  收藏

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


网站导航: